cos-wx-sdk-v5.js 409 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475
  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 = 6);
  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__(8);
  83. var CryptoJS = __webpack_require__(12);
  84. var xml2json = __webpack_require__(13);
  85. var json2xml = __webpack_require__(16);
  86. var base64 = __webpack_require__(3);
  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. // 如果有传入存储桶,那么签名默认加 Host 参与计算,避免跨桶访问
  154. if (!headers.Host && !headers.host && opt.Bucket && opt.Region) headers.Host = opt.Bucket + '.cos.' + opt.Region + '.myqcloud.com';
  155. if (!SecretId) return console.error('missing param SecretId');
  156. if (!SecretKey) return console.error('missing param SecretKey');
  157. // 签名有效起止时间
  158. var now = Math.round(getSkewTime(opt.SystemClockOffset) / 1000) - 1;
  159. var exp = now;
  160. var Expires = opt.Expires || opt.expires;
  161. if (Expires === undefined) {
  162. exp += 900; // 签名过期时间为当前 + 900s
  163. } else {
  164. exp += Expires * 1 || 0;
  165. }
  166. // 要用到的 Authorization 参数列表
  167. var qSignAlgorithm = 'sha1';
  168. var qAk = SecretId;
  169. var qSignTime = KeyTime || now + ';' + exp;
  170. var qKeyTime = KeyTime || now + ';' + exp;
  171. var qHeaderList = getObjectKeys(headers, true).join(';').toLowerCase();
  172. var qUrlParamList = getObjectKeys(queryParams, true).join(';').toLowerCase();
  173. // 签名算法说明文档:https://www.qcloud.com/document/product/436/7778
  174. // 步骤一:计算 SignKey
  175. var signKey = CryptoJS.HmacSHA1(qKeyTime, SecretKey).toString();
  176. // 步骤二:构成 FormatString
  177. var formatString = [method, pathname, util.obj2str(queryParams, true), util.obj2str(headers, true), ''].join('\n');
  178. // 步骤三:计算 StringToSign
  179. var stringToSign = ['sha1', qSignTime, CryptoJS.SHA1(formatString).toString(), ''].join('\n');
  180. // 步骤四:计算 Signature
  181. var qSignature = CryptoJS.HmacSHA1(stringToSign, signKey).toString();
  182. // 步骤五:构造 Authorization
  183. 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('&');
  184. return authorization;
  185. };
  186. var noop = function noop() {};
  187. // 清除对象里值为的 undefined 或 null 的属性
  188. var clearKey = function clearKey(obj) {
  189. var retObj = {};
  190. for (var key in obj) {
  191. if (obj.hasOwnProperty(key) && obj[key] !== undefined && obj[key] !== null) {
  192. retObj[key] = obj[key];
  193. }
  194. }
  195. return retObj;
  196. };
  197. // 获取文件分片
  198. var fileSlice = function fileSlice(FilePath, start, end, callback) {
  199. if (FilePath) {
  200. wxfs.readFile({
  201. filePath: FilePath,
  202. position: start,
  203. length: end - start,
  204. success: function success(res) {
  205. callback(res.data);
  206. },
  207. fail: function fail() {
  208. callback(null);
  209. }
  210. });
  211. } else {
  212. callback(null);
  213. }
  214. };
  215. // 获取文件内容的 MD5
  216. var getBodyMd5 = function getBodyMd5(UploadCheckContentMd5, Body, callback) {
  217. callback = callback || noop;
  218. if (UploadCheckContentMd5) {
  219. if (Body && Body instanceof ArrayBuffer) {
  220. util.getFileMd5(Body, function (err, md5) {
  221. callback(md5);
  222. });
  223. } else {
  224. callback();
  225. }
  226. } else {
  227. callback();
  228. }
  229. };
  230. // 获取文件 md5 值
  231. var getFileMd5 = function getFileMd5(body, callback) {
  232. var hash = md5(body);
  233. callback && callback(hash);
  234. return hash;
  235. };
  236. function clone(obj) {
  237. return map(obj, function (v) {
  238. return (typeof v === 'undefined' ? 'undefined' : _typeof(v)) === 'object' && v !== null ? clone(v) : v;
  239. });
  240. }
  241. function attr(obj, name, defaultValue) {
  242. return obj && name in obj ? obj[name] : defaultValue;
  243. }
  244. function extend(target, source) {
  245. each(source, function (val, key) {
  246. target[key] = source[key];
  247. });
  248. return target;
  249. }
  250. function isArray(arr) {
  251. return arr instanceof Array;
  252. }
  253. function isInArray(arr, item) {
  254. var flag = false;
  255. for (var i = 0; i < arr.length; i++) {
  256. if (item === arr[i]) {
  257. flag = true;
  258. break;
  259. }
  260. }
  261. return flag;
  262. }
  263. function makeArray(arr) {
  264. return isArray(arr) ? arr : [arr];
  265. }
  266. function each(obj, fn) {
  267. for (var i in obj) {
  268. if (obj.hasOwnProperty(i)) {
  269. fn(obj[i], i);
  270. }
  271. }
  272. }
  273. function map(obj, fn) {
  274. var o = isArray(obj) ? [] : {};
  275. for (var i in obj) {
  276. if (obj.hasOwnProperty(i)) {
  277. o[i] = fn(obj[i], i);
  278. }
  279. }
  280. return o;
  281. }
  282. function filter(obj, fn) {
  283. var iaArr = isArray(obj);
  284. var o = iaArr ? [] : {};
  285. for (var i in obj) {
  286. if (obj.hasOwnProperty(i)) {
  287. if (fn(obj[i], i)) {
  288. if (iaArr) {
  289. o.push(obj[i]);
  290. } else {
  291. o[i] = obj[i];
  292. }
  293. }
  294. }
  295. }
  296. return o;
  297. }
  298. var binaryBase64 = function binaryBase64(str) {
  299. var i,
  300. len,
  301. char,
  302. res = '';
  303. for (i = 0, len = str.length / 2; i < len; i++) {
  304. char = parseInt(str[i * 2] + str[i * 2 + 1], 16);
  305. res += String.fromCharCode(char);
  306. }
  307. return btoa(res);
  308. };
  309. var uuid = function uuid() {
  310. var S4 = function S4() {
  311. return ((1 + Math.random()) * 0x10000 | 0).toString(16).substring(1);
  312. };
  313. return S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4();
  314. };
  315. var hasMissingParams = function hasMissingParams(apiName, params) {
  316. var Bucket = params.Bucket;
  317. var Region = params.Region;
  318. var Key = params.Key;
  319. if (apiName.indexOf('Bucket') > -1 || apiName === 'deleteMultipleObject' || apiName === 'multipartList' || apiName === 'listObjectVersions') {
  320. if (!Bucket) return 'Bucket';
  321. if (!Region) return 'Region';
  322. } else if (apiName.indexOf('Object') > -1 || apiName.indexOf('multipart') > -1 || apiName === 'sliceUploadFile' || apiName === 'abortUploadTask') {
  323. if (!Bucket) return 'Bucket';
  324. if (!Region) return 'Region';
  325. if (!Key) return 'Key';
  326. }
  327. return false;
  328. };
  329. var formatParams = function formatParams(apiName, params) {
  330. // 复制参数对象
  331. params = extend({}, params);
  332. // 统一处理 Headers
  333. if (apiName !== 'getAuth' && apiName !== 'getV4Auth' && apiName !== 'getObjectUrl') {
  334. var Headers = params.Headers || {};
  335. if (params && (typeof params === 'undefined' ? 'undefined' : _typeof(params)) === 'object') {
  336. (function () {
  337. for (var key in params) {
  338. if (params.hasOwnProperty(key) && key.indexOf('x-cos-') > -1) {
  339. Headers[key] = params[key];
  340. }
  341. }
  342. })();
  343. var headerMap = {
  344. // params headers
  345. 'x-cos-mfa': 'MFA',
  346. 'Content-MD5': 'ContentMD5',
  347. 'Content-Length': 'ContentLength',
  348. 'Content-Type': 'ContentType',
  349. 'Expect': 'Expect',
  350. 'Expires': 'Expires',
  351. 'Cache-Control': 'CacheControl',
  352. 'Content-Disposition': 'ContentDisposition',
  353. 'Content-Encoding': 'ContentEncoding',
  354. 'Range': 'Range',
  355. 'If-Modified-Since': 'IfModifiedSince',
  356. 'If-Unmodified-Since': 'IfUnmodifiedSince',
  357. 'If-Match': 'IfMatch',
  358. 'If-None-Match': 'IfNoneMatch',
  359. 'x-cos-copy-source': 'CopySource',
  360. 'x-cos-copy-source-Range': 'CopySourceRange',
  361. 'x-cos-metadata-directive': 'MetadataDirective',
  362. 'x-cos-copy-source-If-Modified-Since': 'CopySourceIfModifiedSince',
  363. 'x-cos-copy-source-If-Unmodified-Since': 'CopySourceIfUnmodifiedSince',
  364. 'x-cos-copy-source-If-Match': 'CopySourceIfMatch',
  365. 'x-cos-copy-source-If-None-Match': 'CopySourceIfNoneMatch',
  366. 'x-cos-acl': 'ACL',
  367. 'x-cos-grant-read': 'GrantRead',
  368. 'x-cos-grant-write': 'GrantWrite',
  369. 'x-cos-grant-full-control': 'GrantFullControl',
  370. 'x-cos-grant-read-acp': 'GrantReadAcp',
  371. 'x-cos-grant-write-acp': 'GrantWriteAcp',
  372. 'x-cos-storage-class': 'StorageClass',
  373. // SSE-C
  374. 'x-cos-server-side-encryption-customer-algorithm': 'SSECustomerAlgorithm',
  375. 'x-cos-server-side-encryption-customer-key': 'SSECustomerKey',
  376. 'x-cos-server-side-encryption-customer-key-MD5': 'SSECustomerKeyMD5',
  377. // SSE-COS、SSE-KMS
  378. 'x-cos-server-side-encryption': 'ServerSideEncryption',
  379. 'x-cos-server-side-encryption-cos-kms-key-id': 'SSEKMSKeyId',
  380. 'x-cos-server-side-encryption-context': 'SSEContext'
  381. };
  382. util.each(headerMap, function (paramKey, headerKey) {
  383. if (params[paramKey] !== undefined) {
  384. Headers[headerKey] = params[paramKey];
  385. }
  386. });
  387. params.Headers = clearKey(Headers);
  388. }
  389. }
  390. return params;
  391. };
  392. var apiWrapper = function apiWrapper(apiName, apiFn) {
  393. return function (params, callback) {
  394. var self = this;
  395. // 处理参数
  396. if (typeof params === 'function') {
  397. callback = params;
  398. params = {};
  399. }
  400. // 整理参数格式
  401. params = formatParams(apiName, params);
  402. // 代理回调函数
  403. var formatResult = function formatResult(result) {
  404. if (result && result.headers) {
  405. result.headers['x-cos-version-id'] && (result.VersionId = result.headers['x-cos-version-id']);
  406. result.headers['x-cos-delete-marker'] && (result.DeleteMarker = result.headers['x-cos-delete-marker']);
  407. }
  408. return result;
  409. };
  410. var _callback = function _callback(err, data) {
  411. callback && callback(formatResult(err), formatResult(data));
  412. };
  413. var checkParams = function checkParams() {
  414. if (apiName !== 'getService' && apiName !== 'abortUploadTask') {
  415. // 判断参数是否完整
  416. var missingResult = hasMissingParams(apiName, params);
  417. if (missingResult) {
  418. return 'missing param ' + missingResult;
  419. }
  420. // 判断 region 格式
  421. if (params.Region) {
  422. if (params.Region.indexOf('cos.') > -1) {
  423. return 'param Region should not be start with "cos."';
  424. } else if (!/^([a-z\d-]+)$/.test(params.Region)) {
  425. return 'Region format error.';
  426. }
  427. // 判断 region 格式
  428. if (!self.options.CompatibilityMode && params.Region.indexOf('-') === -1 && params.Region !== 'yfb' && params.Region !== 'default' && params.Region !== 'accelerate') {
  429. console.warn('warning: param Region format error, find help here: https://cloud.tencent.com/document/product/436/6224');
  430. }
  431. }
  432. // 兼容不带 AppId 的 Bucket
  433. if (params.Bucket) {
  434. if (!/^([a-z\d-]+)-(\d+)$/.test(params.Bucket)) {
  435. if (params.AppId) {
  436. params.Bucket = params.Bucket + '-' + params.AppId;
  437. } else if (self.options.AppId) {
  438. params.Bucket = params.Bucket + '-' + self.options.AppId;
  439. } else {
  440. return 'Bucket should format as "test-1250000000".';
  441. }
  442. }
  443. if (params.AppId) {
  444. console.warn('warning: AppId has been deprecated, Please put it at the end of parameter Bucket(E.g Bucket:"test-1250000000" ).');
  445. delete params.AppId;
  446. }
  447. }
  448. // 如果 Key 是 / 开头,强制去掉第一个 /
  449. if (params.Key && params.Key.substr(0, 1) === '/') {
  450. params.Key = params.Key.substr(1);
  451. }
  452. }
  453. };
  454. var errMsg = checkParams();
  455. var isSync = apiName === 'getAuth' || apiName === 'getObjectUrl';
  456. var Promise = global.Promise;
  457. if (!isSync && Promise && !callback) {
  458. return new Promise(function (resolve, reject) {
  459. callback = function callback(err, data) {
  460. err ? reject(err) : resolve(data);
  461. };
  462. if (errMsg) return _callback({ error: errMsg });
  463. apiFn.call(self, params, _callback);
  464. });
  465. } else {
  466. if (errMsg) return _callback({ error: errMsg });
  467. var res = apiFn.call(self, params, _callback);
  468. if (isSync) return res;
  469. }
  470. };
  471. };
  472. var throttleOnProgress = function throttleOnProgress(total, onProgress) {
  473. var self = this;
  474. var size0 = 0;
  475. var size1 = 0;
  476. var time0 = Date.now();
  477. var time1;
  478. var timer;
  479. function update() {
  480. timer = 0;
  481. if (onProgress && typeof onProgress === 'function') {
  482. time1 = Date.now();
  483. var speed = Math.max(0, Math.round((size1 - size0) / ((time1 - time0) / 1000) * 100) / 100) || 0;
  484. var percent;
  485. if (size1 === 0 && total === 0) {
  486. percent = 1;
  487. } else {
  488. percent = Math.floor(size1 / total * 100) / 100 || 0;
  489. }
  490. time0 = time1;
  491. size0 = size1;
  492. try {
  493. onProgress({ loaded: size1, total: total, speed: speed, percent: percent });
  494. } catch (e) {}
  495. }
  496. }
  497. return function (info, immediately) {
  498. if (info) {
  499. size1 = info.loaded;
  500. total = info.total;
  501. }
  502. if (immediately) {
  503. clearTimeout(timer);
  504. update();
  505. } else {
  506. if (timer) return;
  507. timer = setTimeout(update, self.options.ProgressInterval);
  508. }
  509. };
  510. };
  511. var getFileSize = function getFileSize(api, params, callback) {
  512. if (api === 'postObject') {
  513. callback();
  514. } else if (api === 'putObject') {
  515. if (params.Body !== undefined) {
  516. params.ContentLength = params.Body.byteLength;
  517. callback(null, params.ContentLength);
  518. } else {
  519. callback({ error: 'missing param Body' });
  520. }
  521. } else {
  522. if (params.FilePath) {
  523. wxfs.stat({
  524. path: params.FilePath,
  525. success: function success(res) {
  526. var stats = res.stats;
  527. params.FileStat = stats;
  528. params.FileStat.FilePath = params.FilePath;
  529. var size = stats.isDirectory() ? 0 : stats.size;
  530. params.ContentLength = size = size || 0;
  531. callback(null, size);
  532. },
  533. fail: function fail(err) {
  534. callback(err);
  535. }
  536. });
  537. } else {
  538. callback({ error: 'missing param FilePath' });
  539. }
  540. }
  541. };
  542. var getSkewTime = function getSkewTime(offset) {
  543. return Date.now() + (offset || 0);
  544. };
  545. var compareVersion = function compareVersion(v1, v2) {
  546. v1 = v1.split('.');
  547. v2 = v2.split('.');
  548. var len = Math.max(v1.length, v2.length);
  549. while (v1.length < len) {
  550. v1.push('0');
  551. }
  552. while (v2.length < len) {
  553. v2.push('0');
  554. }
  555. for (var i = 0; i < len; i++) {
  556. var num1 = parseInt(v1[i]);
  557. var num2 = parseInt(v2[i]);
  558. if (num1 > num2) {
  559. return 1;
  560. } else if (num1 < num2) {
  561. return -1;
  562. }
  563. }
  564. return 0;
  565. };
  566. var canFileSlice = function () {
  567. var systemInfo = wx.getSystemInfoSync();
  568. var support = compareVersion(systemInfo.SDKVersion, '2.10.0') >= 0;
  569. var needWarning = !support && systemInfo.platform === "devtools";
  570. return function () {
  571. if (needWarning) console.warn('当前小程序版本小于 2.10.0,不支持分片上传,请更新软件。');
  572. needWarning = false;
  573. return support;
  574. };
  575. }();
  576. var isCIHost = function isCIHost(url) {
  577. return (/^https?:\/\/([^/]+\.)?ci\.[^/]+/.test(url)
  578. );
  579. };
  580. var util = {
  581. noop: noop,
  582. formatParams: formatParams,
  583. apiWrapper: apiWrapper,
  584. xml2json: xml2json,
  585. json2xml: json2xml,
  586. md5: md5,
  587. clearKey: clearKey,
  588. fileSlice: fileSlice,
  589. getBodyMd5: getBodyMd5,
  590. getFileMd5: getFileMd5,
  591. binaryBase64: binaryBase64,
  592. extend: extend,
  593. isArray: isArray,
  594. isInArray: isInArray,
  595. makeArray: makeArray,
  596. each: each,
  597. map: map,
  598. filter: filter,
  599. clone: clone,
  600. attr: attr,
  601. uuid: uuid,
  602. camSafeUrlEncode: camSafeUrlEncode,
  603. throttleOnProgress: throttleOnProgress,
  604. getFileSize: getFileSize,
  605. getSkewTime: getSkewTime,
  606. obj2str: obj2str,
  607. getAuth: getAuth,
  608. compareVersion: compareVersion,
  609. canFileSlice: canFileSlice,
  610. isCIHost: isCIHost
  611. };
  612. module.exports = util;
  613. xml2json;
  614. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1)))
  615. /***/ }),
  616. /* 1 */
  617. /***/ (function(module, exports, __webpack_require__) {
  618. "use strict";
  619. 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; };
  620. var g;
  621. // This works in non-strict mode
  622. g = function () {
  623. return this;
  624. }();
  625. try {
  626. // This works if eval is allowed (see CSP)
  627. g = g || Function("return this")() || (1, eval)("this");
  628. } catch (e) {
  629. // This works if the window reference is available
  630. if ((typeof window === "undefined" ? "undefined" : _typeof(window)) === "object") g = window;
  631. }
  632. // g can still be undefined, but nothing to do about it...
  633. // We return undefined, instead of nothing here, so it's
  634. // easier to handle this case. if(!global) { ...}
  635. module.exports = g;
  636. /***/ }),
  637. /* 2 */
  638. /***/ (function(module, exports, __webpack_require__) {
  639. "use strict";
  640. 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; };
  641. /*
  642. * DOM Level 2
  643. * Object DOMException
  644. * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
  645. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
  646. */
  647. function copy(src, dest) {
  648. for (var p in src) {
  649. dest[p] = src[p];
  650. }
  651. }
  652. /**
  653. ^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
  654. ^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
  655. */
  656. function _extends(Class, Super) {
  657. var pt = Class.prototype;
  658. if (Object.create) {
  659. var ppt = Object.create(Super.prototype);
  660. pt.__proto__ = ppt;
  661. }
  662. if (!(pt instanceof Super)) {
  663. var t = function t() {};
  664. ;
  665. t.prototype = Super.prototype;
  666. t = new t();
  667. copy(pt, t);
  668. Class.prototype = pt = t;
  669. }
  670. if (pt.constructor != Class) {
  671. if (typeof Class != 'function') {
  672. console.error("unknow Class:" + Class);
  673. }
  674. pt.constructor = Class;
  675. }
  676. }
  677. var htmlns = 'http://www.w3.org/1999/xhtml';
  678. // Node Types
  679. var NodeType = {};
  680. var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
  681. var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
  682. var TEXT_NODE = NodeType.TEXT_NODE = 3;
  683. var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
  684. var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
  685. var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
  686. var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
  687. var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
  688. var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
  689. var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
  690. var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
  691. var NOTATION_NODE = NodeType.NOTATION_NODE = 12;
  692. // ExceptionCode
  693. var ExceptionCode = {};
  694. var ExceptionMessage = {};
  695. var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = (ExceptionMessage[1] = "Index size error", 1);
  696. var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = (ExceptionMessage[2] = "DOMString size error", 2);
  697. var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = (ExceptionMessage[3] = "Hierarchy request error", 3);
  698. var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = (ExceptionMessage[4] = "Wrong document", 4);
  699. var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = (ExceptionMessage[5] = "Invalid character", 5);
  700. var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = (ExceptionMessage[6] = "No data allowed", 6);
  701. var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = (ExceptionMessage[7] = "No modification allowed", 7);
  702. var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = (ExceptionMessage[8] = "Not found", 8);
  703. var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = (ExceptionMessage[9] = "Not supported", 9);
  704. var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = (ExceptionMessage[10] = "Attribute in use", 10);
  705. //level2
  706. var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = (ExceptionMessage[11] = "Invalid state", 11);
  707. var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = (ExceptionMessage[12] = "Syntax error", 12);
  708. var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = (ExceptionMessage[13] = "Invalid modification", 13);
  709. var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = (ExceptionMessage[14] = "Invalid namespace", 14);
  710. var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = (ExceptionMessage[15] = "Invalid access", 15);
  711. function DOMException(code, message) {
  712. if (message instanceof Error) {
  713. var error = message;
  714. } else {
  715. error = this;
  716. Error.call(this, ExceptionMessage[code]);
  717. this.message = ExceptionMessage[code];
  718. if (Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
  719. }
  720. error.code = code;
  721. if (message) this.message = this.message + ": " + message;
  722. return error;
  723. };
  724. DOMException.prototype = Error.prototype;
  725. copy(ExceptionCode, DOMException);
  726. /**
  727. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
  728. * 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.
  729. * The items in the NodeList are accessible via an integral index, starting from 0.
  730. */
  731. function NodeList() {};
  732. NodeList.prototype = {
  733. /**
  734. * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
  735. * @standard level1
  736. */
  737. length: 0,
  738. /**
  739. * 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.
  740. * @standard level1
  741. * @param index unsigned long
  742. * Index into the collection.
  743. * @return Node
  744. * The node at the indexth position in the NodeList, or null if that is not a valid index.
  745. */
  746. item: function item(index) {
  747. return this[index] || null;
  748. },
  749. toString: function toString(isHTML, nodeFilter) {
  750. for (var buf = [], i = 0; i < this.length; i++) {
  751. serializeToString(this[i], buf, isHTML, nodeFilter);
  752. }
  753. return buf.join('');
  754. }
  755. };
  756. function LiveNodeList(node, refresh) {
  757. this._node = node;
  758. this._refresh = refresh;
  759. _updateLiveList(this);
  760. }
  761. function _updateLiveList(list) {
  762. var inc = list._node._inc || list._node.ownerDocument._inc;
  763. if (list._inc != inc) {
  764. var ls = list._refresh(list._node);
  765. //console.log(ls.length)
  766. __set__(list, 'length', ls.length);
  767. copy(ls, list);
  768. list._inc = inc;
  769. }
  770. }
  771. LiveNodeList.prototype.item = function (i) {
  772. _updateLiveList(this);
  773. return this[i];
  774. };
  775. _extends(LiveNodeList, NodeList);
  776. /**
  777. *
  778. * Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name. Note that NamedNodeMap does not inherit from NodeList; NamedNodeMaps are not maintained in any particular order. Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index, but this is simply to allow convenient enumeration of the contents of a NamedNodeMap, and does not imply that the DOM specifies an order to these Nodes.
  779. * NamedNodeMap objects in the DOM are live.
  780. * used for attributes or DocumentType entities
  781. */
  782. function NamedNodeMap() {};
  783. function _findNodeIndex(list, node) {
  784. var i = list.length;
  785. while (i--) {
  786. if (list[i] === node) {
  787. return i;
  788. }
  789. }
  790. }
  791. function _addNamedNode(el, list, newAttr, oldAttr) {
  792. if (oldAttr) {
  793. list[_findNodeIndex(list, oldAttr)] = newAttr;
  794. } else {
  795. list[list.length++] = newAttr;
  796. }
  797. if (el) {
  798. newAttr.ownerElement = el;
  799. var doc = el.ownerDocument;
  800. if (doc) {
  801. oldAttr && _onRemoveAttribute(doc, el, oldAttr);
  802. _onAddAttribute(doc, el, newAttr);
  803. }
  804. }
  805. }
  806. function _removeNamedNode(el, list, attr) {
  807. //console.log('remove attr:'+attr)
  808. var i = _findNodeIndex(list, attr);
  809. if (i >= 0) {
  810. var lastIndex = list.length - 1;
  811. while (i < lastIndex) {
  812. list[i] = list[++i];
  813. }
  814. list.length = lastIndex;
  815. if (el) {
  816. var doc = el.ownerDocument;
  817. if (doc) {
  818. _onRemoveAttribute(doc, el, attr);
  819. attr.ownerElement = null;
  820. }
  821. }
  822. } else {
  823. throw DOMException(NOT_FOUND_ERR, new Error(el.tagName + '@' + attr));
  824. }
  825. }
  826. NamedNodeMap.prototype = {
  827. length: 0,
  828. item: NodeList.prototype.item,
  829. getNamedItem: function getNamedItem(key) {
  830. // if(key.indexOf(':')>0 || key == 'xmlns'){
  831. // return null;
  832. // }
  833. //console.log()
  834. var i = this.length;
  835. while (i--) {
  836. var attr = this[i];
  837. //console.log(attr.nodeName,key)
  838. if (attr.nodeName == key) {
  839. return attr;
  840. }
  841. }
  842. },
  843. setNamedItem: function setNamedItem(attr) {
  844. var el = attr.ownerElement;
  845. if (el && el != this._ownerElement) {
  846. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  847. }
  848. var oldAttr = this.getNamedItem(attr.nodeName);
  849. _addNamedNode(this._ownerElement, this, attr, oldAttr);
  850. return oldAttr;
  851. },
  852. /* returns Node */
  853. setNamedItemNS: function setNamedItemNS(attr) {
  854. // raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
  855. var el = attr.ownerElement,
  856. oldAttr;
  857. if (el && el != this._ownerElement) {
  858. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  859. }
  860. oldAttr = this.getNamedItemNS(attr.namespaceURI, attr.localName);
  861. _addNamedNode(this._ownerElement, this, attr, oldAttr);
  862. return oldAttr;
  863. },
  864. /* returns Node */
  865. removeNamedItem: function removeNamedItem(key) {
  866. var attr = this.getNamedItem(key);
  867. _removeNamedNode(this._ownerElement, this, attr);
  868. return attr;
  869. }, // raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
  870. //for level2
  871. removeNamedItemNS: function removeNamedItemNS(namespaceURI, localName) {
  872. var attr = this.getNamedItemNS(namespaceURI, localName);
  873. _removeNamedNode(this._ownerElement, this, attr);
  874. return attr;
  875. },
  876. getNamedItemNS: function getNamedItemNS(namespaceURI, localName) {
  877. var i = this.length;
  878. while (i--) {
  879. var node = this[i];
  880. if (node.localName == localName && node.namespaceURI == namespaceURI) {
  881. return node;
  882. }
  883. }
  884. return null;
  885. }
  886. };
  887. /**
  888. * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490
  889. */
  890. function DOMImplementation( /* Object */features) {
  891. this._features = {};
  892. if (features) {
  893. for (var feature in features) {
  894. this._features = features[feature];
  895. }
  896. }
  897. };
  898. DOMImplementation.prototype = {
  899. hasFeature: function hasFeature( /* string */feature, /* string */version) {
  900. var versions = this._features[feature.toLowerCase()];
  901. if (versions && (!version || version in versions)) {
  902. return true;
  903. } else {
  904. return false;
  905. }
  906. },
  907. // Introduced in DOM Level 2:
  908. createDocument: function createDocument(namespaceURI, qualifiedName, doctype) {
  909. // raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR
  910. var doc = new Document();
  911. doc.implementation = this;
  912. doc.childNodes = new NodeList();
  913. doc.doctype = doctype;
  914. if (doctype) {
  915. doc.appendChild(doctype);
  916. }
  917. if (qualifiedName) {
  918. var root = doc.createElementNS(namespaceURI, qualifiedName);
  919. doc.appendChild(root);
  920. }
  921. return doc;
  922. },
  923. // Introduced in DOM Level 2:
  924. createDocumentType: function createDocumentType(qualifiedName, publicId, systemId) {
  925. // raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR
  926. var node = new DocumentType();
  927. node.name = qualifiedName;
  928. node.nodeName = qualifiedName;
  929. node.publicId = publicId;
  930. node.systemId = systemId;
  931. // Introduced in DOM Level 2:
  932. //readonly attribute DOMString internalSubset;
  933. //TODO:..
  934. // readonly attribute NamedNodeMap entities;
  935. // readonly attribute NamedNodeMap notations;
  936. return node;
  937. }
  938. };
  939. /**
  940. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
  941. */
  942. function Node() {};
  943. Node.prototype = {
  944. firstChild: null,
  945. lastChild: null,
  946. previousSibling: null,
  947. nextSibling: null,
  948. attributes: null,
  949. parentNode: null,
  950. childNodes: null,
  951. ownerDocument: null,
  952. nodeValue: null,
  953. namespaceURI: null,
  954. prefix: null,
  955. localName: null,
  956. // Modified in DOM Level 2:
  957. insertBefore: function insertBefore(newChild, refChild) {
  958. //raises
  959. return _insertBefore(this, newChild, refChild);
  960. },
  961. replaceChild: function replaceChild(newChild, oldChild) {
  962. //raises
  963. this.insertBefore(newChild, oldChild);
  964. if (oldChild) {
  965. this.removeChild(oldChild);
  966. }
  967. },
  968. removeChild: function removeChild(oldChild) {
  969. return _removeChild(this, oldChild);
  970. },
  971. appendChild: function appendChild(newChild) {
  972. return this.insertBefore(newChild, null);
  973. },
  974. hasChildNodes: function hasChildNodes() {
  975. return this.firstChild != null;
  976. },
  977. cloneNode: function cloneNode(deep) {
  978. return _cloneNode(this.ownerDocument || this, this, deep);
  979. },
  980. // Modified in DOM Level 2:
  981. normalize: function normalize() {
  982. var child = this.firstChild;
  983. while (child) {
  984. var next = child.nextSibling;
  985. if (next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE) {
  986. this.removeChild(next);
  987. child.appendData(next.data);
  988. } else {
  989. child.normalize();
  990. child = next;
  991. }
  992. }
  993. },
  994. // Introduced in DOM Level 2:
  995. isSupported: function isSupported(feature, version) {
  996. return this.ownerDocument.implementation.hasFeature(feature, version);
  997. },
  998. // Introduced in DOM Level 2:
  999. hasAttributes: function hasAttributes() {
  1000. return this.attributes.length > 0;
  1001. },
  1002. lookupPrefix: function lookupPrefix(namespaceURI) {
  1003. var el = this;
  1004. while (el) {
  1005. var map = el._nsMap;
  1006. //console.dir(map)
  1007. if (map) {
  1008. for (var n in map) {
  1009. if (map[n] == namespaceURI) {
  1010. return n;
  1011. }
  1012. }
  1013. }
  1014. el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode;
  1015. }
  1016. return null;
  1017. },
  1018. // Introduced in DOM Level 3:
  1019. lookupNamespaceURI: function lookupNamespaceURI(prefix) {
  1020. var el = this;
  1021. while (el) {
  1022. var map = el._nsMap;
  1023. //console.dir(map)
  1024. if (map) {
  1025. if (prefix in map) {
  1026. return map[prefix];
  1027. }
  1028. }
  1029. el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode;
  1030. }
  1031. return null;
  1032. },
  1033. // Introduced in DOM Level 3:
  1034. isDefaultNamespace: function isDefaultNamespace(namespaceURI) {
  1035. var prefix = this.lookupPrefix(namespaceURI);
  1036. return prefix == null;
  1037. }
  1038. };
  1039. function _xmlEncoder(c) {
  1040. return c == '<' && '&lt;' || c == '>' && '&gt;' || c == '&' && '&amp;' || c == '"' && '&quot;' || '&#' + c.charCodeAt() + ';';
  1041. }
  1042. copy(NodeType, Node);
  1043. copy(NodeType, Node.prototype);
  1044. /**
  1045. * @param callback return true for continue,false for break
  1046. * @return boolean true: break visit;
  1047. */
  1048. function _visitNode(node, callback) {
  1049. if (callback(node)) {
  1050. return true;
  1051. }
  1052. if (node = node.firstChild) {
  1053. do {
  1054. if (_visitNode(node, callback)) {
  1055. return true;
  1056. }
  1057. } while (node = node.nextSibling);
  1058. }
  1059. }
  1060. function Document() {}
  1061. function _onAddAttribute(doc, el, newAttr) {
  1062. doc && doc._inc++;
  1063. var ns = newAttr.namespaceURI;
  1064. if (ns == 'http://www.w3.org/2000/xmlns/') {
  1065. //update namespace
  1066. el._nsMap[newAttr.prefix ? newAttr.localName : ''] = newAttr.value;
  1067. }
  1068. }
  1069. function _onRemoveAttribute(doc, el, newAttr, remove) {
  1070. doc && doc._inc++;
  1071. var ns = newAttr.namespaceURI;
  1072. if (ns == 'http://www.w3.org/2000/xmlns/') {
  1073. //update namespace
  1074. delete el._nsMap[newAttr.prefix ? newAttr.localName : ''];
  1075. }
  1076. }
  1077. function _onUpdateChild(doc, el, newChild) {
  1078. if (doc && doc._inc) {
  1079. doc._inc++;
  1080. //update childNodes
  1081. var cs = el.childNodes;
  1082. if (newChild) {
  1083. cs[cs.length++] = newChild;
  1084. } else {
  1085. //console.log(1)
  1086. var child = el.firstChild;
  1087. var i = 0;
  1088. while (child) {
  1089. cs[i++] = child;
  1090. child = child.nextSibling;
  1091. }
  1092. cs.length = i;
  1093. }
  1094. }
  1095. }
  1096. /**
  1097. * attributes;
  1098. * children;
  1099. *
  1100. * writeable properties:
  1101. * nodeValue,Attr:value,CharacterData:data
  1102. * prefix
  1103. */
  1104. function _removeChild(parentNode, child) {
  1105. var previous = child.previousSibling;
  1106. var next = child.nextSibling;
  1107. if (previous) {
  1108. previous.nextSibling = next;
  1109. } else {
  1110. parentNode.firstChild = next;
  1111. }
  1112. if (next) {
  1113. next.previousSibling = previous;
  1114. } else {
  1115. parentNode.lastChild = previous;
  1116. }
  1117. _onUpdateChild(parentNode.ownerDocument, parentNode);
  1118. return child;
  1119. }
  1120. /**
  1121. * preformance key(refChild == null)
  1122. */
  1123. function _insertBefore(parentNode, newChild, nextChild) {
  1124. var cp = newChild.parentNode;
  1125. if (cp) {
  1126. cp.removeChild(newChild); //remove and update
  1127. }
  1128. if (newChild.nodeType === DOCUMENT_FRAGMENT_NODE) {
  1129. var newFirst = newChild.firstChild;
  1130. if (newFirst == null) {
  1131. return newChild;
  1132. }
  1133. var newLast = newChild.lastChild;
  1134. } else {
  1135. newFirst = newLast = newChild;
  1136. }
  1137. var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild;
  1138. newFirst.previousSibling = pre;
  1139. newLast.nextSibling = nextChild;
  1140. if (pre) {
  1141. pre.nextSibling = newFirst;
  1142. } else {
  1143. parentNode.firstChild = newFirst;
  1144. }
  1145. if (nextChild == null) {
  1146. parentNode.lastChild = newLast;
  1147. } else {
  1148. nextChild.previousSibling = newLast;
  1149. }
  1150. do {
  1151. newFirst.parentNode = parentNode;
  1152. } while (newFirst !== newLast && (newFirst = newFirst.nextSibling));
  1153. _onUpdateChild(parentNode.ownerDocument || parentNode, parentNode);
  1154. //console.log(parentNode.lastChild.nextSibling == null)
  1155. if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
  1156. newChild.firstChild = newChild.lastChild = null;
  1157. }
  1158. return newChild;
  1159. }
  1160. function _appendSingleChild(parentNode, newChild) {
  1161. var cp = newChild.parentNode;
  1162. if (cp) {
  1163. var pre = parentNode.lastChild;
  1164. cp.removeChild(newChild); //remove and update
  1165. var pre = parentNode.lastChild;
  1166. }
  1167. var pre = parentNode.lastChild;
  1168. newChild.parentNode = parentNode;
  1169. newChild.previousSibling = pre;
  1170. newChild.nextSibling = null;
  1171. if (pre) {
  1172. pre.nextSibling = newChild;
  1173. } else {
  1174. parentNode.firstChild = newChild;
  1175. }
  1176. parentNode.lastChild = newChild;
  1177. _onUpdateChild(parentNode.ownerDocument, parentNode, newChild);
  1178. return newChild;
  1179. //console.log("__aa",parentNode.lastChild.nextSibling == null)
  1180. }
  1181. Document.prototype = {
  1182. //implementation : null,
  1183. nodeName: '#document',
  1184. nodeType: DOCUMENT_NODE,
  1185. doctype: null,
  1186. documentElement: null,
  1187. _inc: 1,
  1188. insertBefore: function insertBefore(newChild, refChild) {
  1189. //raises
  1190. if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
  1191. var child = newChild.firstChild;
  1192. while (child) {
  1193. var next = child.nextSibling;
  1194. this.insertBefore(child, refChild);
  1195. child = next;
  1196. }
  1197. return newChild;
  1198. }
  1199. if (this.documentElement == null && newChild.nodeType == ELEMENT_NODE) {
  1200. this.documentElement = newChild;
  1201. }
  1202. return _insertBefore(this, newChild, refChild), newChild.ownerDocument = this, newChild;
  1203. },
  1204. removeChild: function removeChild(oldChild) {
  1205. if (this.documentElement == oldChild) {
  1206. this.documentElement = null;
  1207. }
  1208. return _removeChild(this, oldChild);
  1209. },
  1210. // Introduced in DOM Level 2:
  1211. importNode: function importNode(importedNode, deep) {
  1212. return _importNode(this, importedNode, deep);
  1213. },
  1214. // Introduced in DOM Level 2:
  1215. getElementById: function getElementById(id) {
  1216. var rtv = null;
  1217. _visitNode(this.documentElement, function (node) {
  1218. if (node.nodeType == ELEMENT_NODE) {
  1219. if (node.getAttribute('id') == id) {
  1220. rtv = node;
  1221. return true;
  1222. }
  1223. }
  1224. });
  1225. return rtv;
  1226. },
  1227. //document factory method:
  1228. createElement: function createElement(tagName) {
  1229. var node = new Element();
  1230. node.ownerDocument = this;
  1231. node.nodeName = tagName;
  1232. node.tagName = tagName;
  1233. node.childNodes = new NodeList();
  1234. var attrs = node.attributes = new NamedNodeMap();
  1235. attrs._ownerElement = node;
  1236. return node;
  1237. },
  1238. createDocumentFragment: function createDocumentFragment() {
  1239. var node = new DocumentFragment();
  1240. node.ownerDocument = this;
  1241. node.childNodes = new NodeList();
  1242. return node;
  1243. },
  1244. createTextNode: function createTextNode(data) {
  1245. var node = new Text();
  1246. node.ownerDocument = this;
  1247. node.appendData(data);
  1248. return node;
  1249. },
  1250. createComment: function createComment(data) {
  1251. var node = new Comment();
  1252. node.ownerDocument = this;
  1253. node.appendData(data);
  1254. return node;
  1255. },
  1256. createCDATASection: function createCDATASection(data) {
  1257. var node = new CDATASection();
  1258. node.ownerDocument = this;
  1259. node.appendData(data);
  1260. return node;
  1261. },
  1262. createProcessingInstruction: function createProcessingInstruction(target, data) {
  1263. var node = new ProcessingInstruction();
  1264. node.ownerDocument = this;
  1265. node.tagName = node.target = target;
  1266. node.nodeValue = node.data = data;
  1267. return node;
  1268. },
  1269. createAttribute: function createAttribute(name) {
  1270. var node = new Attr();
  1271. node.ownerDocument = this;
  1272. node.name = name;
  1273. node.nodeName = name;
  1274. node.localName = name;
  1275. node.specified = true;
  1276. return node;
  1277. },
  1278. createEntityReference: function createEntityReference(name) {
  1279. var node = new EntityReference();
  1280. node.ownerDocument = this;
  1281. node.nodeName = name;
  1282. return node;
  1283. },
  1284. // Introduced in DOM Level 2:
  1285. createElementNS: function createElementNS(namespaceURI, qualifiedName) {
  1286. var node = new Element();
  1287. var pl = qualifiedName.split(':');
  1288. var attrs = node.attributes = new NamedNodeMap();
  1289. node.childNodes = new NodeList();
  1290. node.ownerDocument = this;
  1291. node.nodeName = qualifiedName;
  1292. node.tagName = qualifiedName;
  1293. node.namespaceURI = namespaceURI;
  1294. if (pl.length == 2) {
  1295. node.prefix = pl[0];
  1296. node.localName = pl[1];
  1297. } else {
  1298. //el.prefix = null;
  1299. node.localName = qualifiedName;
  1300. }
  1301. attrs._ownerElement = node;
  1302. return node;
  1303. },
  1304. // Introduced in DOM Level 2:
  1305. createAttributeNS: function createAttributeNS(namespaceURI, qualifiedName) {
  1306. var node = new Attr();
  1307. var pl = qualifiedName.split(':');
  1308. node.ownerDocument = this;
  1309. node.nodeName = qualifiedName;
  1310. node.name = qualifiedName;
  1311. node.namespaceURI = namespaceURI;
  1312. node.specified = true;
  1313. if (pl.length == 2) {
  1314. node.prefix = pl[0];
  1315. node.localName = pl[1];
  1316. } else {
  1317. //el.prefix = null;
  1318. node.localName = qualifiedName;
  1319. }
  1320. return node;
  1321. }
  1322. };
  1323. _extends(Document, Node);
  1324. function Element() {
  1325. this._nsMap = {};
  1326. };
  1327. Element.prototype = {
  1328. nodeType: ELEMENT_NODE,
  1329. hasAttribute: function hasAttribute(name) {
  1330. return this.getAttributeNode(name) != null;
  1331. },
  1332. getAttribute: function getAttribute(name) {
  1333. var attr = this.getAttributeNode(name);
  1334. return attr && attr.value || '';
  1335. },
  1336. getAttributeNode: function getAttributeNode(name) {
  1337. return this.attributes.getNamedItem(name);
  1338. },
  1339. setAttribute: function setAttribute(name, value) {
  1340. var attr = this.ownerDocument.createAttribute(name);
  1341. attr.value = attr.nodeValue = "" + value;
  1342. this.setAttributeNode(attr);
  1343. },
  1344. removeAttribute: function removeAttribute(name) {
  1345. var attr = this.getAttributeNode(name);
  1346. attr && this.removeAttributeNode(attr);
  1347. },
  1348. //four real opeartion method
  1349. appendChild: function appendChild(newChild) {
  1350. if (newChild.nodeType === DOCUMENT_FRAGMENT_NODE) {
  1351. return this.insertBefore(newChild, null);
  1352. } else {
  1353. return _appendSingleChild(this, newChild);
  1354. }
  1355. },
  1356. setAttributeNode: function setAttributeNode(newAttr) {
  1357. return this.attributes.setNamedItem(newAttr);
  1358. },
  1359. setAttributeNodeNS: function setAttributeNodeNS(newAttr) {
  1360. return this.attributes.setNamedItemNS(newAttr);
  1361. },
  1362. removeAttributeNode: function removeAttributeNode(oldAttr) {
  1363. //console.log(this == oldAttr.ownerElement)
  1364. return this.attributes.removeNamedItem(oldAttr.nodeName);
  1365. },
  1366. //get real attribute name,and remove it by removeAttributeNode
  1367. removeAttributeNS: function removeAttributeNS(namespaceURI, localName) {
  1368. var old = this.getAttributeNodeNS(namespaceURI, localName);
  1369. old && this.removeAttributeNode(old);
  1370. },
  1371. hasAttributeNS: function hasAttributeNS(namespaceURI, localName) {
  1372. return this.getAttributeNodeNS(namespaceURI, localName) != null;
  1373. },
  1374. getAttributeNS: function getAttributeNS(namespaceURI, localName) {
  1375. var attr = this.getAttributeNodeNS(namespaceURI, localName);
  1376. return attr && attr.value || '';
  1377. },
  1378. setAttributeNS: function setAttributeNS(namespaceURI, qualifiedName, value) {
  1379. var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
  1380. attr.value = attr.nodeValue = "" + value;
  1381. this.setAttributeNode(attr);
  1382. },
  1383. getAttributeNodeNS: function getAttributeNodeNS(namespaceURI, localName) {
  1384. return this.attributes.getNamedItemNS(namespaceURI, localName);
  1385. },
  1386. getElementsByTagName: function getElementsByTagName(tagName) {
  1387. return new LiveNodeList(this, function (base) {
  1388. var ls = [];
  1389. _visitNode(base, function (node) {
  1390. if (node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)) {
  1391. ls.push(node);
  1392. }
  1393. });
  1394. return ls;
  1395. });
  1396. },
  1397. getElementsByTagNameNS: function getElementsByTagNameNS(namespaceURI, localName) {
  1398. return new LiveNodeList(this, function (base) {
  1399. var ls = [];
  1400. _visitNode(base, function (node) {
  1401. if (node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)) {
  1402. ls.push(node);
  1403. }
  1404. });
  1405. return ls;
  1406. });
  1407. }
  1408. };
  1409. Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
  1410. Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
  1411. _extends(Element, Node);
  1412. function Attr() {};
  1413. Attr.prototype.nodeType = ATTRIBUTE_NODE;
  1414. _extends(Attr, Node);
  1415. function CharacterData() {};
  1416. CharacterData.prototype = {
  1417. data: '',
  1418. substringData: function substringData(offset, count) {
  1419. return this.data.substring(offset, offset + count);
  1420. },
  1421. appendData: function appendData(text) {
  1422. text = this.data + text;
  1423. this.nodeValue = this.data = text;
  1424. this.length = text.length;
  1425. },
  1426. insertData: function insertData(offset, text) {
  1427. this.replaceData(offset, 0, text);
  1428. },
  1429. appendChild: function appendChild(newChild) {
  1430. throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR]);
  1431. },
  1432. deleteData: function deleteData(offset, count) {
  1433. this.replaceData(offset, count, "");
  1434. },
  1435. replaceData: function replaceData(offset, count, text) {
  1436. var start = this.data.substring(0, offset);
  1437. var end = this.data.substring(offset + count);
  1438. text = start + text + end;
  1439. this.nodeValue = this.data = text;
  1440. this.length = text.length;
  1441. }
  1442. };
  1443. _extends(CharacterData, Node);
  1444. function Text() {};
  1445. Text.prototype = {
  1446. nodeName: "#text",
  1447. nodeType: TEXT_NODE,
  1448. splitText: function splitText(offset) {
  1449. var text = this.data;
  1450. var newText = text.substring(offset);
  1451. text = text.substring(0, offset);
  1452. this.data = this.nodeValue = text;
  1453. this.length = text.length;
  1454. var newNode = this.ownerDocument.createTextNode(newText);
  1455. if (this.parentNode) {
  1456. this.parentNode.insertBefore(newNode, this.nextSibling);
  1457. }
  1458. return newNode;
  1459. }
  1460. };
  1461. _extends(Text, CharacterData);
  1462. function Comment() {};
  1463. Comment.prototype = {
  1464. nodeName: "#comment",
  1465. nodeType: COMMENT_NODE
  1466. };
  1467. _extends(Comment, CharacterData);
  1468. function CDATASection() {};
  1469. CDATASection.prototype = {
  1470. nodeName: "#cdata-section",
  1471. nodeType: CDATA_SECTION_NODE
  1472. };
  1473. _extends(CDATASection, CharacterData);
  1474. function DocumentType() {};
  1475. DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
  1476. _extends(DocumentType, Node);
  1477. function Notation() {};
  1478. Notation.prototype.nodeType = NOTATION_NODE;
  1479. _extends(Notation, Node);
  1480. function Entity() {};
  1481. Entity.prototype.nodeType = ENTITY_NODE;
  1482. _extends(Entity, Node);
  1483. function EntityReference() {};
  1484. EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
  1485. _extends(EntityReference, Node);
  1486. function DocumentFragment() {};
  1487. DocumentFragment.prototype.nodeName = "#document-fragment";
  1488. DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
  1489. _extends(DocumentFragment, Node);
  1490. function ProcessingInstruction() {}
  1491. ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
  1492. _extends(ProcessingInstruction, Node);
  1493. function XMLSerializer() {}
  1494. XMLSerializer.prototype.serializeToString = function (node, isHtml, nodeFilter) {
  1495. return nodeSerializeToString.call(node, isHtml, nodeFilter);
  1496. };
  1497. Node.prototype.toString = nodeSerializeToString;
  1498. function nodeSerializeToString(isHtml, nodeFilter) {
  1499. var buf = [];
  1500. var refNode = this.nodeType == 9 ? this.documentElement : this;
  1501. var prefix = refNode.prefix;
  1502. var uri = refNode.namespaceURI;
  1503. if (uri && prefix == null) {
  1504. //console.log(prefix)
  1505. var prefix = refNode.lookupPrefix(uri);
  1506. if (prefix == null) {
  1507. //isHTML = true;
  1508. var visibleNamespaces = [{ namespace: uri, prefix: null
  1509. //{namespace:uri,prefix:''}
  1510. }];
  1511. }
  1512. }
  1513. serializeToString(this, buf, isHtml, nodeFilter, visibleNamespaces);
  1514. //console.log('###',this.nodeType,uri,prefix,buf.join(''))
  1515. return buf.join('');
  1516. }
  1517. function needNamespaceDefine(node, isHTML, visibleNamespaces) {
  1518. var prefix = node.prefix || '';
  1519. var uri = node.namespaceURI;
  1520. if (!prefix && !uri) {
  1521. return false;
  1522. }
  1523. if (prefix === "xml" && uri === "http://www.w3.org/XML/1998/namespace" || uri == 'http://www.w3.org/2000/xmlns/') {
  1524. return false;
  1525. }
  1526. var i = visibleNamespaces.length;
  1527. //console.log('@@@@',node.tagName,prefix,uri,visibleNamespaces)
  1528. while (i--) {
  1529. var ns = visibleNamespaces[i];
  1530. // get namespace prefix
  1531. //console.log(node.nodeType,node.tagName,ns.prefix,prefix)
  1532. if (ns.prefix == prefix) {
  1533. return ns.namespace != uri;
  1534. }
  1535. }
  1536. //console.log(isHTML,uri,prefix=='')
  1537. //if(isHTML && prefix ==null && uri == 'http://www.w3.org/1999/xhtml'){
  1538. // return false;
  1539. //}
  1540. //node.flag = '11111'
  1541. //console.error(3,true,node.flag,node.prefix,node.namespaceURI)
  1542. return true;
  1543. }
  1544. function serializeToString(node, buf, isHTML, nodeFilter, visibleNamespaces) {
  1545. if (nodeFilter) {
  1546. node = nodeFilter(node);
  1547. if (node) {
  1548. if (typeof node == 'string') {
  1549. buf.push(node);
  1550. return;
  1551. }
  1552. } else {
  1553. return;
  1554. }
  1555. //buf.sort.apply(attrs, attributeSorter);
  1556. }
  1557. switch (node.nodeType) {
  1558. case ELEMENT_NODE:
  1559. if (!visibleNamespaces) visibleNamespaces = [];
  1560. var startVisibleNamespaces = visibleNamespaces.length;
  1561. var attrs = node.attributes;
  1562. var len = attrs.length;
  1563. var child = node.firstChild;
  1564. var nodeName = node.tagName;
  1565. isHTML = htmlns === node.namespaceURI || isHTML;
  1566. buf.push('<', nodeName);
  1567. for (var i = 0; i < len; i++) {
  1568. // add namespaces for attributes
  1569. var attr = attrs.item(i);
  1570. if (attr.prefix == 'xmlns') {
  1571. visibleNamespaces.push({ prefix: attr.localName, namespace: attr.value });
  1572. } else if (attr.nodeName == 'xmlns') {
  1573. visibleNamespaces.push({ prefix: '', namespace: attr.value });
  1574. }
  1575. }
  1576. for (var i = 0; i < len; i++) {
  1577. var attr = attrs.item(i);
  1578. if (needNamespaceDefine(attr, isHTML, visibleNamespaces)) {
  1579. var prefix = attr.prefix || '';
  1580. var uri = attr.namespaceURI;
  1581. var ns = prefix ? ' xmlns:' + prefix : " xmlns";
  1582. buf.push(ns, '="', uri, '"');
  1583. visibleNamespaces.push({ prefix: prefix, namespace: uri });
  1584. }
  1585. serializeToString(attr, buf, isHTML, nodeFilter, visibleNamespaces);
  1586. }
  1587. // add namespace for current node
  1588. if (needNamespaceDefine(node, isHTML, visibleNamespaces)) {
  1589. var prefix = node.prefix || '';
  1590. var uri = node.namespaceURI;
  1591. var ns = prefix ? ' xmlns:' + prefix : " xmlns";
  1592. buf.push(ns, '="', uri, '"');
  1593. visibleNamespaces.push({ prefix: prefix, namespace: uri });
  1594. }
  1595. if (child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)) {
  1596. buf.push('>');
  1597. //if is cdata child node
  1598. if (isHTML && /^script$/i.test(nodeName)) {
  1599. while (child) {
  1600. if (child.data) {
  1601. buf.push(child.data);
  1602. } else {
  1603. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces);
  1604. }
  1605. child = child.nextSibling;
  1606. }
  1607. } else {
  1608. while (child) {
  1609. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces);
  1610. child = child.nextSibling;
  1611. }
  1612. }
  1613. buf.push('</', nodeName, '>');
  1614. } else {
  1615. buf.push('/>');
  1616. }
  1617. // remove added visible namespaces
  1618. //visibleNamespaces.length = startVisibleNamespaces;
  1619. return;
  1620. case DOCUMENT_NODE:
  1621. case DOCUMENT_FRAGMENT_NODE:
  1622. var child = node.firstChild;
  1623. while (child) {
  1624. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces);
  1625. child = child.nextSibling;
  1626. }
  1627. return;
  1628. case ATTRIBUTE_NODE:
  1629. return buf.push(' ', node.name, '="', node.value.replace(/[<&"]/g, _xmlEncoder), '"');
  1630. case TEXT_NODE:
  1631. return buf.push(node.data.replace(/[<&]/g, _xmlEncoder));
  1632. case CDATA_SECTION_NODE:
  1633. return buf.push('<![CDATA[', node.data, ']]>');
  1634. case COMMENT_NODE:
  1635. return buf.push("<!--", node.data, "-->");
  1636. case DOCUMENT_TYPE_NODE:
  1637. var pubid = node.publicId;
  1638. var sysid = node.systemId;
  1639. buf.push('<!DOCTYPE ', node.name);
  1640. if (pubid) {
  1641. buf.push(' PUBLIC "', pubid);
  1642. if (sysid && sysid != '.') {
  1643. buf.push('" "', sysid);
  1644. }
  1645. buf.push('">');
  1646. } else if (sysid && sysid != '.') {
  1647. buf.push(' SYSTEM "', sysid, '">');
  1648. } else {
  1649. var sub = node.internalSubset;
  1650. if (sub) {
  1651. buf.push(" [", sub, "]");
  1652. }
  1653. buf.push(">");
  1654. }
  1655. return;
  1656. case PROCESSING_INSTRUCTION_NODE:
  1657. return buf.push("<?", node.target, " ", node.data, "?>");
  1658. case ENTITY_REFERENCE_NODE:
  1659. return buf.push('&', node.nodeName, ';');
  1660. //case ENTITY_NODE:
  1661. //case NOTATION_NODE:
  1662. default:
  1663. buf.push('??', node.nodeName);
  1664. }
  1665. }
  1666. function _importNode(doc, node, deep) {
  1667. var node2;
  1668. switch (node.nodeType) {
  1669. case ELEMENT_NODE:
  1670. node2 = node.cloneNode(false);
  1671. node2.ownerDocument = doc;
  1672. //var attrs = node2.attributes;
  1673. //var len = attrs.length;
  1674. //for(var i=0;i<len;i++){
  1675. //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
  1676. //}
  1677. case DOCUMENT_FRAGMENT_NODE:
  1678. break;
  1679. case ATTRIBUTE_NODE:
  1680. deep = true;
  1681. break;
  1682. //case ENTITY_REFERENCE_NODE:
  1683. //case PROCESSING_INSTRUCTION_NODE:
  1684. ////case TEXT_NODE:
  1685. //case CDATA_SECTION_NODE:
  1686. //case COMMENT_NODE:
  1687. // deep = false;
  1688. // break;
  1689. //case DOCUMENT_NODE:
  1690. //case DOCUMENT_TYPE_NODE:
  1691. //cannot be imported.
  1692. //case ENTITY_NODE:
  1693. //case NOTATION_NODE:
  1694. //can not hit in level3
  1695. //default:throw e;
  1696. }
  1697. if (!node2) {
  1698. node2 = node.cloneNode(false); //false
  1699. }
  1700. node2.ownerDocument = doc;
  1701. node2.parentNode = null;
  1702. if (deep) {
  1703. var child = node.firstChild;
  1704. while (child) {
  1705. node2.appendChild(_importNode(doc, child, deep));
  1706. child = child.nextSibling;
  1707. }
  1708. }
  1709. return node2;
  1710. }
  1711. //
  1712. //var _relationMap = {firstChild:1,lastChild:1,previousSibling:1,nextSibling:1,
  1713. // attributes:1,childNodes:1,parentNode:1,documentElement:1,doctype,};
  1714. function _cloneNode(doc, node, deep) {
  1715. var node2 = new node.constructor();
  1716. for (var n in node) {
  1717. var v = node[n];
  1718. if ((typeof v === 'undefined' ? 'undefined' : _typeof(v)) != 'object') {
  1719. if (v != node2[n]) {
  1720. node2[n] = v;
  1721. }
  1722. }
  1723. }
  1724. if (node.childNodes) {
  1725. node2.childNodes = new NodeList();
  1726. }
  1727. node2.ownerDocument = doc;
  1728. switch (node2.nodeType) {
  1729. case ELEMENT_NODE:
  1730. var attrs = node.attributes;
  1731. var attrs2 = node2.attributes = new NamedNodeMap();
  1732. var len = attrs.length;
  1733. attrs2._ownerElement = node2;
  1734. for (var i = 0; i < len; i++) {
  1735. node2.setAttributeNode(_cloneNode(doc, attrs.item(i), true));
  1736. }
  1737. break;;
  1738. case ATTRIBUTE_NODE:
  1739. deep = true;
  1740. }
  1741. if (deep) {
  1742. var child = node.firstChild;
  1743. while (child) {
  1744. node2.appendChild(_cloneNode(doc, child, deep));
  1745. child = child.nextSibling;
  1746. }
  1747. }
  1748. return node2;
  1749. }
  1750. function __set__(object, key, value) {
  1751. object[key] = value;
  1752. }
  1753. //do dynamic
  1754. try {
  1755. if (Object.defineProperty) {
  1756. var getTextContent = function getTextContent(node) {
  1757. switch (node.nodeType) {
  1758. case ELEMENT_NODE:
  1759. case DOCUMENT_FRAGMENT_NODE:
  1760. var buf = [];
  1761. node = node.firstChild;
  1762. while (node) {
  1763. if (node.nodeType !== 7 && node.nodeType !== 8) {
  1764. buf.push(getTextContent(node));
  1765. }
  1766. node = node.nextSibling;
  1767. }
  1768. return buf.join('');
  1769. default:
  1770. return node.nodeValue;
  1771. }
  1772. };
  1773. Object.defineProperty(LiveNodeList.prototype, 'length', {
  1774. get: function get() {
  1775. _updateLiveList(this);
  1776. return this.$$length;
  1777. }
  1778. });
  1779. Object.defineProperty(Node.prototype, 'textContent', {
  1780. get: function get() {
  1781. return getTextContent(this);
  1782. },
  1783. set: function set(data) {
  1784. switch (this.nodeType) {
  1785. case ELEMENT_NODE:
  1786. case DOCUMENT_FRAGMENT_NODE:
  1787. while (this.firstChild) {
  1788. this.removeChild(this.firstChild);
  1789. }
  1790. if (data || String(data)) {
  1791. this.appendChild(this.ownerDocument.createTextNode(data));
  1792. }
  1793. break;
  1794. default:
  1795. //TODO:
  1796. this.data = data;
  1797. this.value = data;
  1798. this.nodeValue = data;
  1799. }
  1800. }
  1801. });
  1802. __set__ = function __set__(object, key, value) {
  1803. //console.log(value)
  1804. object['$$' + key] = value;
  1805. };
  1806. }
  1807. } catch (e) {} //ie8
  1808. //if(typeof require == 'function'){
  1809. exports.DOMImplementation = DOMImplementation;
  1810. exports.XMLSerializer = XMLSerializer;
  1811. //}
  1812. /***/ }),
  1813. /* 3 */
  1814. /***/ (function(module, exports, __webpack_require__) {
  1815. "use strict";
  1816. /*
  1817. * $Id: base64.js,v 2.15 2014/04/05 12:58:57 dankogai Exp dankogai $
  1818. *
  1819. * Licensed under the BSD 3-Clause License.
  1820. * http://opensource.org/licenses/BSD-3-Clause
  1821. *
  1822. * References:
  1823. * http://en.wikipedia.org/wiki/Base64
  1824. */
  1825. var Base64 = function (global) {
  1826. global = global || {};
  1827. 'use strict';
  1828. // existing version for noConflict()
  1829. var _Base64 = global.Base64;
  1830. var version = "2.1.9";
  1831. // if node.js, we use Buffer
  1832. var buffer;
  1833. // constants
  1834. var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  1835. var b64tab = function (bin) {
  1836. var t = {};
  1837. for (var i = 0, l = bin.length; i < l; i++) {
  1838. t[bin.charAt(i)] = i;
  1839. }return t;
  1840. }(b64chars);
  1841. var fromCharCode = String.fromCharCode;
  1842. // encoder stuff
  1843. var cb_utob = function cb_utob(c) {
  1844. if (c.length < 2) {
  1845. var cc = c.charCodeAt(0);
  1846. 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);
  1847. } else {
  1848. var cc = 0x10000 + (c.charCodeAt(0) - 0xD800) * 0x400 + (c.charCodeAt(1) - 0xDC00);
  1849. return fromCharCode(0xf0 | cc >>> 18 & 0x07) + fromCharCode(0x80 | cc >>> 12 & 0x3f) + fromCharCode(0x80 | cc >>> 6 & 0x3f) + fromCharCode(0x80 | cc & 0x3f);
  1850. }
  1851. };
  1852. var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
  1853. var utob = function utob(u) {
  1854. return u.replace(re_utob, cb_utob);
  1855. };
  1856. var cb_encode = function cb_encode(ccc) {
  1857. var padlen = [0, 2, 1][ccc.length % 3],
  1858. ord = ccc.charCodeAt(0) << 16 | (ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8 | (ccc.length > 2 ? ccc.charCodeAt(2) : 0),
  1859. chars = [b64chars.charAt(ord >>> 18), b64chars.charAt(ord >>> 12 & 63), padlen >= 2 ? '=' : b64chars.charAt(ord >>> 6 & 63), padlen >= 1 ? '=' : b64chars.charAt(ord & 63)];
  1860. return chars.join('');
  1861. };
  1862. var btoa = global.btoa ? function (b) {
  1863. return global.btoa(b);
  1864. } : function (b) {
  1865. return b.replace(/[\s\S]{1,3}/g, cb_encode);
  1866. };
  1867. var _encode = buffer ? function (u) {
  1868. return (u.constructor === buffer.constructor ? u : new buffer(u)).toString('base64');
  1869. } : function (u) {
  1870. return btoa(utob(u));
  1871. };
  1872. var encode = function encode(u, urisafe) {
  1873. return !urisafe ? _encode(String(u)) : _encode(String(u)).replace(/[+\/]/g, function (m0) {
  1874. return m0 == '+' ? '-' : '_';
  1875. }).replace(/=/g, '');
  1876. };
  1877. var encodeURI = function encodeURI(u) {
  1878. return encode(u, true);
  1879. };
  1880. // decoder stuff
  1881. var re_btou = new RegExp(['[\xC0-\xDF][\x80-\xBF]', '[\xE0-\xEF][\x80-\xBF]{2}', '[\xF0-\xF7][\x80-\xBF]{3}'].join('|'), 'g');
  1882. var cb_btou = function cb_btou(cccc) {
  1883. switch (cccc.length) {
  1884. case 4:
  1885. var cp = (0x07 & cccc.charCodeAt(0)) << 18 | (0x3f & cccc.charCodeAt(1)) << 12 | (0x3f & cccc.charCodeAt(2)) << 6 | 0x3f & cccc.charCodeAt(3),
  1886. offset = cp - 0x10000;
  1887. return fromCharCode((offset >>> 10) + 0xD800) + fromCharCode((offset & 0x3FF) + 0xDC00);
  1888. case 3:
  1889. return fromCharCode((0x0f & cccc.charCodeAt(0)) << 12 | (0x3f & cccc.charCodeAt(1)) << 6 | 0x3f & cccc.charCodeAt(2));
  1890. default:
  1891. return fromCharCode((0x1f & cccc.charCodeAt(0)) << 6 | 0x3f & cccc.charCodeAt(1));
  1892. }
  1893. };
  1894. var btou = function btou(b) {
  1895. return b.replace(re_btou, cb_btou);
  1896. };
  1897. var cb_decode = function cb_decode(cccc) {
  1898. var len = cccc.length,
  1899. padlen = len % 4,
  1900. 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),
  1901. chars = [fromCharCode(n >>> 16), fromCharCode(n >>> 8 & 0xff), fromCharCode(n & 0xff)];
  1902. chars.length -= [0, 0, 2, 1][padlen];
  1903. return chars.join('');
  1904. };
  1905. var atob = global.atob ? function (a) {
  1906. return global.atob(a);
  1907. } : function (a) {
  1908. return a.replace(/[\s\S]{1,4}/g, cb_decode);
  1909. };
  1910. var _decode = buffer ? function (a) {
  1911. return (a.constructor === buffer.constructor ? a : new buffer(a, 'base64')).toString();
  1912. } : function (a) {
  1913. return btou(atob(a));
  1914. };
  1915. var decode = function decode(a) {
  1916. return _decode(String(a).replace(/[-_]/g, function (m0) {
  1917. return m0 == '-' ? '+' : '/';
  1918. }).replace(/[^A-Za-z0-9\+\/]/g, ''));
  1919. };
  1920. var noConflict = function noConflict() {
  1921. var Base64 = global.Base64;
  1922. global.Base64 = _Base64;
  1923. return Base64;
  1924. };
  1925. // export Base64
  1926. var Base64 = {
  1927. VERSION: version,
  1928. atob: atob,
  1929. btoa: btoa,
  1930. fromBase64: decode,
  1931. toBase64: encode,
  1932. utob: utob,
  1933. encode: encode,
  1934. encodeURI: encodeURI,
  1935. btou: btou,
  1936. decode: decode,
  1937. noConflict: noConflict
  1938. };
  1939. return Base64;
  1940. }();
  1941. module.exports = Base64;
  1942. /***/ }),
  1943. /* 4 */
  1944. /***/ (function(module, exports, __webpack_require__) {
  1945. "use strict";
  1946. var initEvent = function initEvent(cos) {
  1947. var listeners = {};
  1948. var getList = function getList(action) {
  1949. !listeners[action] && (listeners[action] = []);
  1950. return listeners[action];
  1951. };
  1952. cos.on = function (action, callback) {
  1953. getList(action).push(callback);
  1954. };
  1955. cos.off = function (action, callback) {
  1956. var list = getList(action);
  1957. for (var i = list.length - 1; i >= 0; i--) {
  1958. callback === list[i] && list.splice(i, 1);
  1959. }
  1960. };
  1961. cos.emit = function (action, data) {
  1962. var list = getList(action).map(function (cb) {
  1963. return cb;
  1964. });
  1965. for (var i = 0; i < list.length; i++) {
  1966. list[i](data);
  1967. }
  1968. };
  1969. };
  1970. var EventProxy = function EventProxy() {
  1971. initEvent(this);
  1972. };
  1973. module.exports.init = initEvent;
  1974. module.exports.EventProxy = EventProxy;
  1975. /***/ }),
  1976. /* 5 */
  1977. /***/ (function(module, exports, __webpack_require__) {
  1978. "use strict";
  1979. var util = __webpack_require__(0);
  1980. // 按照文件特征值,缓存 UploadId
  1981. var cacheKey = 'cos_sdk_upload_cache';
  1982. var expires = 30 * 24 * 3600;
  1983. var cache;
  1984. var timer;
  1985. var getCache = function getCache() {
  1986. try {
  1987. var val = JSON.parse(wx.getStorageSync(cacheKey));
  1988. } catch (e) {}
  1989. if (!val) val = [];
  1990. return val;
  1991. };
  1992. var setCache = function setCache() {
  1993. try {
  1994. wx.setStorageSync(cacheKey, JSON.stringify(cache));
  1995. } catch (e) {}
  1996. };
  1997. var init = function init() {
  1998. if (cache) return;
  1999. cache = getCache();
  2000. // 清理太老旧的数据
  2001. var changed = false;
  2002. var now = Math.round(Date.now() / 1000);
  2003. for (var i = cache.length - 1; i >= 0; i--) {
  2004. var mtime = cache[i][2];
  2005. if (!mtime || mtime + expires < now) {
  2006. cache.splice(i, 1);
  2007. changed = true;
  2008. }
  2009. }
  2010. changed && setCache();
  2011. };
  2012. // 把缓存存到本地
  2013. var save = function save() {
  2014. if (timer) return;
  2015. timer = setTimeout(function () {
  2016. setCache();
  2017. timer = null;
  2018. }, 400);
  2019. };
  2020. var mod = {
  2021. using: {},
  2022. // 标记 UploadId 正在使用
  2023. setUsing: function setUsing(uuid) {
  2024. mod.using[uuid] = true;
  2025. },
  2026. // 标记 UploadId 已经没在使用
  2027. removeUsing: function removeUsing(uuid) {
  2028. delete mod.using[uuid];
  2029. },
  2030. // 用上传参数生成哈希值
  2031. getFileId: function getFileId(FileStat, ChunkSize, Bucket, Key) {
  2032. if (FileStat.FilePath && FileStat.size && FileStat.lastModifiedTime && ChunkSize) {
  2033. return util.md5([FileStat.FilePath].join('::')) + '-' + util.md5([FileStat.size, FileStat.mode, FileStat.lastAccessedTime, FileStat.lastModifiedTime, ChunkSize, Bucket, Key].join('::'));
  2034. } else {
  2035. return null;
  2036. }
  2037. },
  2038. // 获取文件对应的 UploadId 列表
  2039. getUploadIdList: function getUploadIdList(uuid) {
  2040. if (!uuid) return null;
  2041. init();
  2042. var list = [];
  2043. for (var i = 0; i < cache.length; i++) {
  2044. if (cache[i][0] === uuid) list.push(cache[i][1]);
  2045. }
  2046. return list.length ? list : null;
  2047. },
  2048. // 缓存 UploadId
  2049. saveUploadId: function saveUploadId(uuid, UploadId, limit) {
  2050. init();
  2051. if (!uuid) return;
  2052. // 清理没用的 UploadId
  2053. var part1 = uuid.substr(0, uuid.indexOf('-') + 1);
  2054. for (var i = cache.length - 1; i >= 0; i--) {
  2055. var item = cache[i];
  2056. if (item[0] === uuid && item[1] === UploadId) {
  2057. cache.splice(i, 1);
  2058. } else if (uuid !== item[0] && item[0].indexOf(part1) === 0) {
  2059. // 文件路径相同,但其他信息不同,说明文件改变了或上传参数(存储桶、路径、分片大小)变了,直接清理掉
  2060. cache.splice(i, 1);
  2061. }
  2062. }
  2063. cache.unshift([uuid, UploadId, Math.round(Date.now() / 1000)]);
  2064. if (cache.length > limit) cache.splice(limit);
  2065. save();
  2066. },
  2067. // UploadId 已用完,移除掉
  2068. removeUploadId: function removeUploadId(UploadId) {
  2069. init();
  2070. delete mod.using[UploadId];
  2071. for (var i = cache.length - 1; i >= 0; i--) {
  2072. if (cache[i][1] === UploadId) cache.splice(i, 1);
  2073. }
  2074. save();
  2075. }
  2076. };
  2077. module.exports = mod;
  2078. /***/ }),
  2079. /* 6 */
  2080. /***/ (function(module, exports, __webpack_require__) {
  2081. "use strict";
  2082. var COS = __webpack_require__(7);
  2083. module.exports = COS;
  2084. /***/ }),
  2085. /* 7 */
  2086. /***/ (function(module, exports, __webpack_require__) {
  2087. "use strict";
  2088. var util = __webpack_require__(0);
  2089. var event = __webpack_require__(4);
  2090. var task = __webpack_require__(17);
  2091. var base = __webpack_require__(18);
  2092. var advance = __webpack_require__(24);
  2093. var defaultOptions = {
  2094. SecretId: '',
  2095. SecretKey: '',
  2096. XCosSecurityToken: '', // 使用临时密钥需要注意自行刷新 Token
  2097. ChunkRetryTimes: 2,
  2098. FileParallelLimit: 3,
  2099. ChunkParallelLimit: 3,
  2100. ChunkSize: 1024 * 1024,
  2101. SliceSize: 1024 * 1024,
  2102. CopyChunkParallelLimit: 20,
  2103. CopyChunkSize: 1024 * 1024 * 10,
  2104. CopySliceSize: 1024 * 1024 * 10,
  2105. MaxPartNumber: 10000,
  2106. ProgressInterval: 1000,
  2107. UploadQueueSize: 10000,
  2108. Domain: '',
  2109. ServiceDomain: '',
  2110. Protocol: '',
  2111. CompatibilityMode: false,
  2112. ForcePathStyle: false,
  2113. Timeout: 0, // 单位毫秒,0 代表不设置超时时间
  2114. CorrectClockSkew: true,
  2115. SystemClockOffset: 0, // 单位毫秒,ms
  2116. UploadCheckContentMd5: false,
  2117. UploadIdCacheLimit: 50,
  2118. UseAccelerate: false
  2119. };
  2120. // 对外暴露的类
  2121. var COS = function COS(options) {
  2122. this.options = util.extend(util.clone(defaultOptions), options || {});
  2123. this.options.FileParallelLimit = Math.max(1, this.options.FileParallelLimit);
  2124. this.options.ChunkParallelLimit = Math.max(1, this.options.ChunkParallelLimit);
  2125. this.options.ChunkRetryTimes = Math.max(0, this.options.ChunkRetryTimes);
  2126. this.options.ChunkSize = Math.max(1024 * 1024, this.options.ChunkSize);
  2127. this.options.CopyChunkParallelLimit = Math.max(1, this.options.CopyChunkParallelLimit);
  2128. this.options.CopyChunkSize = Math.max(1024 * 1024, this.options.CopyChunkSize);
  2129. this.options.CopySliceSize = Math.max(0, this.options.CopySliceSize);
  2130. this.options.MaxPartNumber = Math.max(1024, Math.min(10000, this.options.MaxPartNumber));
  2131. this.options.Timeout = Math.max(0, this.options.Timeout);
  2132. if (this.options.AppId) {
  2133. console.warn('warning: AppId has been deprecated, Please put it at the end of parameter Bucket(E.g: "test-1250000000").');
  2134. }
  2135. if (this.options.SecretId && this.options.SecretId.indexOf(' ') > -1) {
  2136. console.error('error: SecretId格式错误,请检查');
  2137. console.error('error: SecretId format is incorrect. Please check');
  2138. }
  2139. if (this.options.SecretKey && this.options.SecretKey.indexOf(' ') > -1) {
  2140. console.error('error: SecretKey格式错误,请检查');
  2141. console.error('error: SecretKey format is incorrect. Please check');
  2142. }
  2143. event.init(this);
  2144. task.init(this);
  2145. };
  2146. base.init(COS, task);
  2147. advance.init(COS, task);
  2148. COS.getAuthorization = util.getAuth;
  2149. COS.version = '1.1.5';
  2150. module.exports = COS;
  2151. /***/ }),
  2152. /* 8 */
  2153. /***/ (function(module, exports, __webpack_require__) {
  2154. "use strict";
  2155. /* WEBPACK VAR INJECTION */(function(process, global, module) {var __WEBPACK_AMD_DEFINE_RESULT__;
  2156. 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; };
  2157. /* https://github.com/emn178/js-md5 */
  2158. (function () {
  2159. 'use strict';
  2160. var ERROR = 'input is invalid type';
  2161. var WINDOW = (typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object';
  2162. var root = WINDOW ? window : {};
  2163. if (root.JS_MD5_NO_WINDOW) {
  2164. WINDOW = false;
  2165. }
  2166. var WEB_WORKER = !WINDOW && (typeof self === 'undefined' ? 'undefined' : _typeof(self)) === 'object';
  2167. var NODE_JS = !root.JS_MD5_NO_NODE_JS && (typeof process === 'undefined' ? 'undefined' : _typeof(process)) === 'object' && process.versions && process.versions.node;
  2168. if (NODE_JS) {
  2169. root = global;
  2170. } else if (WEB_WORKER) {
  2171. root = self;
  2172. }
  2173. var COMMON_JS = !root.JS_MD5_NO_COMMON_JS && ( false ? 'undefined' : _typeof(module)) === 'object' && module.exports;
  2174. var AMD = "function" === 'function' && __webpack_require__(11);
  2175. var ARRAY_BUFFER = !root.JS_MD5_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined';
  2176. var HEX_CHARS = '0123456789abcdef'.split('');
  2177. var EXTRA = [128, 32768, 8388608, -2147483648];
  2178. var SHIFT = [0, 8, 16, 24];
  2179. var OUTPUT_TYPES = ['hex', 'array', 'digest', 'buffer', 'arrayBuffer', 'base64'];
  2180. var BASE64_ENCODE_CHAR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  2181. var blocks = [],
  2182. buffer8;
  2183. if (ARRAY_BUFFER) {
  2184. var buffer = new ArrayBuffer(68);
  2185. buffer8 = new Uint8Array(buffer);
  2186. blocks = new Uint32Array(buffer);
  2187. }
  2188. if (root.JS_MD5_NO_NODE_JS || !Array.isArray) {
  2189. Array.isArray = function (obj) {
  2190. return Object.prototype.toString.call(obj) === '[object Array]';
  2191. };
  2192. }
  2193. if (ARRAY_BUFFER && (root.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) {
  2194. ArrayBuffer.isView = function (obj) {
  2195. return (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer;
  2196. };
  2197. }
  2198. /**
  2199. * @method hex
  2200. * @memberof md5
  2201. * @description Output hash as hex string
  2202. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  2203. * @returns {String} Hex string
  2204. * @example
  2205. * md5.hex('The quick brown fox jumps over the lazy dog');
  2206. * // equal to
  2207. * md5('The quick brown fox jumps over the lazy dog');
  2208. */
  2209. /**
  2210. * @method digest
  2211. * @memberof md5
  2212. * @description Output hash as bytes array
  2213. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  2214. * @returns {Array} Bytes array
  2215. * @example
  2216. * md5.digest('The quick brown fox jumps over the lazy dog');
  2217. */
  2218. /**
  2219. * @method array
  2220. * @memberof md5
  2221. * @description Output hash as bytes array
  2222. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  2223. * @returns {Array} Bytes array
  2224. * @example
  2225. * md5.array('The quick brown fox jumps over the lazy dog');
  2226. */
  2227. /**
  2228. * @method arrayBuffer
  2229. * @memberof md5
  2230. * @description Output hash as ArrayBuffer
  2231. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  2232. * @returns {ArrayBuffer} ArrayBuffer
  2233. * @example
  2234. * md5.arrayBuffer('The quick brown fox jumps over the lazy dog');
  2235. */
  2236. /**
  2237. * @method buffer
  2238. * @deprecated This maybe confuse with Buffer in node.js. Please use arrayBuffer instead.
  2239. * @memberof md5
  2240. * @description Output hash as ArrayBuffer
  2241. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  2242. * @returns {ArrayBuffer} ArrayBuffer
  2243. * @example
  2244. * md5.buffer('The quick brown fox jumps over the lazy dog');
  2245. */
  2246. /**
  2247. * @method base64
  2248. * @memberof md5
  2249. * @description Output hash as base64 string
  2250. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  2251. * @returns {String} base64 string
  2252. * @example
  2253. * md5.base64('The quick brown fox jumps over the lazy dog');
  2254. */
  2255. var createOutputMethod = function createOutputMethod(outputType) {
  2256. return function (message) {
  2257. return new Md5(true).update(message)[outputType]();
  2258. };
  2259. };
  2260. /**
  2261. * @method create
  2262. * @memberof md5
  2263. * @description Create Md5 object
  2264. * @returns {Md5} Md5 object.
  2265. * @example
  2266. * var hash = md5.create();
  2267. */
  2268. /**
  2269. * @method update
  2270. * @memberof md5
  2271. * @description Create and update Md5 object
  2272. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  2273. * @returns {Md5} Md5 object.
  2274. * @example
  2275. * var hash = md5.update('The quick brown fox jumps over the lazy dog');
  2276. * // equal to
  2277. * var hash = md5.create();
  2278. * hash.update('The quick brown fox jumps over the lazy dog');
  2279. */
  2280. var createMethod = function createMethod() {
  2281. var method = createOutputMethod('hex');
  2282. if (NODE_JS) {
  2283. method = nodeWrap(method);
  2284. }
  2285. method.getCtx = method.create = function () {
  2286. return new Md5();
  2287. };
  2288. method.update = function (message) {
  2289. return method.create().update(message);
  2290. };
  2291. for (var i = 0; i < OUTPUT_TYPES.length; ++i) {
  2292. var type = OUTPUT_TYPES[i];
  2293. method[type] = createOutputMethod(type);
  2294. }
  2295. return method;
  2296. };
  2297. var nodeWrap = function nodeWrap(method) {
  2298. var crypto = eval("require('crypto')");
  2299. var Buffer = eval("require('buffer').Buffer");
  2300. var nodeMethod = function nodeMethod(message) {
  2301. if (typeof message === 'string') {
  2302. return crypto.createHash('md5').update(message, 'utf8').digest('hex');
  2303. } else {
  2304. if (message === null || message === undefined) {
  2305. throw ERROR;
  2306. } else if (message.constructor === ArrayBuffer) {
  2307. message = new Uint8Array(message);
  2308. }
  2309. }
  2310. if (Array.isArray(message) || ArrayBuffer.isView(message) || message.constructor === Buffer) {
  2311. return crypto.createHash('md5').update(new Buffer(message)).digest('hex');
  2312. } else {
  2313. return method(message);
  2314. }
  2315. };
  2316. return nodeMethod;
  2317. };
  2318. /**
  2319. * Md5 class
  2320. * @class Md5
  2321. * @description This is internal class.
  2322. * @see {@link md5.create}
  2323. */
  2324. function Md5(sharedMemory) {
  2325. if (sharedMemory) {
  2326. 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;
  2327. this.blocks = blocks;
  2328. this.buffer8 = buffer8;
  2329. } else {
  2330. if (ARRAY_BUFFER) {
  2331. var buffer = new ArrayBuffer(68);
  2332. this.buffer8 = new Uint8Array(buffer);
  2333. this.blocks = new Uint32Array(buffer);
  2334. } else {
  2335. this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
  2336. }
  2337. }
  2338. this.h0 = this.h1 = this.h2 = this.h3 = this.start = this.bytes = this.hBytes = 0;
  2339. this.finalized = this.hashed = false;
  2340. this.first = true;
  2341. }
  2342. /**
  2343. * @method update
  2344. * @memberof Md5
  2345. * @instance
  2346. * @description Update hash
  2347. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  2348. * @returns {Md5} Md5 object.
  2349. * @see {@link md5.update}
  2350. */
  2351. Md5.prototype.update = function (message) {
  2352. if (this.finalized) {
  2353. return;
  2354. }
  2355. var notString,
  2356. type = typeof message === 'undefined' ? 'undefined' : _typeof(message);
  2357. if (type !== 'string') {
  2358. if (type === 'object') {
  2359. if (message === null) {
  2360. throw ERROR;
  2361. } else if (ARRAY_BUFFER && (message.constructor === ArrayBuffer || message.constructor.name === 'ArrayBuffer')) {
  2362. message = new Uint8Array(message);
  2363. } else if (!Array.isArray(message)) {
  2364. if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) {
  2365. throw ERROR;
  2366. }
  2367. }
  2368. } else {
  2369. throw ERROR;
  2370. }
  2371. notString = true;
  2372. }
  2373. var code,
  2374. index = 0,
  2375. i,
  2376. length = message.length,
  2377. blocks = this.blocks;
  2378. var buffer8 = this.buffer8;
  2379. while (index < length) {
  2380. if (this.hashed) {
  2381. this.hashed = false;
  2382. blocks[0] = blocks[16];
  2383. 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;
  2384. }
  2385. if (notString) {
  2386. if (ARRAY_BUFFER) {
  2387. for (i = this.start; index < length && i < 64; ++index) {
  2388. buffer8[i++] = message[index];
  2389. }
  2390. } else {
  2391. for (i = this.start; index < length && i < 64; ++index) {
  2392. blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];
  2393. }
  2394. }
  2395. } else {
  2396. if (ARRAY_BUFFER) {
  2397. for (i = this.start; index < length && i < 64; ++index) {
  2398. code = message.charCodeAt(index);
  2399. if (code < 0x80) {
  2400. buffer8[i++] = code;
  2401. } else if (code < 0x800) {
  2402. buffer8[i++] = 0xc0 | code >> 6;
  2403. buffer8[i++] = 0x80 | code & 0x3f;
  2404. } else if (code < 0xd800 || code >= 0xe000) {
  2405. buffer8[i++] = 0xe0 | code >> 12;
  2406. buffer8[i++] = 0x80 | code >> 6 & 0x3f;
  2407. buffer8[i++] = 0x80 | code & 0x3f;
  2408. } else {
  2409. code = 0x10000 + ((code & 0x3ff) << 10 | message.charCodeAt(++index) & 0x3ff);
  2410. buffer8[i++] = 0xf0 | code >> 18;
  2411. buffer8[i++] = 0x80 | code >> 12 & 0x3f;
  2412. buffer8[i++] = 0x80 | code >> 6 & 0x3f;
  2413. buffer8[i++] = 0x80 | code & 0x3f;
  2414. }
  2415. }
  2416. } else {
  2417. for (i = this.start; index < length && i < 64; ++index) {
  2418. code = message.charCodeAt(index);
  2419. if (code < 0x80) {
  2420. blocks[i >> 2] |= code << SHIFT[i++ & 3];
  2421. } else if (code < 0x800) {
  2422. blocks[i >> 2] |= (0xc0 | code >> 6) << SHIFT[i++ & 3];
  2423. blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3];
  2424. } else if (code < 0xd800 || code >= 0xe000) {
  2425. blocks[i >> 2] |= (0xe0 | code >> 12) << SHIFT[i++ & 3];
  2426. blocks[i >> 2] |= (0x80 | code >> 6 & 0x3f) << SHIFT[i++ & 3];
  2427. blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3];
  2428. } else {
  2429. code = 0x10000 + ((code & 0x3ff) << 10 | message.charCodeAt(++index) & 0x3ff);
  2430. blocks[i >> 2] |= (0xf0 | code >> 18) << SHIFT[i++ & 3];
  2431. blocks[i >> 2] |= (0x80 | code >> 12 & 0x3f) << SHIFT[i++ & 3];
  2432. blocks[i >> 2] |= (0x80 | code >> 6 & 0x3f) << SHIFT[i++ & 3];
  2433. blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3];
  2434. }
  2435. }
  2436. }
  2437. }
  2438. this.lastByteIndex = i;
  2439. this.bytes += i - this.start;
  2440. if (i >= 64) {
  2441. this.start = i - 64;
  2442. this.hash();
  2443. this.hashed = true;
  2444. } else {
  2445. this.start = i;
  2446. }
  2447. }
  2448. if (this.bytes > 4294967295) {
  2449. this.hBytes += this.bytes / 4294967296 << 0;
  2450. this.bytes = this.bytes % 4294967296;
  2451. }
  2452. return this;
  2453. };
  2454. Md5.prototype.finalize = function () {
  2455. if (this.finalized) {
  2456. return;
  2457. }
  2458. this.finalized = true;
  2459. var blocks = this.blocks,
  2460. i = this.lastByteIndex;
  2461. blocks[i >> 2] |= EXTRA[i & 3];
  2462. if (i >= 56) {
  2463. if (!this.hashed) {
  2464. this.hash();
  2465. }
  2466. blocks[0] = blocks[16];
  2467. 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;
  2468. }
  2469. blocks[14] = this.bytes << 3;
  2470. blocks[15] = this.hBytes << 3 | this.bytes >>> 29;
  2471. this.hash();
  2472. };
  2473. Md5.prototype.hash = function () {
  2474. var a,
  2475. b,
  2476. c,
  2477. d,
  2478. bc,
  2479. da,
  2480. blocks = this.blocks;
  2481. if (this.first) {
  2482. a = blocks[0] - 680876937;
  2483. a = (a << 7 | a >>> 25) - 271733879 << 0;
  2484. d = (-1732584194 ^ a & 2004318071) + blocks[1] - 117830708;
  2485. d = (d << 12 | d >>> 20) + a << 0;
  2486. c = (-271733879 ^ d & (a ^ -271733879)) + blocks[2] - 1126478375;
  2487. c = (c << 17 | c >>> 15) + d << 0;
  2488. b = (a ^ c & (d ^ a)) + blocks[3] - 1316259209;
  2489. b = (b << 22 | b >>> 10) + c << 0;
  2490. } else {
  2491. a = this.h0;
  2492. b = this.h1;
  2493. c = this.h2;
  2494. d = this.h3;
  2495. a += (d ^ b & (c ^ d)) + blocks[0] - 680876936;
  2496. a = (a << 7 | a >>> 25) + b << 0;
  2497. d += (c ^ a & (b ^ c)) + blocks[1] - 389564586;
  2498. d = (d << 12 | d >>> 20) + a << 0;
  2499. c += (b ^ d & (a ^ b)) + blocks[2] + 606105819;
  2500. c = (c << 17 | c >>> 15) + d << 0;
  2501. b += (a ^ c & (d ^ a)) + blocks[3] - 1044525330;
  2502. b = (b << 22 | b >>> 10) + c << 0;
  2503. }
  2504. a += (d ^ b & (c ^ d)) + blocks[4] - 176418897;
  2505. a = (a << 7 | a >>> 25) + b << 0;
  2506. d += (c ^ a & (b ^ c)) + blocks[5] + 1200080426;
  2507. d = (d << 12 | d >>> 20) + a << 0;
  2508. c += (b ^ d & (a ^ b)) + blocks[6] - 1473231341;
  2509. c = (c << 17 | c >>> 15) + d << 0;
  2510. b += (a ^ c & (d ^ a)) + blocks[7] - 45705983;
  2511. b = (b << 22 | b >>> 10) + c << 0;
  2512. a += (d ^ b & (c ^ d)) + blocks[8] + 1770035416;
  2513. a = (a << 7 | a >>> 25) + b << 0;
  2514. d += (c ^ a & (b ^ c)) + blocks[9] - 1958414417;
  2515. d = (d << 12 | d >>> 20) + a << 0;
  2516. c += (b ^ d & (a ^ b)) + blocks[10] - 42063;
  2517. c = (c << 17 | c >>> 15) + d << 0;
  2518. b += (a ^ c & (d ^ a)) + blocks[11] - 1990404162;
  2519. b = (b << 22 | b >>> 10) + c << 0;
  2520. a += (d ^ b & (c ^ d)) + blocks[12] + 1804603682;
  2521. a = (a << 7 | a >>> 25) + b << 0;
  2522. d += (c ^ a & (b ^ c)) + blocks[13] - 40341101;
  2523. d = (d << 12 | d >>> 20) + a << 0;
  2524. c += (b ^ d & (a ^ b)) + blocks[14] - 1502002290;
  2525. c = (c << 17 | c >>> 15) + d << 0;
  2526. b += (a ^ c & (d ^ a)) + blocks[15] + 1236535329;
  2527. b = (b << 22 | b >>> 10) + c << 0;
  2528. a += (c ^ d & (b ^ c)) + blocks[1] - 165796510;
  2529. a = (a << 5 | a >>> 27) + b << 0;
  2530. d += (b ^ c & (a ^ b)) + blocks[6] - 1069501632;
  2531. d = (d << 9 | d >>> 23) + a << 0;
  2532. c += (a ^ b & (d ^ a)) + blocks[11] + 643717713;
  2533. c = (c << 14 | c >>> 18) + d << 0;
  2534. b += (d ^ a & (c ^ d)) + blocks[0] - 373897302;
  2535. b = (b << 20 | b >>> 12) + c << 0;
  2536. a += (c ^ d & (b ^ c)) + blocks[5] - 701558691;
  2537. a = (a << 5 | a >>> 27) + b << 0;
  2538. d += (b ^ c & (a ^ b)) + blocks[10] + 38016083;
  2539. d = (d << 9 | d >>> 23) + a << 0;
  2540. c += (a ^ b & (d ^ a)) + blocks[15] - 660478335;
  2541. c = (c << 14 | c >>> 18) + d << 0;
  2542. b += (d ^ a & (c ^ d)) + blocks[4] - 405537848;
  2543. b = (b << 20 | b >>> 12) + c << 0;
  2544. a += (c ^ d & (b ^ c)) + blocks[9] + 568446438;
  2545. a = (a << 5 | a >>> 27) + b << 0;
  2546. d += (b ^ c & (a ^ b)) + blocks[14] - 1019803690;
  2547. d = (d << 9 | d >>> 23) + a << 0;
  2548. c += (a ^ b & (d ^ a)) + blocks[3] - 187363961;
  2549. c = (c << 14 | c >>> 18) + d << 0;
  2550. b += (d ^ a & (c ^ d)) + blocks[8] + 1163531501;
  2551. b = (b << 20 | b >>> 12) + c << 0;
  2552. a += (c ^ d & (b ^ c)) + blocks[13] - 1444681467;
  2553. a = (a << 5 | a >>> 27) + b << 0;
  2554. d += (b ^ c & (a ^ b)) + blocks[2] - 51403784;
  2555. d = (d << 9 | d >>> 23) + a << 0;
  2556. c += (a ^ b & (d ^ a)) + blocks[7] + 1735328473;
  2557. c = (c << 14 | c >>> 18) + d << 0;
  2558. b += (d ^ a & (c ^ d)) + blocks[12] - 1926607734;
  2559. b = (b << 20 | b >>> 12) + c << 0;
  2560. bc = b ^ c;
  2561. a += (bc ^ d) + blocks[5] - 378558;
  2562. a = (a << 4 | a >>> 28) + b << 0;
  2563. d += (bc ^ a) + blocks[8] - 2022574463;
  2564. d = (d << 11 | d >>> 21) + a << 0;
  2565. da = d ^ a;
  2566. c += (da ^ b) + blocks[11] + 1839030562;
  2567. c = (c << 16 | c >>> 16) + d << 0;
  2568. b += (da ^ c) + blocks[14] - 35309556;
  2569. b = (b << 23 | b >>> 9) + c << 0;
  2570. bc = b ^ c;
  2571. a += (bc ^ d) + blocks[1] - 1530992060;
  2572. a = (a << 4 | a >>> 28) + b << 0;
  2573. d += (bc ^ a) + blocks[4] + 1272893353;
  2574. d = (d << 11 | d >>> 21) + a << 0;
  2575. da = d ^ a;
  2576. c += (da ^ b) + blocks[7] - 155497632;
  2577. c = (c << 16 | c >>> 16) + d << 0;
  2578. b += (da ^ c) + blocks[10] - 1094730640;
  2579. b = (b << 23 | b >>> 9) + c << 0;
  2580. bc = b ^ c;
  2581. a += (bc ^ d) + blocks[13] + 681279174;
  2582. a = (a << 4 | a >>> 28) + b << 0;
  2583. d += (bc ^ a) + blocks[0] - 358537222;
  2584. d = (d << 11 | d >>> 21) + a << 0;
  2585. da = d ^ a;
  2586. c += (da ^ b) + blocks[3] - 722521979;
  2587. c = (c << 16 | c >>> 16) + d << 0;
  2588. b += (da ^ c) + blocks[6] + 76029189;
  2589. b = (b << 23 | b >>> 9) + c << 0;
  2590. bc = b ^ c;
  2591. a += (bc ^ d) + blocks[9] - 640364487;
  2592. a = (a << 4 | a >>> 28) + b << 0;
  2593. d += (bc ^ a) + blocks[12] - 421815835;
  2594. d = (d << 11 | d >>> 21) + a << 0;
  2595. da = d ^ a;
  2596. c += (da ^ b) + blocks[15] + 530742520;
  2597. c = (c << 16 | c >>> 16) + d << 0;
  2598. b += (da ^ c) + blocks[2] - 995338651;
  2599. b = (b << 23 | b >>> 9) + c << 0;
  2600. a += (c ^ (b | ~d)) + blocks[0] - 198630844;
  2601. a = (a << 6 | a >>> 26) + b << 0;
  2602. d += (b ^ (a | ~c)) + blocks[7] + 1126891415;
  2603. d = (d << 10 | d >>> 22) + a << 0;
  2604. c += (a ^ (d | ~b)) + blocks[14] - 1416354905;
  2605. c = (c << 15 | c >>> 17) + d << 0;
  2606. b += (d ^ (c | ~a)) + blocks[5] - 57434055;
  2607. b = (b << 21 | b >>> 11) + c << 0;
  2608. a += (c ^ (b | ~d)) + blocks[12] + 1700485571;
  2609. a = (a << 6 | a >>> 26) + b << 0;
  2610. d += (b ^ (a | ~c)) + blocks[3] - 1894986606;
  2611. d = (d << 10 | d >>> 22) + a << 0;
  2612. c += (a ^ (d | ~b)) + blocks[10] - 1051523;
  2613. c = (c << 15 | c >>> 17) + d << 0;
  2614. b += (d ^ (c | ~a)) + blocks[1] - 2054922799;
  2615. b = (b << 21 | b >>> 11) + c << 0;
  2616. a += (c ^ (b | ~d)) + blocks[8] + 1873313359;
  2617. a = (a << 6 | a >>> 26) + b << 0;
  2618. d += (b ^ (a | ~c)) + blocks[15] - 30611744;
  2619. d = (d << 10 | d >>> 22) + a << 0;
  2620. c += (a ^ (d | ~b)) + blocks[6] - 1560198380;
  2621. c = (c << 15 | c >>> 17) + d << 0;
  2622. b += (d ^ (c | ~a)) + blocks[13] + 1309151649;
  2623. b = (b << 21 | b >>> 11) + c << 0;
  2624. a += (c ^ (b | ~d)) + blocks[4] - 145523070;
  2625. a = (a << 6 | a >>> 26) + b << 0;
  2626. d += (b ^ (a | ~c)) + blocks[11] - 1120210379;
  2627. d = (d << 10 | d >>> 22) + a << 0;
  2628. c += (a ^ (d | ~b)) + blocks[2] + 718787259;
  2629. c = (c << 15 | c >>> 17) + d << 0;
  2630. b += (d ^ (c | ~a)) + blocks[9] - 343485551;
  2631. b = (b << 21 | b >>> 11) + c << 0;
  2632. if (this.first) {
  2633. this.h0 = a + 1732584193 << 0;
  2634. this.h1 = b - 271733879 << 0;
  2635. this.h2 = c - 1732584194 << 0;
  2636. this.h3 = d + 271733878 << 0;
  2637. this.first = false;
  2638. } else {
  2639. this.h0 = this.h0 + a << 0;
  2640. this.h1 = this.h1 + b << 0;
  2641. this.h2 = this.h2 + c << 0;
  2642. this.h3 = this.h3 + d << 0;
  2643. }
  2644. };
  2645. /**
  2646. * @method hex
  2647. * @memberof Md5
  2648. * @instance
  2649. * @description Output hash as hex string
  2650. * @returns {String} Hex string
  2651. * @see {@link md5.hex}
  2652. * @example
  2653. * hash.hex();
  2654. */
  2655. Md5.prototype.hex = function () {
  2656. this.finalize();
  2657. var h0 = this.h0,
  2658. h1 = this.h1,
  2659. h2 = this.h2,
  2660. h3 = this.h3;
  2661. 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];
  2662. };
  2663. /**
  2664. * @method toString
  2665. * @memberof Md5
  2666. * @instance
  2667. * @description Output hash as hex string
  2668. * @returns {String} Hex string
  2669. * @see {@link md5.hex}
  2670. * @example
  2671. * hash.toString();
  2672. */
  2673. Md5.prototype.toString = Md5.prototype.hex;
  2674. /**
  2675. * @method digest
  2676. * @memberof Md5
  2677. * @instance
  2678. * @description Output hash as bytes array
  2679. * @returns {Array} Bytes array
  2680. * @see {@link md5.digest}
  2681. * @example
  2682. * hash.digest();
  2683. */
  2684. Md5.prototype.digest = function () {
  2685. this.finalize();
  2686. var h0 = this.h0,
  2687. h1 = this.h1,
  2688. h2 = this.h2,
  2689. h3 = this.h3;
  2690. 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];
  2691. };
  2692. /**
  2693. * @method array
  2694. * @memberof Md5
  2695. * @instance
  2696. * @description Output hash as bytes array
  2697. * @returns {Array} Bytes array
  2698. * @see {@link md5.array}
  2699. * @example
  2700. * hash.array();
  2701. */
  2702. Md5.prototype.array = Md5.prototype.digest;
  2703. /**
  2704. * @method arrayBuffer
  2705. * @memberof Md5
  2706. * @instance
  2707. * @description Output hash as ArrayBuffer
  2708. * @returns {ArrayBuffer} ArrayBuffer
  2709. * @see {@link md5.arrayBuffer}
  2710. * @example
  2711. * hash.arrayBuffer();
  2712. */
  2713. Md5.prototype.arrayBuffer = function () {
  2714. this.finalize();
  2715. var buffer = new ArrayBuffer(16);
  2716. var blocks = new Uint32Array(buffer);
  2717. blocks[0] = this.h0;
  2718. blocks[1] = this.h1;
  2719. blocks[2] = this.h2;
  2720. blocks[3] = this.h3;
  2721. return buffer;
  2722. };
  2723. /**
  2724. * @method buffer
  2725. * @deprecated This maybe confuse with Buffer in node.js. Please use arrayBuffer instead.
  2726. * @memberof Md5
  2727. * @instance
  2728. * @description Output hash as ArrayBuffer
  2729. * @returns {ArrayBuffer} ArrayBuffer
  2730. * @see {@link md5.buffer}
  2731. * @example
  2732. * hash.buffer();
  2733. */
  2734. Md5.prototype.buffer = Md5.prototype.arrayBuffer;
  2735. /**
  2736. * @method base64
  2737. * @memberof Md5
  2738. * @instance
  2739. * @description Output hash as base64 string
  2740. * @returns {String} base64 string
  2741. * @see {@link md5.base64}
  2742. * @example
  2743. * hash.base64();
  2744. */
  2745. Md5.prototype.base64 = function () {
  2746. var v1,
  2747. v2,
  2748. v3,
  2749. base64Str = '',
  2750. bytes = this.array();
  2751. for (var i = 0; i < 15;) {
  2752. v1 = bytes[i++];
  2753. v2 = bytes[i++];
  2754. v3 = bytes[i++];
  2755. 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];
  2756. }
  2757. v1 = bytes[i];
  2758. base64Str += BASE64_ENCODE_CHAR[v1 >>> 2] + BASE64_ENCODE_CHAR[v1 << 4 & 63] + '==';
  2759. return base64Str;
  2760. };
  2761. var exports = createMethod();
  2762. if (COMMON_JS) {
  2763. module.exports = exports;
  2764. } else {
  2765. /**
  2766. * @method md5
  2767. * @description Md5 hash function, export to global in browsers.
  2768. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  2769. * @returns {String} md5 hashes
  2770. * @example
  2771. * md5(''); // d41d8cd98f00b204e9800998ecf8427e
  2772. * md5('The quick brown fox jumps over the lazy dog'); // 9e107d9d372bb6826bd81d3542a419d6
  2773. * md5('The quick brown fox jumps over the lazy dog.'); // e4d909c290d0fb1ca068ffaddf22cbd0
  2774. *
  2775. * // It also supports UTF-8 encoding
  2776. * md5('中文'); // a7bac2239fcdcb3a067903d8077c4a07
  2777. *
  2778. * // It also supports byte `Array`, `Uint8Array`, `ArrayBuffer`
  2779. * md5([]); // d41d8cd98f00b204e9800998ecf8427e
  2780. * md5(new Uint8Array([])); // d41d8cd98f00b204e9800998ecf8427e
  2781. */
  2782. root.md5 = exports;
  2783. if (AMD) {
  2784. !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {
  2785. return exports;
  2786. }).call(exports, __webpack_require__, exports, module),
  2787. __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  2788. }
  2789. }
  2790. })();
  2791. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9), __webpack_require__(1), __webpack_require__(10)(module)))
  2792. /***/ }),
  2793. /* 9 */
  2794. /***/ (function(module, exports, __webpack_require__) {
  2795. "use strict";
  2796. // shim for using process in browser
  2797. var process = module.exports = {};
  2798. // cached from whatever global is present so that test runners that stub it
  2799. // don't break things. But we need to wrap it in a try catch in case it is
  2800. // wrapped in strict mode code which doesn't define any globals. It's inside a
  2801. // function because try/catches deoptimize in certain engines.
  2802. var cachedSetTimeout;
  2803. var cachedClearTimeout;
  2804. function defaultSetTimout() {
  2805. throw new Error('setTimeout has not been defined');
  2806. }
  2807. function defaultClearTimeout() {
  2808. throw new Error('clearTimeout has not been defined');
  2809. }
  2810. (function () {
  2811. try {
  2812. if (typeof setTimeout === 'function') {
  2813. cachedSetTimeout = setTimeout;
  2814. } else {
  2815. cachedSetTimeout = defaultSetTimout;
  2816. }
  2817. } catch (e) {
  2818. cachedSetTimeout = defaultSetTimout;
  2819. }
  2820. try {
  2821. if (typeof clearTimeout === 'function') {
  2822. cachedClearTimeout = clearTimeout;
  2823. } else {
  2824. cachedClearTimeout = defaultClearTimeout;
  2825. }
  2826. } catch (e) {
  2827. cachedClearTimeout = defaultClearTimeout;
  2828. }
  2829. })();
  2830. function runTimeout(fun) {
  2831. if (cachedSetTimeout === setTimeout) {
  2832. //normal enviroments in sane situations
  2833. return setTimeout(fun, 0);
  2834. }
  2835. // if setTimeout wasn't available but was latter defined
  2836. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  2837. cachedSetTimeout = setTimeout;
  2838. return setTimeout(fun, 0);
  2839. }
  2840. try {
  2841. // when when somebody has screwed with setTimeout but no I.E. maddness
  2842. return cachedSetTimeout(fun, 0);
  2843. } catch (e) {
  2844. try {
  2845. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  2846. return cachedSetTimeout.call(null, fun, 0);
  2847. } catch (e) {
  2848. // 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
  2849. return cachedSetTimeout.call(this, fun, 0);
  2850. }
  2851. }
  2852. }
  2853. function runClearTimeout(marker) {
  2854. if (cachedClearTimeout === clearTimeout) {
  2855. //normal enviroments in sane situations
  2856. return clearTimeout(marker);
  2857. }
  2858. // if clearTimeout wasn't available but was latter defined
  2859. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  2860. cachedClearTimeout = clearTimeout;
  2861. return clearTimeout(marker);
  2862. }
  2863. try {
  2864. // when when somebody has screwed with setTimeout but no I.E. maddness
  2865. return cachedClearTimeout(marker);
  2866. } catch (e) {
  2867. try {
  2868. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  2869. return cachedClearTimeout.call(null, marker);
  2870. } catch (e) {
  2871. // 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.
  2872. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  2873. return cachedClearTimeout.call(this, marker);
  2874. }
  2875. }
  2876. }
  2877. var queue = [];
  2878. var draining = false;
  2879. var currentQueue;
  2880. var queueIndex = -1;
  2881. function cleanUpNextTick() {
  2882. if (!draining || !currentQueue) {
  2883. return;
  2884. }
  2885. draining = false;
  2886. if (currentQueue.length) {
  2887. queue = currentQueue.concat(queue);
  2888. } else {
  2889. queueIndex = -1;
  2890. }
  2891. if (queue.length) {
  2892. drainQueue();
  2893. }
  2894. }
  2895. function drainQueue() {
  2896. if (draining) {
  2897. return;
  2898. }
  2899. var timeout = runTimeout(cleanUpNextTick);
  2900. draining = true;
  2901. var len = queue.length;
  2902. while (len) {
  2903. currentQueue = queue;
  2904. queue = [];
  2905. while (++queueIndex < len) {
  2906. if (currentQueue) {
  2907. currentQueue[queueIndex].run();
  2908. }
  2909. }
  2910. queueIndex = -1;
  2911. len = queue.length;
  2912. }
  2913. currentQueue = null;
  2914. draining = false;
  2915. runClearTimeout(timeout);
  2916. }
  2917. process.nextTick = function (fun) {
  2918. var args = new Array(arguments.length - 1);
  2919. if (arguments.length > 1) {
  2920. for (var i = 1; i < arguments.length; i++) {
  2921. args[i - 1] = arguments[i];
  2922. }
  2923. }
  2924. queue.push(new Item(fun, args));
  2925. if (queue.length === 1 && !draining) {
  2926. runTimeout(drainQueue);
  2927. }
  2928. };
  2929. // v8 likes predictible objects
  2930. function Item(fun, array) {
  2931. this.fun = fun;
  2932. this.array = array;
  2933. }
  2934. Item.prototype.run = function () {
  2935. this.fun.apply(null, this.array);
  2936. };
  2937. process.title = 'browser';
  2938. process.browser = true;
  2939. process.env = {};
  2940. process.argv = [];
  2941. process.version = ''; // empty string to avoid regexp issues
  2942. process.versions = {};
  2943. function noop() {}
  2944. process.on = noop;
  2945. process.addListener = noop;
  2946. process.once = noop;
  2947. process.off = noop;
  2948. process.removeListener = noop;
  2949. process.removeAllListeners = noop;
  2950. process.emit = noop;
  2951. process.prependListener = noop;
  2952. process.prependOnceListener = noop;
  2953. process.listeners = function (name) {
  2954. return [];
  2955. };
  2956. process.binding = function (name) {
  2957. throw new Error('process.binding is not supported');
  2958. };
  2959. process.cwd = function () {
  2960. return '/';
  2961. };
  2962. process.chdir = function (dir) {
  2963. throw new Error('process.chdir is not supported');
  2964. };
  2965. process.umask = function () {
  2966. return 0;
  2967. };
  2968. /***/ }),
  2969. /* 10 */
  2970. /***/ (function(module, exports, __webpack_require__) {
  2971. "use strict";
  2972. module.exports = function (module) {
  2973. if (!module.webpackPolyfill) {
  2974. module.deprecate = function () {};
  2975. module.paths = [];
  2976. // module.parent = undefined by default
  2977. if (!module.children) module.children = [];
  2978. Object.defineProperty(module, "loaded", {
  2979. enumerable: true,
  2980. get: function get() {
  2981. return module.l;
  2982. }
  2983. });
  2984. Object.defineProperty(module, "id", {
  2985. enumerable: true,
  2986. get: function get() {
  2987. return module.i;
  2988. }
  2989. });
  2990. module.webpackPolyfill = 1;
  2991. }
  2992. return module;
  2993. };
  2994. /***/ }),
  2995. /* 11 */
  2996. /***/ (function(module, exports) {
  2997. /* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {/* globals __webpack_amd_options__ */
  2998. module.exports = __webpack_amd_options__;
  2999. /* WEBPACK VAR INJECTION */}.call(exports, {}))
  3000. /***/ }),
  3001. /* 12 */
  3002. /***/ (function(module, exports, __webpack_require__) {
  3003. "use strict";
  3004. /*
  3005. CryptoJS v3.1.2
  3006. code.google.com/p/crypto-js
  3007. (c) 2009-2013 by Jeff Mott. All rights reserved.
  3008. code.google.com/p/crypto-js/wiki/License
  3009. */
  3010. var CryptoJS = CryptoJS || function (g, l) {
  3011. var e = {},
  3012. d = e.lib = {},
  3013. m = function m() {},
  3014. k = d.Base = { extend: function extend(a) {
  3015. m.prototype = this;var c = new m();a && c.mixIn(a);c.hasOwnProperty("init") || (c.init = function () {
  3016. c.$super.init.apply(this, arguments);
  3017. });c.init.prototype = c;c.$super = this;return c;
  3018. }, create: function create() {
  3019. var a = this.extend();a.init.apply(a, arguments);return a;
  3020. }, init: function init() {}, mixIn: function mixIn(a) {
  3021. for (var c in a) {
  3022. a.hasOwnProperty(c) && (this[c] = a[c]);
  3023. }a.hasOwnProperty("toString") && (this.toString = a.toString);
  3024. }, clone: function clone() {
  3025. return this.init.prototype.extend(this);
  3026. } },
  3027. p = d.WordArray = k.extend({ init: function init(a, c) {
  3028. a = this.words = a || [];this.sigBytes = c != l ? c : 4 * a.length;
  3029. }, toString: function toString(a) {
  3030. return (a || n).stringify(this);
  3031. }, concat: function concat(a) {
  3032. var c = this.words,
  3033. q = a.words,
  3034. f = this.sigBytes;a = a.sigBytes;this.clamp();if (f % 4) for (var b = 0; b < a; b++) {
  3035. c[f + b >>> 2] |= (q[b >>> 2] >>> 24 - 8 * (b % 4) & 255) << 24 - 8 * ((f + b) % 4);
  3036. } else if (65535 < q.length) for (b = 0; b < a; b += 4) {
  3037. c[f + b >>> 2] = q[b >>> 2];
  3038. } else c.push.apply(c, q);this.sigBytes += a;return this;
  3039. }, clamp: function clamp() {
  3040. var a = this.words,
  3041. c = this.sigBytes;a[c >>> 2] &= 4294967295 << 32 - 8 * (c % 4);a.length = g.ceil(c / 4);
  3042. }, clone: function clone() {
  3043. var a = k.clone.call(this);a.words = this.words.slice(0);return a;
  3044. }, random: function random(a) {
  3045. for (var c = [], b = 0; b < a; b += 4) {
  3046. c.push(4294967296 * g.random() | 0);
  3047. }return new p.init(c, a);
  3048. } }),
  3049. b = e.enc = {},
  3050. n = b.Hex = { stringify: function stringify(a) {
  3051. var c = a.words;a = a.sigBytes;for (var b = [], f = 0; f < a; f++) {
  3052. var d = c[f >>> 2] >>> 24 - 8 * (f % 4) & 255;b.push((d >>> 4).toString(16));b.push((d & 15).toString(16));
  3053. }return b.join("");
  3054. }, parse: function parse(a) {
  3055. for (var c = a.length, b = [], f = 0; f < c; f += 2) {
  3056. b[f >>> 3] |= parseInt(a.substr(f, 2), 16) << 24 - 4 * (f % 8);
  3057. }return new p.init(b, c / 2);
  3058. } },
  3059. j = b.Latin1 = { stringify: function stringify(a) {
  3060. var c = a.words;a = a.sigBytes;for (var b = [], f = 0; f < a; f++) {
  3061. b.push(String.fromCharCode(c[f >>> 2] >>> 24 - 8 * (f % 4) & 255));
  3062. }return b.join("");
  3063. }, parse: function parse(a) {
  3064. for (var c = a.length, b = [], f = 0; f < c; f++) {
  3065. b[f >>> 2] |= (a.charCodeAt(f) & 255) << 24 - 8 * (f % 4);
  3066. }return new p.init(b, c);
  3067. } },
  3068. h = b.Utf8 = { stringify: function stringify(a) {
  3069. try {
  3070. return decodeURIComponent(escape(j.stringify(a)));
  3071. } catch (c) {
  3072. throw Error("Malformed UTF-8 data");
  3073. }
  3074. }, parse: function parse(a) {
  3075. return j.parse(unescape(encodeURIComponent(a)));
  3076. } },
  3077. r = d.BufferedBlockAlgorithm = k.extend({ reset: function reset() {
  3078. this._data = new p.init();this._nDataBytes = 0;
  3079. }, _append: function _append(a) {
  3080. "string" == typeof a && (a = h.parse(a));this._data.concat(a);this._nDataBytes += a.sigBytes;
  3081. }, _process: function _process(a) {
  3082. var c = this._data,
  3083. b = c.words,
  3084. f = c.sigBytes,
  3085. d = this.blockSize,
  3086. e = f / (4 * d),
  3087. e = a ? g.ceil(e) : g.max((e | 0) - this._minBufferSize, 0);a = e * d;f = g.min(4 * a, f);if (a) {
  3088. for (var k = 0; k < a; k += d) {
  3089. this._doProcessBlock(b, k);
  3090. }k = b.splice(0, a);c.sigBytes -= f;
  3091. }return new p.init(k, f);
  3092. }, clone: function clone() {
  3093. var a = k.clone.call(this);
  3094. a._data = this._data.clone();return a;
  3095. }, _minBufferSize: 0 });d.Hasher = r.extend({ cfg: k.extend(), init: function init(a) {
  3096. this.cfg = this.cfg.extend(a);this.reset();
  3097. }, reset: function reset() {
  3098. r.reset.call(this);this._doReset();
  3099. }, update: function update(a) {
  3100. this._append(a);this._process();return this;
  3101. }, finalize: function finalize(a) {
  3102. a && this._append(a);return this._doFinalize();
  3103. }, blockSize: 16, _createHelper: function _createHelper(a) {
  3104. return function (b, d) {
  3105. return new a.init(d).finalize(b);
  3106. };
  3107. }, _createHmacHelper: function _createHmacHelper(a) {
  3108. return function (b, d) {
  3109. return new s.HMAC.init(a, d).finalize(b);
  3110. };
  3111. } });var s = e.algo = {};return e;
  3112. }(Math);
  3113. (function () {
  3114. var g = CryptoJS,
  3115. l = g.lib,
  3116. e = l.WordArray,
  3117. d = l.Hasher,
  3118. m = [],
  3119. l = g.algo.SHA1 = d.extend({ _doReset: function _doReset() {
  3120. this._hash = new e.init([1732584193, 4023233417, 2562383102, 271733878, 3285377520]);
  3121. }, _doProcessBlock: function _doProcessBlock(d, e) {
  3122. 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++) {
  3123. if (16 > a) m[a] = d[e + a] | 0;else {
  3124. var c = m[a - 3] ^ m[a - 8] ^ m[a - 14] ^ m[a - 16];m[a] = c << 1 | c >>> 31;
  3125. }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;
  3126. }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;
  3127. }, _doFinalize: function _doFinalize() {
  3128. var d = this._data,
  3129. e = d.words,
  3130. b = 8 * this._nDataBytes,
  3131. 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;
  3132. }, clone: function clone() {
  3133. var e = d.clone.call(this);e._hash = this._hash.clone();return e;
  3134. } });g.SHA1 = d._createHelper(l);g.HmacSHA1 = d._createHmacHelper(l);
  3135. })();
  3136. (function () {
  3137. var g = CryptoJS,
  3138. l = g.enc.Utf8;g.algo.HMAC = g.lib.Base.extend({ init: function init(e, d) {
  3139. e = this._hasher = new e.init();"string" == typeof d && (d = l.parse(d));var g = e.blockSize,
  3140. 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++) {
  3141. n[h] ^= 1549556828, j[h] ^= 909522486;
  3142. }p.sigBytes = b.sigBytes = k;this.reset();
  3143. }, reset: function reset() {
  3144. var e = this._hasher;e.reset();e.update(this._iKey);
  3145. }, update: function update(e) {
  3146. this._hasher.update(e);return this;
  3147. }, finalize: function finalize(e) {
  3148. var d = this._hasher;e = d.finalize(e);d.reset();return d.finalize(this._oKey.clone().concat(e));
  3149. } });
  3150. })();
  3151. (function () {
  3152. // Shortcuts
  3153. var C = CryptoJS;
  3154. var C_lib = C.lib;
  3155. var WordArray = C_lib.WordArray;
  3156. var C_enc = C.enc;
  3157. /**
  3158. * Base64 encoding strategy.
  3159. */
  3160. var Base64 = C_enc.Base64 = {
  3161. /**
  3162. * Converts a word array to a Base64 string.
  3163. *
  3164. * @param {WordArray} wordArray The word array.
  3165. *
  3166. * @return {string} The Base64 string.
  3167. *
  3168. * @static
  3169. *
  3170. * @example
  3171. *
  3172. * var base64String = CryptoJS.enc.Base64.stringify(wordArray);
  3173. */
  3174. stringify: function stringify(wordArray) {
  3175. // Shortcuts
  3176. var words = wordArray.words;
  3177. var sigBytes = wordArray.sigBytes;
  3178. var map = this._map;
  3179. // Clamp excess bits
  3180. wordArray.clamp();
  3181. // Convert
  3182. var base64Chars = [];
  3183. for (var i = 0; i < sigBytes; i += 3) {
  3184. var byte1 = words[i >>> 2] >>> 24 - i % 4 * 8 & 0xff;
  3185. var byte2 = words[i + 1 >>> 2] >>> 24 - (i + 1) % 4 * 8 & 0xff;
  3186. var byte3 = words[i + 2 >>> 2] >>> 24 - (i + 2) % 4 * 8 & 0xff;
  3187. var triplet = byte1 << 16 | byte2 << 8 | byte3;
  3188. for (var j = 0; j < 4 && i + j * 0.75 < sigBytes; j++) {
  3189. base64Chars.push(map.charAt(triplet >>> 6 * (3 - j) & 0x3f));
  3190. }
  3191. }
  3192. // Add padding
  3193. var paddingChar = map.charAt(64);
  3194. if (paddingChar) {
  3195. while (base64Chars.length % 4) {
  3196. base64Chars.push(paddingChar);
  3197. }
  3198. }
  3199. return base64Chars.join('');
  3200. },
  3201. /**
  3202. * Converts a Base64 string to a word array.
  3203. *
  3204. * @param {string} base64Str The Base64 string.
  3205. *
  3206. * @return {WordArray} The word array.
  3207. *
  3208. * @static
  3209. *
  3210. * @example
  3211. *
  3212. * var wordArray = CryptoJS.enc.Base64.parse(base64String);
  3213. */
  3214. parse: function parse(base64Str) {
  3215. // Shortcuts
  3216. var base64StrLength = base64Str.length;
  3217. var map = this._map;
  3218. // Ignore padding
  3219. var paddingChar = map.charAt(64);
  3220. if (paddingChar) {
  3221. var paddingIndex = base64Str.indexOf(paddingChar);
  3222. if (paddingIndex != -1) {
  3223. base64StrLength = paddingIndex;
  3224. }
  3225. }
  3226. // Convert
  3227. var words = [];
  3228. var nBytes = 0;
  3229. for (var i = 0; i < base64StrLength; i++) {
  3230. if (i % 4) {
  3231. var bits1 = map.indexOf(base64Str.charAt(i - 1)) << i % 4 * 2;
  3232. var bits2 = map.indexOf(base64Str.charAt(i)) >>> 6 - i % 4 * 2;
  3233. words[nBytes >>> 2] |= (bits1 | bits2) << 24 - nBytes % 4 * 8;
  3234. nBytes++;
  3235. }
  3236. }
  3237. return WordArray.create(words, nBytes);
  3238. },
  3239. _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
  3240. };
  3241. })();
  3242. module.exports = CryptoJS;
  3243. /***/ }),
  3244. /* 13 */
  3245. /***/ (function(module, exports, __webpack_require__) {
  3246. "use strict";
  3247. /*
  3248. Copyright 2011-2013 Abdulla Abdurakhmanov
  3249. Original sources are available at https://code.google.com/p/x2js/
  3250. Licensed under the Apache License, Version 2.0 (the "License");
  3251. you may not use this file except in compliance with the License.
  3252. You may obtain a copy of the License at
  3253. http://www.apache.org/licenses/LICENSE-2.0
  3254. Unless required by applicable law or agreed to in writing, software
  3255. distributed under the License is distributed on an "AS IS" BASIS,
  3256. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3257. See the License for the specific language governing permissions and
  3258. limitations under the License.
  3259. */
  3260. var DOMParser = __webpack_require__(14).DOMParser;
  3261. var x2js = function x2js(config) {
  3262. 'use strict';
  3263. var VERSION = "1.2.0";
  3264. config = config || {};
  3265. initConfigDefaults();
  3266. initRequiredPolyfills();
  3267. function initConfigDefaults() {
  3268. if (config.escapeMode === undefined) {
  3269. config.escapeMode = true;
  3270. }
  3271. config.attributePrefix = config.attributePrefix || "_";
  3272. config.arrayAccessForm = config.arrayAccessForm || "none";
  3273. config.emptyNodeForm = config.emptyNodeForm || "text";
  3274. if (config.enableToStringFunc === undefined) {
  3275. config.enableToStringFunc = true;
  3276. }
  3277. config.arrayAccessFormPaths = config.arrayAccessFormPaths || [];
  3278. if (config.skipEmptyTextNodesForObj === undefined) {
  3279. config.skipEmptyTextNodesForObj = true;
  3280. }
  3281. if (config.stripWhitespaces === undefined) {
  3282. config.stripWhitespaces = true;
  3283. }
  3284. config.datetimeAccessFormPaths = config.datetimeAccessFormPaths || [];
  3285. if (config.useDoubleQuotes === undefined) {
  3286. config.useDoubleQuotes = false;
  3287. }
  3288. config.xmlElementsFilter = config.xmlElementsFilter || [];
  3289. config.jsonPropertiesFilter = config.jsonPropertiesFilter || [];
  3290. if (config.keepCData === undefined) {
  3291. config.keepCData = false;
  3292. }
  3293. }
  3294. var DOMNodeTypes = {
  3295. ELEMENT_NODE: 1,
  3296. TEXT_NODE: 3,
  3297. CDATA_SECTION_NODE: 4,
  3298. COMMENT_NODE: 8,
  3299. DOCUMENT_NODE: 9
  3300. };
  3301. function initRequiredPolyfills() {}
  3302. function getNodeLocalName(node) {
  3303. var nodeLocalName = node.localName;
  3304. if (nodeLocalName == null) // Yeah, this is IE!!
  3305. nodeLocalName = node.baseName;
  3306. if (nodeLocalName == null || nodeLocalName == "") // =="" is IE too
  3307. nodeLocalName = node.nodeName;
  3308. return nodeLocalName;
  3309. }
  3310. function getNodePrefix(node) {
  3311. return node.prefix;
  3312. }
  3313. function escapeXmlChars(str) {
  3314. if (typeof str == "string") return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;');else return str;
  3315. }
  3316. function unescapeXmlChars(str) {
  3317. return str.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&amp;/g, '&');
  3318. }
  3319. function checkInStdFiltersArrayForm(stdFiltersArrayForm, obj, name, path) {
  3320. var idx = 0;
  3321. for (; idx < stdFiltersArrayForm.length; idx++) {
  3322. var filterPath = stdFiltersArrayForm[idx];
  3323. if (typeof filterPath === "string") {
  3324. if (filterPath == path) break;
  3325. } else if (filterPath instanceof RegExp) {
  3326. if (filterPath.test(path)) break;
  3327. } else if (typeof filterPath === "function") {
  3328. if (filterPath(obj, name, path)) break;
  3329. }
  3330. }
  3331. return idx != stdFiltersArrayForm.length;
  3332. }
  3333. function toArrayAccessForm(obj, childName, path) {
  3334. switch (config.arrayAccessForm) {
  3335. case "property":
  3336. if (!(obj[childName] instanceof Array)) obj[childName + "_asArray"] = [obj[childName]];else obj[childName + "_asArray"] = obj[childName];
  3337. break;
  3338. /*case "none":
  3339. break;*/
  3340. }
  3341. if (!(obj[childName] instanceof Array) && config.arrayAccessFormPaths.length > 0) {
  3342. if (checkInStdFiltersArrayForm(config.arrayAccessFormPaths, obj, childName, path)) {
  3343. obj[childName] = [obj[childName]];
  3344. }
  3345. }
  3346. }
  3347. function fromXmlDateTime(prop) {
  3348. // Implementation based up on http://stackoverflow.com/questions/8178598/xml-datetime-to-javascript-date-object
  3349. // Improved to support full spec and optional parts
  3350. var bits = prop.split(/[-T:+Z]/g);
  3351. var d = new Date(bits[0], bits[1] - 1, bits[2]);
  3352. var secondBits = bits[5].split("\.");
  3353. d.setHours(bits[3], bits[4], secondBits[0]);
  3354. if (secondBits.length > 1) d.setMilliseconds(secondBits[1]);
  3355. // Get supplied time zone offset in minutes
  3356. if (bits[6] && bits[7]) {
  3357. var offsetMinutes = bits[6] * 60 + Number(bits[7]);
  3358. var sign = /\d\d-\d\d:\d\d$/.test(prop) ? '-' : '+';
  3359. // Apply the sign
  3360. offsetMinutes = 0 + (sign == '-' ? -1 * offsetMinutes : offsetMinutes);
  3361. // Apply offset and local timezone
  3362. d.setMinutes(d.getMinutes() - offsetMinutes - d.getTimezoneOffset());
  3363. } else if (prop.indexOf("Z", prop.length - 1) !== -1) {
  3364. d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds()));
  3365. }
  3366. // d is now a local time equivalent to the supplied time
  3367. return d;
  3368. }
  3369. function checkFromXmlDateTimePaths(value, childName, fullPath) {
  3370. if (config.datetimeAccessFormPaths.length > 0) {
  3371. var path = fullPath.split("\.#")[0];
  3372. if (checkInStdFiltersArrayForm(config.datetimeAccessFormPaths, value, childName, path)) {
  3373. return fromXmlDateTime(value);
  3374. } else return value;
  3375. } else return value;
  3376. }
  3377. function checkXmlElementsFilter(obj, childType, childName, childPath) {
  3378. if (childType == DOMNodeTypes.ELEMENT_NODE && config.xmlElementsFilter.length > 0) {
  3379. return checkInStdFiltersArrayForm(config.xmlElementsFilter, obj, childName, childPath);
  3380. } else return true;
  3381. }
  3382. function parseDOMChildren(node, path) {
  3383. if (node.nodeType == DOMNodeTypes.DOCUMENT_NODE) {
  3384. var result = new Object();
  3385. var nodeChildren = node.childNodes;
  3386. // Alternative for firstElementChild which is not supported in some environments
  3387. for (var cidx = 0; cidx < nodeChildren.length; cidx++) {
  3388. var child = nodeChildren.item(cidx);
  3389. if (child.nodeType == DOMNodeTypes.ELEMENT_NODE) {
  3390. var childName = getNodeLocalName(child);
  3391. result[childName] = parseDOMChildren(child, childName);
  3392. }
  3393. }
  3394. return result;
  3395. } else if (node.nodeType == DOMNodeTypes.ELEMENT_NODE) {
  3396. var result = new Object();
  3397. result.__cnt = 0;
  3398. var nodeChildren = node.childNodes;
  3399. // Children nodes
  3400. for (var cidx = 0; cidx < nodeChildren.length; cidx++) {
  3401. var child = nodeChildren.item(cidx); // nodeChildren[cidx];
  3402. var childName = getNodeLocalName(child);
  3403. if (child.nodeType != DOMNodeTypes.COMMENT_NODE) {
  3404. var childPath = path + "." + childName;
  3405. if (checkXmlElementsFilter(result, child.nodeType, childName, childPath)) {
  3406. result.__cnt++;
  3407. if (result[childName] == null) {
  3408. result[childName] = parseDOMChildren(child, childPath);
  3409. toArrayAccessForm(result, childName, childPath);
  3410. } else {
  3411. if (result[childName] != null) {
  3412. if (!(result[childName] instanceof Array)) {
  3413. result[childName] = [result[childName]];
  3414. toArrayAccessForm(result, childName, childPath);
  3415. }
  3416. }
  3417. result[childName][result[childName].length] = parseDOMChildren(child, childPath);
  3418. }
  3419. }
  3420. }
  3421. }
  3422. // Attributes
  3423. for (var aidx = 0; aidx < node.attributes.length; aidx++) {
  3424. var attr = node.attributes.item(aidx); // [aidx];
  3425. result.__cnt++;
  3426. result[config.attributePrefix + attr.name] = attr.value;
  3427. }
  3428. // Node namespace prefix
  3429. var nodePrefix = getNodePrefix(node);
  3430. if (nodePrefix != null && nodePrefix != "") {
  3431. result.__cnt++;
  3432. result.__prefix = nodePrefix;
  3433. }
  3434. if (result["#text"] != null) {
  3435. result.__text = result["#text"];
  3436. if (result.__text instanceof Array) {
  3437. result.__text = result.__text.join("\n");
  3438. }
  3439. //if(config.escapeMode)
  3440. // result.__text = unescapeXmlChars(result.__text);
  3441. if (config.stripWhitespaces) result.__text = result.__text.trim();
  3442. delete result["#text"];
  3443. if (config.arrayAccessForm == "property") delete result["#text_asArray"];
  3444. result.__text = checkFromXmlDateTimePaths(result.__text, childName, path + "." + childName);
  3445. }
  3446. if (result["#cdata-section"] != null) {
  3447. result.__cdata = result["#cdata-section"];
  3448. delete result["#cdata-section"];
  3449. if (config.arrayAccessForm == "property") delete result["#cdata-section_asArray"];
  3450. }
  3451. if (result.__cnt == 0 && config.emptyNodeForm == "text") {
  3452. result = '';
  3453. } else if (result.__cnt == 1 && result.__text != null) {
  3454. result = result.__text;
  3455. } else if (result.__cnt == 1 && result.__cdata != null && !config.keepCData) {
  3456. result = result.__cdata;
  3457. } else if (result.__cnt > 1 && result.__text != null && config.skipEmptyTextNodesForObj) {
  3458. if (config.stripWhitespaces && result.__text == "" || result.__text.trim() == "") {
  3459. delete result.__text;
  3460. }
  3461. }
  3462. delete result.__cnt;
  3463. if (config.enableToStringFunc && (result.__text != null || result.__cdata != null)) {
  3464. result.toString = function () {
  3465. return (this.__text != null ? this.__text : '') + (this.__cdata != null ? this.__cdata : '');
  3466. };
  3467. }
  3468. return result;
  3469. } else if (node.nodeType == DOMNodeTypes.TEXT_NODE || node.nodeType == DOMNodeTypes.CDATA_SECTION_NODE) {
  3470. return node.nodeValue;
  3471. }
  3472. }
  3473. function startTag(jsonObj, element, attrList, closed) {
  3474. var resultStr = "<" + (jsonObj != null && jsonObj.__prefix != null ? jsonObj.__prefix + ":" : "") + element;
  3475. if (attrList != null) {
  3476. for (var aidx = 0; aidx < attrList.length; aidx++) {
  3477. var attrName = attrList[aidx];
  3478. var attrVal = jsonObj[attrName];
  3479. if (config.escapeMode) attrVal = escapeXmlChars(attrVal);
  3480. resultStr += " " + attrName.substr(config.attributePrefix.length) + "=";
  3481. if (config.useDoubleQuotes) resultStr += '"' + attrVal + '"';else resultStr += "'" + attrVal + "'";
  3482. }
  3483. }
  3484. if (!closed) resultStr += ">";else resultStr += "/>";
  3485. return resultStr;
  3486. }
  3487. function endTag(jsonObj, elementName) {
  3488. return "</" + (jsonObj.__prefix != null ? jsonObj.__prefix + ":" : "") + elementName + ">";
  3489. }
  3490. function endsWith(str, suffix) {
  3491. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  3492. }
  3493. function jsonXmlSpecialElem(jsonObj, jsonObjField) {
  3494. 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;
  3495. }
  3496. function jsonXmlElemCount(jsonObj) {
  3497. var elementsCnt = 0;
  3498. if (jsonObj instanceof Object) {
  3499. for (var it in jsonObj) {
  3500. if (jsonXmlSpecialElem(jsonObj, it)) continue;
  3501. elementsCnt++;
  3502. }
  3503. }
  3504. return elementsCnt;
  3505. }
  3506. function checkJsonObjPropertiesFilter(jsonObj, propertyName, jsonObjPath) {
  3507. return config.jsonPropertiesFilter.length == 0 || jsonObjPath == "" || checkInStdFiltersArrayForm(config.jsonPropertiesFilter, jsonObj, propertyName, jsonObjPath);
  3508. }
  3509. function parseJSONAttributes(jsonObj) {
  3510. var attrList = [];
  3511. if (jsonObj instanceof Object) {
  3512. for (var ait in jsonObj) {
  3513. if (ait.toString().indexOf("__") == -1 && ait.toString().indexOf(config.attributePrefix) == 0) {
  3514. attrList.push(ait);
  3515. }
  3516. }
  3517. }
  3518. return attrList;
  3519. }
  3520. function parseJSONTextAttrs(jsonTxtObj) {
  3521. var result = "";
  3522. if (jsonTxtObj.__cdata != null) {
  3523. result += "<![CDATA[" + jsonTxtObj.__cdata + "]]>";
  3524. }
  3525. if (jsonTxtObj.__text != null) {
  3526. if (config.escapeMode) result += escapeXmlChars(jsonTxtObj.__text);else result += jsonTxtObj.__text;
  3527. }
  3528. return result;
  3529. }
  3530. function parseJSONTextObject(jsonTxtObj) {
  3531. var result = "";
  3532. if (jsonTxtObj instanceof Object) {
  3533. result += parseJSONTextAttrs(jsonTxtObj);
  3534. } else if (jsonTxtObj != null) {
  3535. if (config.escapeMode) result += escapeXmlChars(jsonTxtObj);else result += jsonTxtObj;
  3536. }
  3537. return result;
  3538. }
  3539. function getJsonPropertyPath(jsonObjPath, jsonPropName) {
  3540. if (jsonObjPath === "") {
  3541. return jsonPropName;
  3542. } else return jsonObjPath + "." + jsonPropName;
  3543. }
  3544. function parseJSONArray(jsonArrRoot, jsonArrObj, attrList, jsonObjPath) {
  3545. var result = "";
  3546. if (jsonArrRoot.length == 0) {
  3547. result += startTag(jsonArrRoot, jsonArrObj, attrList, true);
  3548. } else {
  3549. for (var arIdx = 0; arIdx < jsonArrRoot.length; arIdx++) {
  3550. result += startTag(jsonArrRoot[arIdx], jsonArrObj, parseJSONAttributes(jsonArrRoot[arIdx]), false);
  3551. result += parseJSONObject(jsonArrRoot[arIdx], getJsonPropertyPath(jsonObjPath, jsonArrObj));
  3552. result += endTag(jsonArrRoot[arIdx], jsonArrObj);
  3553. }
  3554. }
  3555. return result;
  3556. }
  3557. function parseJSONObject(jsonObj, jsonObjPath) {
  3558. var result = "";
  3559. var elementsCnt = jsonXmlElemCount(jsonObj);
  3560. if (elementsCnt > 0) {
  3561. for (var it in jsonObj) {
  3562. if (jsonXmlSpecialElem(jsonObj, it) || jsonObjPath != "" && !checkJsonObjPropertiesFilter(jsonObj, it, getJsonPropertyPath(jsonObjPath, it))) continue;
  3563. var subObj = jsonObj[it];
  3564. var attrList = parseJSONAttributes(subObj);
  3565. if (subObj == null || subObj == undefined) {
  3566. result += startTag(subObj, it, attrList, true);
  3567. } else if (subObj instanceof Object) {
  3568. if (subObj instanceof Array) {
  3569. result += parseJSONArray(subObj, it, attrList, jsonObjPath);
  3570. } else if (subObj instanceof Date) {
  3571. result += startTag(subObj, it, attrList, false);
  3572. result += subObj.toISOString();
  3573. result += endTag(subObj, it);
  3574. } else {
  3575. var subObjElementsCnt = jsonXmlElemCount(subObj);
  3576. if (subObjElementsCnt > 0 || subObj.__text != null || subObj.__cdata != null) {
  3577. result += startTag(subObj, it, attrList, false);
  3578. result += parseJSONObject(subObj, getJsonPropertyPath(jsonObjPath, it));
  3579. result += endTag(subObj, it);
  3580. } else {
  3581. result += startTag(subObj, it, attrList, true);
  3582. }
  3583. }
  3584. } else {
  3585. result += startTag(subObj, it, attrList, false);
  3586. result += parseJSONTextObject(subObj);
  3587. result += endTag(subObj, it);
  3588. }
  3589. }
  3590. }
  3591. result += parseJSONTextObject(jsonObj);
  3592. return result;
  3593. }
  3594. this.parseXmlString = function (xmlDocStr) {
  3595. // var isIEParser = window.ActiveXObject || "ActiveXObject" in window;
  3596. var isIEParser = false;
  3597. if (xmlDocStr === undefined) {
  3598. return null;
  3599. }
  3600. var xmlDoc;
  3601. if (DOMParser) {
  3602. var parser = new DOMParser();
  3603. var parsererrorNS = null;
  3604. // IE9+ now is here
  3605. if (!isIEParser) {
  3606. try {
  3607. parsererrorNS = parser.parseFromString("INVALID", "text/xml").getElementsByTagName("parsererror")[0].namespaceURI;
  3608. } catch (err) {
  3609. parsererrorNS = null;
  3610. }
  3611. }
  3612. try {
  3613. xmlDoc = parser.parseFromString(xmlDocStr, "text/xml");
  3614. if (parsererrorNS != null && xmlDoc.getElementsByTagNameNS(parsererrorNS, "parsererror").length > 0) {
  3615. //throw new Error('Error parsing XML: '+xmlDocStr);
  3616. xmlDoc = null;
  3617. }
  3618. } catch (err) {
  3619. xmlDoc = null;
  3620. }
  3621. } else {
  3622. // IE :(
  3623. if (xmlDocStr.indexOf("<?") == 0) {
  3624. xmlDocStr = xmlDocStr.substr(xmlDocStr.indexOf("?>") + 2);
  3625. }
  3626. xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  3627. xmlDoc.async = "false";
  3628. xmlDoc.loadXML(xmlDocStr);
  3629. }
  3630. return xmlDoc;
  3631. };
  3632. this.asArray = function (prop) {
  3633. if (prop === undefined || prop == null) return [];else if (prop instanceof Array) return prop;else return [prop];
  3634. };
  3635. this.toXmlDateTime = function (dt) {
  3636. if (dt instanceof Date) return dt.toISOString();else if (typeof dt === 'number') return new Date(dt).toISOString();else return null;
  3637. };
  3638. this.asDateTime = function (prop) {
  3639. if (typeof prop == "string") {
  3640. return fromXmlDateTime(prop);
  3641. } else return prop;
  3642. };
  3643. this.xml2json = function (xmlDoc) {
  3644. return parseDOMChildren(xmlDoc);
  3645. };
  3646. this.xml_str2json = function (xmlDocStr) {
  3647. var xmlDoc = this.parseXmlString(xmlDocStr);
  3648. if (xmlDoc != null) return this.xml2json(xmlDoc);else return null;
  3649. };
  3650. this.json2xml_str = function (jsonObj) {
  3651. return parseJSONObject(jsonObj, "");
  3652. };
  3653. this.json2xml = function (jsonObj) {
  3654. var xmlDocStr = this.json2xml_str(jsonObj);
  3655. return this.parseXmlString(xmlDocStr);
  3656. };
  3657. this.getVersion = function () {
  3658. return VERSION;
  3659. };
  3660. };
  3661. var xml2json = function xml2json(str) {
  3662. if (!str) return null;
  3663. var parser = new DOMParser();
  3664. var xmlDoc = parser.parseFromString(str, "text/xml");
  3665. var x2jsObj = new x2js();
  3666. var data = x2jsObj.xml2json(xmlDoc);
  3667. if (data.html && data.getElementsByTagName('parsererror').length) {
  3668. return null;
  3669. } else {
  3670. return data;
  3671. }
  3672. };
  3673. var json2xml = function json2xml(data) {
  3674. var x2jsObj = new x2js();
  3675. return x2jsObj.json2xml(data);
  3676. };
  3677. module.exports = xml2json;
  3678. /***/ }),
  3679. /* 14 */
  3680. /***/ (function(module, exports, __webpack_require__) {
  3681. "use strict";
  3682. function DOMParser(options) {
  3683. this.options = options || { locator: {} };
  3684. }
  3685. DOMParser.prototype.parseFromString = function (source, mimeType) {
  3686. var options = this.options;
  3687. var sax = new XMLReader();
  3688. var domBuilder = options.domBuilder || new DOMHandler(); //contentHandler and LexicalHandler
  3689. var errorHandler = options.errorHandler;
  3690. var locator = options.locator;
  3691. var defaultNSMap = options.xmlns || {};
  3692. var entityMap = { 'lt': '<', 'gt': '>', 'amp': '&', 'quot': '"', 'apos': "'" };
  3693. if (locator) {
  3694. domBuilder.setDocumentLocator(locator);
  3695. }
  3696. sax.errorHandler = buildErrorHandler(errorHandler, domBuilder, locator);
  3697. sax.domBuilder = options.domBuilder || domBuilder;
  3698. if (/\/x?html?$/.test(mimeType)) {
  3699. entityMap.nbsp = '\xa0';
  3700. entityMap.copy = '\xa9';
  3701. defaultNSMap[''] = 'http://www.w3.org/1999/xhtml';
  3702. }
  3703. defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace';
  3704. if (source) {
  3705. sax.parse(source, defaultNSMap, entityMap);
  3706. } else {
  3707. sax.errorHandler.error("invalid doc source");
  3708. }
  3709. return domBuilder.doc;
  3710. };
  3711. function buildErrorHandler(errorImpl, domBuilder, locator) {
  3712. if (!errorImpl) {
  3713. if (domBuilder instanceof DOMHandler) {
  3714. return domBuilder;
  3715. }
  3716. errorImpl = domBuilder;
  3717. }
  3718. var errorHandler = {};
  3719. var isCallback = errorImpl instanceof Function;
  3720. locator = locator || {};
  3721. function build(key) {
  3722. var fn = errorImpl[key];
  3723. if (!fn && isCallback) {
  3724. fn = errorImpl.length == 2 ? function (msg) {
  3725. errorImpl(key, msg);
  3726. } : errorImpl;
  3727. }
  3728. errorHandler[key] = fn && function (msg) {
  3729. fn('[xmldom ' + key + ']\t' + msg + _locator(locator));
  3730. } || function () {};
  3731. }
  3732. build('warning');
  3733. build('error');
  3734. build('fatalError');
  3735. return errorHandler;
  3736. }
  3737. //console.log('#\n\n\n\n\n\n\n####')
  3738. /**
  3739. * +ContentHandler+ErrorHandler
  3740. * +LexicalHandler+EntityResolver2
  3741. * -DeclHandler-DTDHandler
  3742. *
  3743. * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
  3744. * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
  3745. * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
  3746. */
  3747. function DOMHandler() {
  3748. this.cdata = false;
  3749. }
  3750. function position(locator, node) {
  3751. node.lineNumber = locator.lineNumber;
  3752. node.columnNumber = locator.columnNumber;
  3753. }
  3754. /**
  3755. * @see org.xml.sax.ContentHandler#startDocument
  3756. * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
  3757. */
  3758. DOMHandler.prototype = {
  3759. startDocument: function startDocument() {
  3760. this.doc = new DOMImplementation().createDocument(null, null, null);
  3761. if (this.locator) {
  3762. this.doc.documentURI = this.locator.systemId;
  3763. }
  3764. },
  3765. startElement: function startElement(namespaceURI, localName, qName, attrs) {
  3766. var doc = this.doc;
  3767. var el = doc.createElementNS(namespaceURI, qName || localName);
  3768. var len = attrs.length;
  3769. appendElement(this, el);
  3770. this.currentElement = el;
  3771. this.locator && position(this.locator, el);
  3772. for (var i = 0; i < len; i++) {
  3773. var namespaceURI = attrs.getURI(i);
  3774. var value = attrs.getValue(i);
  3775. var qName = attrs.getQName(i);
  3776. var attr = doc.createAttributeNS(namespaceURI, qName);
  3777. this.locator && position(attrs.getLocator(i), attr);
  3778. attr.value = attr.nodeValue = value;
  3779. el.setAttributeNode(attr);
  3780. }
  3781. },
  3782. endElement: function endElement(namespaceURI, localName, qName) {
  3783. var current = this.currentElement;
  3784. var tagName = current.tagName;
  3785. this.currentElement = current.parentNode;
  3786. },
  3787. startPrefixMapping: function startPrefixMapping(prefix, uri) {},
  3788. endPrefixMapping: function endPrefixMapping(prefix) {},
  3789. processingInstruction: function processingInstruction(target, data) {
  3790. var ins = this.doc.createProcessingInstruction(target, data);
  3791. this.locator && position(this.locator, ins);
  3792. appendElement(this, ins);
  3793. },
  3794. ignorableWhitespace: function ignorableWhitespace(ch, start, length) {},
  3795. characters: function characters(chars, start, length) {
  3796. chars = _toString.apply(this, arguments);
  3797. //console.log(chars)
  3798. if (chars) {
  3799. if (this.cdata) {
  3800. var charNode = this.doc.createCDATASection(chars);
  3801. } else {
  3802. var charNode = this.doc.createTextNode(chars);
  3803. }
  3804. if (this.currentElement) {
  3805. this.currentElement.appendChild(charNode);
  3806. } else if (/^\s*$/.test(chars)) {
  3807. this.doc.appendChild(charNode);
  3808. //process xml
  3809. }
  3810. this.locator && position(this.locator, charNode);
  3811. }
  3812. },
  3813. skippedEntity: function skippedEntity(name) {},
  3814. endDocument: function endDocument() {
  3815. this.doc.normalize();
  3816. },
  3817. setDocumentLocator: function setDocumentLocator(locator) {
  3818. if (this.locator = locator) {
  3819. // && !('lineNumber' in locator)){
  3820. locator.lineNumber = 0;
  3821. }
  3822. },
  3823. //LexicalHandler
  3824. comment: function comment(chars, start, length) {
  3825. chars = _toString.apply(this, arguments);
  3826. var comm = this.doc.createComment(chars);
  3827. this.locator && position(this.locator, comm);
  3828. appendElement(this, comm);
  3829. },
  3830. startCDATA: function startCDATA() {
  3831. //used in characters() methods
  3832. this.cdata = true;
  3833. },
  3834. endCDATA: function endCDATA() {
  3835. this.cdata = false;
  3836. },
  3837. startDTD: function startDTD(name, publicId, systemId) {
  3838. var impl = this.doc.implementation;
  3839. if (impl && impl.createDocumentType) {
  3840. var dt = impl.createDocumentType(name, publicId, systemId);
  3841. this.locator && position(this.locator, dt);
  3842. appendElement(this, dt);
  3843. }
  3844. },
  3845. /**
  3846. * @see org.xml.sax.ErrorHandler
  3847. * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
  3848. */
  3849. warning: function warning(error) {
  3850. console.warn('[xmldom warning]\t' + error, _locator(this.locator));
  3851. },
  3852. error: function error(_error) {
  3853. console.error('[xmldom error]\t' + _error, _locator(this.locator));
  3854. },
  3855. fatalError: function fatalError(error) {
  3856. console.error('[xmldom fatalError]\t' + error, _locator(this.locator));
  3857. throw error;
  3858. }
  3859. };
  3860. function _locator(l) {
  3861. if (l) {
  3862. return '\n@' + (l.systemId || '') + '#[line:' + l.lineNumber + ',col:' + l.columnNumber + ']';
  3863. }
  3864. }
  3865. function _toString(chars, start, length) {
  3866. if (typeof chars == 'string') {
  3867. return chars.substr(start, length);
  3868. } else {
  3869. //java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
  3870. if (chars.length >= start + length || start) {
  3871. return new java.lang.String(chars, start, length) + '';
  3872. }
  3873. return chars;
  3874. }
  3875. }
  3876. /*
  3877. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
  3878. * used method of org.xml.sax.ext.LexicalHandler:
  3879. * #comment(chars, start, length)
  3880. * #startCDATA()
  3881. * #endCDATA()
  3882. * #startDTD(name, publicId, systemId)
  3883. *
  3884. *
  3885. * IGNORED method of org.xml.sax.ext.LexicalHandler:
  3886. * #endDTD()
  3887. * #startEntity(name)
  3888. * #endEntity(name)
  3889. *
  3890. *
  3891. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
  3892. * IGNORED method of org.xml.sax.ext.DeclHandler
  3893. * #attributeDecl(eName, aName, type, mode, value)
  3894. * #elementDecl(name, model)
  3895. * #externalEntityDecl(name, publicId, systemId)
  3896. * #internalEntityDecl(name, value)
  3897. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
  3898. * IGNORED method of org.xml.sax.EntityResolver2
  3899. * #resolveEntity(String name,String publicId,String baseURI,String systemId)
  3900. * #resolveEntity(publicId, systemId)
  3901. * #getExternalSubset(name, baseURI)
  3902. * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
  3903. * IGNORED method of org.xml.sax.DTDHandler
  3904. * #notationDecl(name, publicId, systemId) {};
  3905. * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
  3906. */
  3907. "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g, function (key) {
  3908. DOMHandler.prototype[key] = function () {
  3909. return null;
  3910. };
  3911. });
  3912. /* 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 */
  3913. function appendElement(hander, node) {
  3914. if (!hander.currentElement) {
  3915. hander.doc.appendChild(node);
  3916. } else {
  3917. hander.currentElement.appendChild(node);
  3918. }
  3919. } //appendChild and setAttributeNS are preformance key
  3920. //if(typeof require == 'function'){
  3921. var XMLReader = __webpack_require__(15).XMLReader;
  3922. var DOMImplementation = exports.DOMImplementation = __webpack_require__(2).DOMImplementation;
  3923. exports.XMLSerializer = __webpack_require__(2).XMLSerializer;
  3924. exports.DOMParser = DOMParser;
  3925. //}
  3926. /***/ }),
  3927. /* 15 */
  3928. /***/ (function(module, exports, __webpack_require__) {
  3929. "use strict";
  3930. //[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]
  3931. //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
  3932. //[5] Name ::= NameStartChar (NameChar)*
  3933. 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
  3934. var nameChar = new RegExp("[\\-\\.0-9" + nameStartChar.source.slice(1, -1) + "\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
  3935. var tagNamePattern = new RegExp('^' + nameStartChar.source + nameChar.source + '*(?:\:' + nameStartChar.source + nameChar.source + '*)?$');
  3936. //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
  3937. //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(',')
  3938. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  3939. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  3940. var S_TAG = 0; //tag name offerring
  3941. var S_ATTR = 1; //attr name offerring
  3942. var S_ATTR_SPACE = 2; //attr name end and space offer
  3943. var S_EQ = 3; //=space?
  3944. var S_ATTR_NOQUOT_VALUE = 4; //attr value(no quot value only)
  3945. var S_ATTR_END = 5; //attr value end and no space(quot end)
  3946. var S_TAG_SPACE = 6; //(attr value end || tag end ) && (space offer)
  3947. var S_TAG_CLOSE = 7; //closed el<el />
  3948. function XMLReader() {}
  3949. XMLReader.prototype = {
  3950. parse: function parse(source, defaultNSMap, entityMap) {
  3951. var domBuilder = this.domBuilder;
  3952. domBuilder.startDocument();
  3953. _copy(defaultNSMap, defaultNSMap = {});
  3954. _parse(source, defaultNSMap, entityMap, domBuilder, this.errorHandler);
  3955. domBuilder.endDocument();
  3956. }
  3957. };
  3958. function _parse(source, defaultNSMapCopy, entityMap, domBuilder, errorHandler) {
  3959. function fixedFromCharCode(code) {
  3960. // String.prototype.fromCharCode does not supports
  3961. // > 2 bytes unicode chars directly
  3962. if (code > 0xffff) {
  3963. code -= 0x10000;
  3964. var surrogate1 = 0xd800 + (code >> 10),
  3965. surrogate2 = 0xdc00 + (code & 0x3ff);
  3966. return String.fromCharCode(surrogate1, surrogate2);
  3967. } else {
  3968. return String.fromCharCode(code);
  3969. }
  3970. }
  3971. function entityReplacer(a) {
  3972. var k = a.slice(1, -1);
  3973. if (k in entityMap) {
  3974. return entityMap[k];
  3975. } else if (k.charAt(0) === '#') {
  3976. return fixedFromCharCode(parseInt(k.substr(1).replace('x', '0x')));
  3977. } else {
  3978. errorHandler.error('entity not found:' + a);
  3979. return a;
  3980. }
  3981. }
  3982. function appendText(end) {
  3983. //has some bugs
  3984. if (end > start) {
  3985. var xt = source.substring(start, end).replace(/&#?\w+;/g, entityReplacer);
  3986. locator && position(start);
  3987. domBuilder.characters(xt, 0, end - start);
  3988. start = end;
  3989. }
  3990. }
  3991. function position(p, m) {
  3992. while (p >= lineEnd && (m = linePattern.exec(source))) {
  3993. lineStart = m.index;
  3994. lineEnd = lineStart + m[0].length;
  3995. locator.lineNumber++;
  3996. //console.log('line++:',locator,startPos,endPos)
  3997. }
  3998. locator.columnNumber = p - lineStart + 1;
  3999. }
  4000. var lineStart = 0;
  4001. var lineEnd = 0;
  4002. var linePattern = /.*(?:\r\n?|\n)|.*$/g;
  4003. var locator = domBuilder.locator;
  4004. var parseStack = [{ currentNSMap: defaultNSMapCopy }];
  4005. var closeMap = {};
  4006. var start = 0;
  4007. while (true) {
  4008. try {
  4009. var tagStart = source.indexOf('<', start);
  4010. if (tagStart < 0) {
  4011. if (!source.substr(start).match(/^\s*$/)) {
  4012. var doc = domBuilder.doc;
  4013. var text = doc.createTextNode(source.substr(start));
  4014. doc.appendChild(text);
  4015. domBuilder.currentElement = text;
  4016. }
  4017. return;
  4018. }
  4019. if (tagStart > start) {
  4020. appendText(tagStart);
  4021. }
  4022. switch (source.charAt(tagStart + 1)) {
  4023. case '/':
  4024. var end = source.indexOf('>', tagStart + 3);
  4025. var tagName = source.substring(tagStart + 2, end);
  4026. var config = parseStack.pop();
  4027. if (end < 0) {
  4028. tagName = source.substring(tagStart + 2).replace(/[\s<].*/, '');
  4029. //console.error('#@@@@@@'+tagName)
  4030. errorHandler.error("end tag name: " + tagName + ' is not complete:' + config.tagName);
  4031. end = tagStart + 1 + tagName.length;
  4032. } else if (tagName.match(/\s</)) {
  4033. tagName = tagName.replace(/[\s<].*/, '');
  4034. errorHandler.error("end tag name: " + tagName + ' maybe not complete');
  4035. end = tagStart + 1 + tagName.length;
  4036. }
  4037. //console.error(parseStack.length,parseStack)
  4038. //console.error(config);
  4039. var localNSMap = config.localNSMap;
  4040. var endMatch = config.tagName == tagName;
  4041. var endIgnoreCaseMach = endMatch || config.tagName && config.tagName.toLowerCase() == tagName.toLowerCase();
  4042. if (endIgnoreCaseMach) {
  4043. domBuilder.endElement(config.uri, config.localName, tagName);
  4044. if (localNSMap) {
  4045. for (var prefix in localNSMap) {
  4046. domBuilder.endPrefixMapping(prefix);
  4047. }
  4048. }
  4049. if (!endMatch) {
  4050. errorHandler.fatalError("end tag name: " + tagName + ' is not match the current start tagName:' + config.tagName);
  4051. }
  4052. } else {
  4053. parseStack.push(config);
  4054. }
  4055. end++;
  4056. break;
  4057. // end elment
  4058. case '?':
  4059. // <?...?>
  4060. locator && position(tagStart);
  4061. end = parseInstruction(source, tagStart, domBuilder);
  4062. break;
  4063. case '!':
  4064. // <!doctype,<![CDATA,<!--
  4065. locator && position(tagStart);
  4066. end = parseDCC(source, tagStart, domBuilder, errorHandler);
  4067. break;
  4068. default:
  4069. locator && position(tagStart);
  4070. var el = new ElementAttributes();
  4071. var currentNSMap = parseStack[parseStack.length - 1].currentNSMap;
  4072. //elStartEnd
  4073. var end = parseElementStartPart(source, tagStart, el, currentNSMap, entityReplacer, errorHandler);
  4074. var len = el.length;
  4075. if (!el.closed && fixSelfClosed(source, end, el.tagName, closeMap)) {
  4076. el.closed = true;
  4077. if (!entityMap.nbsp) {
  4078. errorHandler.warning('unclosed xml attribute');
  4079. }
  4080. }
  4081. if (locator && len) {
  4082. var locator2 = copyLocator(locator, {});
  4083. //try{//attribute position fixed
  4084. for (var i = 0; i < len; i++) {
  4085. var a = el[i];
  4086. position(a.offset);
  4087. a.locator = copyLocator(locator, {});
  4088. }
  4089. //}catch(e){console.error('@@@@@'+e)}
  4090. domBuilder.locator = locator2;
  4091. if (appendElement(el, domBuilder, currentNSMap)) {
  4092. parseStack.push(el);
  4093. }
  4094. domBuilder.locator = locator;
  4095. } else {
  4096. if (appendElement(el, domBuilder, currentNSMap)) {
  4097. parseStack.push(el);
  4098. }
  4099. }
  4100. if (el.uri === 'http://www.w3.org/1999/xhtml' && !el.closed) {
  4101. end = parseHtmlSpecialContent(source, end, el.tagName, entityReplacer, domBuilder);
  4102. } else {
  4103. end++;
  4104. }
  4105. }
  4106. } catch (e) {
  4107. errorHandler.error('element parse error: ' + e);
  4108. //errorHandler.error('element parse error: '+e);
  4109. end = -1;
  4110. //throw e;
  4111. }
  4112. if (end > start) {
  4113. start = end;
  4114. } else {
  4115. //TODO: 这里有可能sax回退,有位置错误风险
  4116. appendText(Math.max(tagStart, start) + 1);
  4117. }
  4118. }
  4119. }
  4120. function copyLocator(f, t) {
  4121. t.lineNumber = f.lineNumber;
  4122. t.columnNumber = f.columnNumber;
  4123. return t;
  4124. }
  4125. /**
  4126. * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
  4127. * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
  4128. */
  4129. function parseElementStartPart(source, start, el, currentNSMap, entityReplacer, errorHandler) {
  4130. var attrName;
  4131. var value;
  4132. var p = ++start;
  4133. var s = S_TAG; //status
  4134. while (true) {
  4135. var c = source.charAt(p);
  4136. switch (c) {
  4137. case '=':
  4138. if (s === S_ATTR) {
  4139. //attrName
  4140. attrName = source.slice(start, p);
  4141. s = S_EQ;
  4142. } else if (s === S_ATTR_SPACE) {
  4143. s = S_EQ;
  4144. } else {
  4145. //fatalError: equal must after attrName or space after attrName
  4146. throw new Error('attribute equal must after attrName');
  4147. }
  4148. break;
  4149. case '\'':
  4150. case '"':
  4151. if (s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
  4152. ) {
  4153. //equal
  4154. if (s === S_ATTR) {
  4155. errorHandler.warning('attribute value must after "="');
  4156. attrName = source.slice(start, p);
  4157. }
  4158. start = p + 1;
  4159. p = source.indexOf(c, start);
  4160. if (p > 0) {
  4161. value = source.slice(start, p).replace(/&#?\w+;/g, entityReplacer);
  4162. el.add(attrName, value, start - 1);
  4163. s = S_ATTR_END;
  4164. } else {
  4165. //fatalError: no end quot match
  4166. throw new Error('attribute value no end \'' + c + '\' match');
  4167. }
  4168. } else if (s == S_ATTR_NOQUOT_VALUE) {
  4169. value = source.slice(start, p).replace(/&#?\w+;/g, entityReplacer);
  4170. //console.log(attrName,value,start,p)
  4171. el.add(attrName, value, start);
  4172. //console.dir(el)
  4173. errorHandler.warning('attribute "' + attrName + '" missed start quot(' + c + ')!!');
  4174. start = p + 1;
  4175. s = S_ATTR_END;
  4176. } else {
  4177. //fatalError: no equal before
  4178. throw new Error('attribute value must after "="');
  4179. }
  4180. break;
  4181. case '/':
  4182. switch (s) {
  4183. case S_TAG:
  4184. el.setTagName(source.slice(start, p));
  4185. case S_ATTR_END:
  4186. case S_TAG_SPACE:
  4187. case S_TAG_CLOSE:
  4188. s = S_TAG_CLOSE;
  4189. el.closed = true;
  4190. case S_ATTR_NOQUOT_VALUE:
  4191. case S_ATTR:
  4192. case S_ATTR_SPACE:
  4193. break;
  4194. //case S_EQ:
  4195. default:
  4196. throw new Error("attribute invalid close char('/')");
  4197. }
  4198. break;
  4199. case '':
  4200. //end document
  4201. //throw new Error('unexpected end of input')
  4202. errorHandler.error('unexpected end of input');
  4203. if (s == S_TAG) {
  4204. el.setTagName(source.slice(start, p));
  4205. }
  4206. return p;
  4207. case '>':
  4208. switch (s) {
  4209. case S_TAG:
  4210. el.setTagName(source.slice(start, p));
  4211. case S_ATTR_END:
  4212. case S_TAG_SPACE:
  4213. case S_TAG_CLOSE:
  4214. break; //normal
  4215. case S_ATTR_NOQUOT_VALUE: //Compatible state
  4216. case S_ATTR:
  4217. value = source.slice(start, p);
  4218. if (value.slice(-1) === '/') {
  4219. el.closed = true;
  4220. value = value.slice(0, -1);
  4221. }
  4222. case S_ATTR_SPACE:
  4223. if (s === S_ATTR_SPACE) {
  4224. value = attrName;
  4225. }
  4226. if (s == S_ATTR_NOQUOT_VALUE) {
  4227. errorHandler.warning('attribute "' + value + '" missed quot(")!!');
  4228. el.add(attrName, value.replace(/&#?\w+;/g, entityReplacer), start);
  4229. } else {
  4230. if (currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)) {
  4231. errorHandler.warning('attribute "' + value + '" missed value!! "' + value + '" instead!!');
  4232. }
  4233. el.add(value, value, start);
  4234. }
  4235. break;
  4236. case S_EQ:
  4237. throw new Error('attribute value missed!!');
  4238. }
  4239. // console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
  4240. return p;
  4241. /*xml space '\x20' | #x9 | #xD | #xA; */
  4242. case "\x80":
  4243. c = ' ';
  4244. default:
  4245. if (c <= ' ') {
  4246. //space
  4247. switch (s) {
  4248. case S_TAG:
  4249. el.setTagName(source.slice(start, p)); //tagName
  4250. s = S_TAG_SPACE;
  4251. break;
  4252. case S_ATTR:
  4253. attrName = source.slice(start, p);
  4254. s = S_ATTR_SPACE;
  4255. break;
  4256. case S_ATTR_NOQUOT_VALUE:
  4257. var value = source.slice(start, p).replace(/&#?\w+;/g, entityReplacer);
  4258. errorHandler.warning('attribute "' + value + '" missed quot(")!!');
  4259. el.add(attrName, value, start);
  4260. case S_ATTR_END:
  4261. s = S_TAG_SPACE;
  4262. break;
  4263. //case S_TAG_SPACE:
  4264. //case S_EQ:
  4265. //case S_ATTR_SPACE:
  4266. // void();break;
  4267. //case S_TAG_CLOSE:
  4268. //ignore warning
  4269. }
  4270. } else {
  4271. //not space
  4272. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  4273. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  4274. switch (s) {
  4275. //case S_TAG:void();break;
  4276. //case S_ATTR:void();break;
  4277. //case S_ATTR_NOQUOT_VALUE:void();break;
  4278. case S_ATTR_SPACE:
  4279. var tagName = el.tagName;
  4280. if (currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)) {
  4281. errorHandler.warning('attribute "' + attrName + '" missed value!! "' + attrName + '" instead2!!');
  4282. }
  4283. el.add(attrName, attrName, start);
  4284. start = p;
  4285. s = S_ATTR;
  4286. break;
  4287. case S_ATTR_END:
  4288. errorHandler.warning('attribute space is required"' + attrName + '"!!');
  4289. case S_TAG_SPACE:
  4290. s = S_ATTR;
  4291. start = p;
  4292. break;
  4293. case S_EQ:
  4294. s = S_ATTR_NOQUOT_VALUE;
  4295. start = p;
  4296. break;
  4297. case S_TAG_CLOSE:
  4298. throw new Error("elements closed character '/' and '>' must be connected to");
  4299. }
  4300. }
  4301. } //end outer switch
  4302. //console.log('p++',p)
  4303. p++;
  4304. }
  4305. }
  4306. /**
  4307. * @return true if has new namespace define
  4308. */
  4309. function appendElement(el, domBuilder, currentNSMap) {
  4310. var tagName = el.tagName;
  4311. var localNSMap = null;
  4312. //var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
  4313. var i = el.length;
  4314. while (i--) {
  4315. var a = el[i];
  4316. var qName = a.qName;
  4317. var value = a.value;
  4318. var nsp = qName.indexOf(':');
  4319. if (nsp > 0) {
  4320. var prefix = a.prefix = qName.slice(0, nsp);
  4321. var localName = qName.slice(nsp + 1);
  4322. var nsPrefix = prefix === 'xmlns' && localName;
  4323. } else {
  4324. localName = qName;
  4325. prefix = null;
  4326. nsPrefix = qName === 'xmlns' && '';
  4327. }
  4328. //can not set prefix,because prefix !== ''
  4329. a.localName = localName;
  4330. //prefix == null for no ns prefix attribute
  4331. if (nsPrefix !== false) {
  4332. //hack!!
  4333. if (localNSMap == null) {
  4334. localNSMap = {};
  4335. //console.log(currentNSMap,0)
  4336. _copy(currentNSMap, currentNSMap = {});
  4337. //console.log(currentNSMap,1)
  4338. }
  4339. currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
  4340. a.uri = 'http://www.w3.org/2000/xmlns/';
  4341. domBuilder.startPrefixMapping(nsPrefix, value);
  4342. }
  4343. }
  4344. var i = el.length;
  4345. while (i--) {
  4346. a = el[i];
  4347. var prefix = a.prefix;
  4348. if (prefix) {
  4349. //no prefix attribute has no namespace
  4350. if (prefix === 'xml') {
  4351. a.uri = 'http://www.w3.org/XML/1998/namespace';
  4352. }if (prefix !== 'xmlns') {
  4353. a.uri = currentNSMap[prefix || ''];
  4354. //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
  4355. }
  4356. }
  4357. }
  4358. var nsp = tagName.indexOf(':');
  4359. if (nsp > 0) {
  4360. prefix = el.prefix = tagName.slice(0, nsp);
  4361. localName = el.localName = tagName.slice(nsp + 1);
  4362. } else {
  4363. prefix = null; //important!!
  4364. localName = el.localName = tagName;
  4365. }
  4366. //no prefix element has default namespace
  4367. var ns = el.uri = currentNSMap[prefix || ''];
  4368. domBuilder.startElement(ns, localName, tagName, el);
  4369. //endPrefixMapping and startPrefixMapping have not any help for dom builder
  4370. //localNSMap = null
  4371. if (el.closed) {
  4372. domBuilder.endElement(ns, localName, tagName);
  4373. if (localNSMap) {
  4374. for (prefix in localNSMap) {
  4375. domBuilder.endPrefixMapping(prefix);
  4376. }
  4377. }
  4378. } else {
  4379. el.currentNSMap = currentNSMap;
  4380. el.localNSMap = localNSMap;
  4381. //parseStack.push(el);
  4382. return true;
  4383. }
  4384. }
  4385. function parseHtmlSpecialContent(source, elStartEnd, tagName, entityReplacer, domBuilder) {
  4386. if (/^(?:script|textarea)$/i.test(tagName)) {
  4387. var elEndStart = source.indexOf('</' + tagName + '>', elStartEnd);
  4388. var text = source.substring(elStartEnd + 1, elEndStart);
  4389. if (/[&<]/.test(text)) {
  4390. if (/^script$/i.test(tagName)) {
  4391. //if(!/\]\]>/.test(text)){
  4392. //lexHandler.startCDATA();
  4393. domBuilder.characters(text, 0, text.length);
  4394. //lexHandler.endCDATA();
  4395. return elEndStart;
  4396. //}
  4397. } //}else{//text area
  4398. text = text.replace(/&#?\w+;/g, entityReplacer);
  4399. domBuilder.characters(text, 0, text.length);
  4400. return elEndStart;
  4401. //}
  4402. }
  4403. }
  4404. return elStartEnd + 1;
  4405. }
  4406. function fixSelfClosed(source, elStartEnd, tagName, closeMap) {
  4407. //if(tagName in closeMap){
  4408. var pos = closeMap[tagName];
  4409. if (pos == null) {
  4410. //console.log(tagName)
  4411. pos = source.lastIndexOf('</' + tagName + '>');
  4412. if (pos < elStartEnd) {
  4413. //忘记闭合
  4414. pos = source.lastIndexOf('</' + tagName);
  4415. }
  4416. closeMap[tagName] = pos;
  4417. }
  4418. return pos < elStartEnd;
  4419. //}
  4420. }
  4421. function _copy(source, target) {
  4422. for (var n in source) {
  4423. target[n] = source[n];
  4424. }
  4425. }
  4426. function parseDCC(source, start, domBuilder, errorHandler) {
  4427. //sure start with '<!'
  4428. var next = source.charAt(start + 2);
  4429. switch (next) {
  4430. case '-':
  4431. if (source.charAt(start + 3) === '-') {
  4432. var end = source.indexOf('-->', start + 4);
  4433. //append comment source.substring(4,end)//<!--
  4434. if (end > start) {
  4435. domBuilder.comment(source, start + 4, end - start - 4);
  4436. return end + 3;
  4437. } else {
  4438. errorHandler.error("Unclosed comment");
  4439. return -1;
  4440. }
  4441. } else {
  4442. //error
  4443. return -1;
  4444. }
  4445. default:
  4446. if (source.substr(start + 3, 6) == 'CDATA[') {
  4447. var end = source.indexOf(']]>', start + 9);
  4448. domBuilder.startCDATA();
  4449. domBuilder.characters(source, start + 9, end - start - 9);
  4450. domBuilder.endCDATA();
  4451. return end + 3;
  4452. }
  4453. //<!DOCTYPE
  4454. //startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId)
  4455. var matchs = split(source, start);
  4456. var len = matchs.length;
  4457. if (len > 1 && /!doctype/i.test(matchs[0][0])) {
  4458. var name = matchs[1][0];
  4459. var pubid = len > 3 && /^public$/i.test(matchs[2][0]) && matchs[3][0];
  4460. var sysid = len > 4 && matchs[4][0];
  4461. var lastMatch = matchs[len - 1];
  4462. domBuilder.startDTD(name, pubid && pubid.replace(/^(['"])(.*?)\1$/, '$2'), sysid && sysid.replace(/^(['"])(.*?)\1$/, '$2'));
  4463. domBuilder.endDTD();
  4464. return lastMatch.index + lastMatch[0].length;
  4465. }
  4466. }
  4467. return -1;
  4468. }
  4469. function parseInstruction(source, start, domBuilder) {
  4470. var end = source.indexOf('?>', start);
  4471. if (end) {
  4472. var match = source.substring(start, end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
  4473. if (match) {
  4474. var len = match[0].length;
  4475. domBuilder.processingInstruction(match[1], match[2]);
  4476. return end + 2;
  4477. } else {
  4478. //error
  4479. return -1;
  4480. }
  4481. }
  4482. return -1;
  4483. }
  4484. /**
  4485. * @param source
  4486. */
  4487. function ElementAttributes(source) {}
  4488. ElementAttributes.prototype = {
  4489. setTagName: function setTagName(tagName) {
  4490. if (!tagNamePattern.test(tagName)) {
  4491. throw new Error('invalid tagName:' + tagName);
  4492. }
  4493. this.tagName = tagName;
  4494. },
  4495. add: function add(qName, value, offset) {
  4496. if (!tagNamePattern.test(qName)) {
  4497. throw new Error('invalid attribute:' + qName);
  4498. }
  4499. this[this.length++] = { qName: qName, value: value, offset: offset };
  4500. },
  4501. length: 0,
  4502. getLocalName: function getLocalName(i) {
  4503. return this[i].localName;
  4504. },
  4505. getLocator: function getLocator(i) {
  4506. return this[i].locator;
  4507. },
  4508. getQName: function getQName(i) {
  4509. return this[i].qName;
  4510. },
  4511. getURI: function getURI(i) {
  4512. return this[i].uri;
  4513. },
  4514. getValue: function getValue(i) {
  4515. return this[i].value;
  4516. }
  4517. // ,getIndex:function(uri, localName)){
  4518. // if(localName){
  4519. //
  4520. // }else{
  4521. // var qName = uri
  4522. // }
  4523. // },
  4524. // getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
  4525. // getType:function(uri,localName){}
  4526. // getType:function(i){},
  4527. };
  4528. function _set_proto_(thiz, parent) {
  4529. thiz.__proto__ = parent;
  4530. return thiz;
  4531. }
  4532. if (!(_set_proto_({}, _set_proto_.prototype) instanceof _set_proto_)) {
  4533. _set_proto_ = function _set_proto_(thiz, parent) {
  4534. function p() {};
  4535. p.prototype = parent;
  4536. p = new p();
  4537. for (parent in thiz) {
  4538. p[parent] = thiz[parent];
  4539. }
  4540. return p;
  4541. };
  4542. }
  4543. function split(source, start) {
  4544. var match;
  4545. var buf = [];
  4546. var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
  4547. reg.lastIndex = start;
  4548. reg.exec(source); //skip <
  4549. while (match = reg.exec(source)) {
  4550. buf.push(match);
  4551. if (match[1]) return buf;
  4552. }
  4553. }
  4554. exports.XMLReader = XMLReader;
  4555. /***/ }),
  4556. /* 16 */
  4557. /***/ (function(module, exports, __webpack_require__) {
  4558. "use strict";
  4559. 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; };
  4560. //copyright Ryan Day 2010 <http://ryanday.org>, Joscha Feth 2013 <http://www.feth.com> [MIT Licensed]
  4561. 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";
  4562. var element_non_start_char = "-.0-9\xB7\u0300-\u036F\u203F\u2040";
  4563. var element_replace = new RegExp("^([^" + element_start_char + "])|^((x|X)(m|M)(l|L))|([^" + element_start_char + element_non_start_char + "])", "g");
  4564. var not_safe_in_xml = /[^\x09\x0A\x0D\x20-\xFF\x85\xA0-\uD7FF\uE000-\uFDCF\uFDE0-\uFFFD]/gm;
  4565. var objKeys = function objKeys(obj) {
  4566. var l = [];
  4567. if (obj instanceof Object) {
  4568. for (var k in obj) {
  4569. if (obj.hasOwnProperty(k)) {
  4570. l.push(k);
  4571. }
  4572. }
  4573. }
  4574. return l;
  4575. };
  4576. var process_to_xml = function process_to_xml(node_data, options) {
  4577. var makeNode = function makeNode(name, content, attributes, level, hasSubNodes) {
  4578. var indent_value = options.indent !== undefined ? options.indent : "\t";
  4579. var indent = options.prettyPrint ? '\n' + new Array(level).join(indent_value) : '';
  4580. if (options.removeIllegalNameCharacters) {
  4581. name = name.replace(element_replace, '_');
  4582. }
  4583. var node = [indent, '<', name, attributes || ''];
  4584. if (content && content.length > 0) {
  4585. node.push('>');
  4586. node.push(content);
  4587. hasSubNodes && node.push(indent);
  4588. node.push('</');
  4589. node.push(name);
  4590. node.push('>');
  4591. } else {
  4592. node.push('/>');
  4593. }
  4594. return node.join('');
  4595. };
  4596. return function fn(node_data, node_descriptor, level) {
  4597. var type = typeof node_data === "undefined" ? "undefined" : _typeof(node_data);
  4598. if (Array.isArray ? Array.isArray(node_data) : node_data instanceof Array) {
  4599. type = 'array';
  4600. } else if (node_data instanceof Date) {
  4601. type = 'date';
  4602. }
  4603. switch (type) {
  4604. //if value is an array create child nodes from values
  4605. case 'array':
  4606. var ret = [];
  4607. node_data.map(function (v) {
  4608. ret.push(fn(v, 1, level + 1));
  4609. //entries that are values of an array are the only ones that can be special node descriptors
  4610. });
  4611. options.prettyPrint && ret.push('\n');
  4612. return ret.join('');
  4613. break;
  4614. case 'date':
  4615. // cast dates to ISO 8601 date (soap likes it)
  4616. return node_data.toJSON ? node_data.toJSON() : node_data + '';
  4617. break;
  4618. case 'object':
  4619. var nodes = [];
  4620. for (var name in node_data) {
  4621. if (node_data.hasOwnProperty(name)) {
  4622. if (node_data[name] instanceof Array) {
  4623. for (var j in node_data[name]) {
  4624. 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));
  4625. }
  4626. } else {
  4627. nodes.push(makeNode(name, fn(node_data[name], 0, level + 1), null, level + 1));
  4628. }
  4629. }
  4630. }
  4631. options.prettyPrint && nodes.length > 0 && nodes.push('\n');
  4632. return nodes.join('');
  4633. break;
  4634. case 'function':
  4635. return node_data();
  4636. break;
  4637. default:
  4638. return options.escape ? esc(node_data) : '' + node_data;
  4639. }
  4640. }(node_data, 0, 0);
  4641. };
  4642. var xml_header = function xml_header(standalone) {
  4643. var ret = ['<?xml version="1.0" encoding="UTF-8"'];
  4644. if (standalone) {
  4645. ret.push(' standalone="yes"');
  4646. }
  4647. ret.push('?>');
  4648. return ret.join('');
  4649. };
  4650. function esc(str) {
  4651. return ('' + str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&apos;').replace(/"/g, '&quot;').replace(not_safe_in_xml, '');
  4652. }
  4653. var json2xml = function json2xml(obj, options) {
  4654. if (!options) {
  4655. options = {
  4656. xmlHeader: {
  4657. standalone: true
  4658. },
  4659. prettyPrint: true,
  4660. indent: " "
  4661. };
  4662. }
  4663. if (typeof obj == 'string') {
  4664. try {
  4665. obj = JSON.parse(obj.toString());
  4666. } catch (e) {
  4667. return false;
  4668. }
  4669. }
  4670. var xmlheader = '';
  4671. var docType = '';
  4672. if (options) {
  4673. if ((typeof options === "undefined" ? "undefined" : _typeof(options)) == 'object') {
  4674. // our config is an object
  4675. if (options.xmlHeader) {
  4676. // the user wants an xml header
  4677. xmlheader = xml_header(!!options.xmlHeader.standalone);
  4678. }
  4679. if (typeof options.docType != 'undefined') {
  4680. docType = '<!DOCTYPE ' + options.docType + '>';
  4681. }
  4682. } else {
  4683. // our config is a boolean value, so just add xml header
  4684. xmlheader = xml_header();
  4685. }
  4686. }
  4687. options = options || {};
  4688. var ret = [xmlheader, options.prettyPrint && docType ? '\n' : '', docType, process_to_xml(obj, options)];
  4689. return ret.join('').replace(/\n{2,}/g, '\n').replace(/\s+$/g, '');
  4690. };
  4691. module.exports = json2xml;
  4692. /***/ }),
  4693. /* 17 */
  4694. /***/ (function(module, exports, __webpack_require__) {
  4695. "use strict";
  4696. var session = __webpack_require__(5);
  4697. var util = __webpack_require__(0);
  4698. var originApiMap = {};
  4699. var transferToTaskMethod = function transferToTaskMethod(apiMap, apiName) {
  4700. originApiMap[apiName] = apiMap[apiName];
  4701. apiMap[apiName] = function (params, callback) {
  4702. if (params.SkipTask) {
  4703. originApiMap[apiName].call(this, params, callback);
  4704. } else {
  4705. this._addTask(apiName, params, callback);
  4706. }
  4707. };
  4708. };
  4709. var initTask = function initTask(cos) {
  4710. var queue = [];
  4711. var tasks = {};
  4712. var uploadingFileCount = 0;
  4713. var nextUploadIndex = 0;
  4714. // 接口返回简略的任务信息
  4715. var formatTask = function formatTask(task) {
  4716. var t = {
  4717. id: task.id,
  4718. Bucket: task.Bucket,
  4719. Region: task.Region,
  4720. Key: task.Key,
  4721. FilePath: task.FilePath,
  4722. state: task.state,
  4723. loaded: task.loaded,
  4724. size: task.size,
  4725. speed: task.speed,
  4726. percent: task.percent,
  4727. hashPercent: task.hashPercent,
  4728. error: task.error
  4729. };
  4730. if (task.FilePath) t.FilePath = task.FilePath;
  4731. return t;
  4732. };
  4733. var emitListUpdate = function () {
  4734. var timer;
  4735. var emit = function emit() {
  4736. timer = 0;
  4737. cos.emit('task-list-update', { list: util.map(queue, formatTask) });
  4738. cos.emit('list-update', { list: util.map(queue, formatTask) });
  4739. };
  4740. return function () {
  4741. if (!timer) timer = setTimeout(emit);
  4742. };
  4743. }();
  4744. var clearQueue = function clearQueue() {
  4745. if (queue.length <= cos.options.UploadQueueSize) return;
  4746. for (var i = 0; i < nextUploadIndex && // 小于当前操作的 index 才清理
  4747. i < queue.length && // 大于队列才清理
  4748. queue.length > cos.options.UploadQueueSize // 如果还太多,才继续清理
  4749. ;) {
  4750. var isActive = queue[i].state === 'waiting' || queue[i].state === 'checking' || queue[i].state === 'uploading';
  4751. if (!queue[i] || !isActive) {
  4752. tasks[queue[i].id] && delete tasks[queue[i].id];
  4753. queue.splice(i, 1);
  4754. nextUploadIndex--;
  4755. } else {
  4756. i++;
  4757. }
  4758. }
  4759. emitListUpdate();
  4760. };
  4761. var startNextTask = function startNextTask() {
  4762. // 检查是否允许增加执行进程
  4763. if (uploadingFileCount >= cos.options.FileParallelLimit) return;
  4764. // 跳过不可执行的任务
  4765. while (queue[nextUploadIndex] && queue[nextUploadIndex].state !== 'waiting') {
  4766. nextUploadIndex++;
  4767. } // 检查是否已遍历结束
  4768. if (nextUploadIndex >= queue.length) return;
  4769. // 上传该遍历到的任务
  4770. var task = queue[nextUploadIndex];
  4771. nextUploadIndex++;
  4772. uploadingFileCount++;
  4773. task.state = 'checking';
  4774. task.params.onTaskStart && task.params.onTaskStart(formatTask(task));
  4775. !task.params.UploadData && (task.params.UploadData = {});
  4776. var apiParams = util.formatParams(task.api, task.params);
  4777. originApiMap[task.api].call(cos, apiParams, function (err, data) {
  4778. if (!cos._isRunningTask(task.id)) return;
  4779. if (task.state === 'checking' || task.state === 'uploading') {
  4780. task.state = err ? 'error' : 'success';
  4781. err && (task.error = err);
  4782. uploadingFileCount--;
  4783. emitListUpdate();
  4784. startNextTask();
  4785. task.callback && task.callback(err, data);
  4786. if (task.state === 'success') {
  4787. if (task.params) {
  4788. delete task.params.UploadData;
  4789. delete task.params.Body;
  4790. delete task.params;
  4791. }
  4792. delete task.callback;
  4793. }
  4794. }
  4795. clearQueue();
  4796. });
  4797. emitListUpdate();
  4798. // 异步执行下一个任务
  4799. setTimeout(startNextTask);
  4800. };
  4801. var killTask = function killTask(id, switchToState) {
  4802. var task = tasks[id];
  4803. if (!task) return;
  4804. var waiting = task && task.state === 'waiting';
  4805. var running = task && (task.state === 'checking' || task.state === 'uploading');
  4806. if (switchToState === 'canceled' && task.state !== 'canceled' || switchToState === 'paused' && waiting || switchToState === 'paused' && running) {
  4807. if (switchToState === 'paused' && task.params.Body && typeof task.params.Body.pipe === 'function') {
  4808. console.error('stream not support pause');
  4809. return;
  4810. }
  4811. task.state = switchToState;
  4812. cos.emit('inner-kill-task', { TaskId: id, toState: switchToState });
  4813. try {
  4814. var UploadId = task && task.params && task.params.UploadData.UploadId;
  4815. } catch (e) {}
  4816. if (switchToState === 'canceled' && UploadId) session.removeUsing(UploadId);
  4817. emitListUpdate();
  4818. if (running) {
  4819. uploadingFileCount--;
  4820. startNextTask();
  4821. }
  4822. if (switchToState === 'canceled') {
  4823. if (task.params) {
  4824. delete task.params.UploadData;
  4825. delete task.params.Body;
  4826. delete task.params;
  4827. }
  4828. delete task.callback;
  4829. }
  4830. }
  4831. clearQueue();
  4832. };
  4833. cos._addTasks = function (taskList) {
  4834. util.each(taskList, function (task) {
  4835. cos._addTask(task.api, task.params, task.callback, true);
  4836. });
  4837. emitListUpdate();
  4838. };
  4839. cos._addTask = function (api, params, callback, ignoreAddEvent) {
  4840. // 如果小程序版本不支持获取文件分片内容,统一转到 postObject 接口上传
  4841. if (api === 'sliceUploadFile' && !util.canFileSlice()) api = 'postObject';
  4842. // 复制参数对象
  4843. params = util.formatParams(api, params);
  4844. // 生成 id
  4845. var id = util.uuid();
  4846. params.TaskId = id;
  4847. params.onTaskReady && params.onTaskReady(id);
  4848. var task = {
  4849. // env
  4850. params: params,
  4851. callback: callback,
  4852. api: api,
  4853. index: queue.length,
  4854. // task
  4855. id: id,
  4856. Bucket: params.Bucket,
  4857. Region: params.Region,
  4858. Key: params.Key,
  4859. FilePath: params.FilePath || '',
  4860. state: 'waiting',
  4861. loaded: 0,
  4862. size: 0,
  4863. speed: 0,
  4864. percent: 0,
  4865. hashPercent: 0,
  4866. error: null
  4867. };
  4868. var onHashProgress = params.onHashProgress;
  4869. params.onHashProgress = function (info) {
  4870. if (!cos._isRunningTask(task.id)) return;
  4871. task.hashPercent = info.percent;
  4872. onHashProgress && onHashProgress(info);
  4873. emitListUpdate();
  4874. };
  4875. var onProgress = params.onProgress;
  4876. params.onProgress = function (info) {
  4877. if (!cos._isRunningTask(task.id)) return;
  4878. task.state === 'checking' && (task.state = 'uploading');
  4879. task.loaded = info.loaded;
  4880. task.size = info.total;
  4881. task.speed = info.speed;
  4882. task.percent = info.percent;
  4883. onProgress && onProgress(info);
  4884. emitListUpdate();
  4885. };
  4886. // 异步获取 filesize
  4887. util.getFileSize(api, params, function (err, size) {
  4888. // 开始处理上传
  4889. if (err) {
  4890. // 如果获取大小出错,不加入队列
  4891. callback(err);
  4892. return;
  4893. }
  4894. // 获取完文件大小再把任务加入队列
  4895. tasks[id] = task;
  4896. queue.push(task);
  4897. task.size = size;
  4898. !ignoreAddEvent && emitListUpdate();
  4899. startNextTask();
  4900. clearQueue();
  4901. });
  4902. return id;
  4903. };
  4904. cos._isRunningTask = function (id) {
  4905. var task = tasks[id];
  4906. return !!(task && (task.state === 'checking' || task.state === 'uploading'));
  4907. };
  4908. cos.getTaskList = function () {
  4909. return util.map(queue, formatTask);
  4910. };
  4911. cos.cancelTask = function (id) {
  4912. killTask(id, 'canceled');
  4913. };
  4914. cos.pauseTask = function (id) {
  4915. killTask(id, 'paused');
  4916. };
  4917. cos.restartTask = function (id) {
  4918. var task = tasks[id];
  4919. if (task && (task.state === 'paused' || task.state === 'error')) {
  4920. task.state = 'waiting';
  4921. emitListUpdate();
  4922. nextUploadIndex = Math.min(nextUploadIndex, task.index);
  4923. startNextTask();
  4924. }
  4925. };
  4926. cos.isUploadRunning = function () {
  4927. return uploadingFileCount || nextUploadIndex < queue.length;
  4928. };
  4929. };
  4930. module.exports.transferToTaskMethod = transferToTaskMethod;
  4931. module.exports.init = initTask;
  4932. /***/ }),
  4933. /* 18 */
  4934. /***/ (function(module, exports, __webpack_require__) {
  4935. "use strict";
  4936. var REQUEST = __webpack_require__(19);
  4937. var base64 = __webpack_require__(3);
  4938. var util = __webpack_require__(0);
  4939. var mime = __webpack_require__(20);
  4940. // Bucket 相关
  4941. /**
  4942. * 获取用户的 bucket 列表
  4943. * @param {Object} params 回调函数,必须,下面为参数列表
  4944. * 无特殊参数
  4945. * @param {Function} callback 回调函数,必须
  4946. */
  4947. function getService(params, callback) {
  4948. if (typeof params === 'function') {
  4949. callback = params;
  4950. params = {};
  4951. }
  4952. var protocol = 'https:';
  4953. var domain = this.options.ServiceDomain;
  4954. var region = params.Region;
  4955. if (domain) {
  4956. domain = domain.replace(/\{\{Region\}\}/ig, region || '').replace(/\{\{.*?\}\}/ig, '');
  4957. if (!/^[a-zA-Z]+:\/\//.test(domain)) {
  4958. domain = protocol + '//' + domain;
  4959. }
  4960. if (domain.slice(-1) === '/') {
  4961. domain = domain.slice(0, -1);
  4962. }
  4963. } else if (region) {
  4964. domain = protocol + '//cos.' + region + '.myqcloud.com';
  4965. } else {
  4966. domain = protocol + '//service.cos.myqcloud.com';
  4967. }
  4968. var SignHost = '';
  4969. var standardHost = region ? 'cos.' + region + '.myqcloud.com' : 'service.cos.myqcloud.com';
  4970. var urlHost = domain.replace(/^https?:\/\/([^/]+)(\/.*)?$/, '$1');
  4971. if (standardHost === urlHost) SignHost = standardHost;
  4972. submitRequest.call(this, {
  4973. Action: 'name/cos:GetService',
  4974. url: domain,
  4975. method: 'GET',
  4976. headers: params.Headers
  4977. }, function (err, data) {
  4978. if (err) return callback(err);
  4979. var buckets = data && data.ListAllMyBucketsResult && data.ListAllMyBucketsResult.Buckets && data.ListAllMyBucketsResult.Buckets.Bucket || [];
  4980. buckets = util.isArray(buckets) ? buckets : [buckets];
  4981. var owner = data && data.ListAllMyBucketsResult && data.ListAllMyBucketsResult.Owner || {};
  4982. callback(null, {
  4983. Buckets: buckets,
  4984. Owner: owner,
  4985. statusCode: data.statusCode,
  4986. headers: data.headers
  4987. });
  4988. });
  4989. }
  4990. /**
  4991. * 创建 Bucket,并初始化访问权限
  4992. * @param {Object} params 参数对象,必须
  4993. * @param {String} params.Bucket Bucket名称,必须
  4994. * @param {String} params.Region 地域名称,必须
  4995. * @param {String} params.ACL 用户自定义文件权限,可以设置:private,public-read;默认值:private,非必须
  4996. * @param {String} params.GrantRead 赋予被授权者读的权限,格式x-cos-grant-read: uin=" ",uin=" ",非必须
  4997. * @param {String} params.GrantWrite 赋予被授权者写的权限,格式x-cos-grant-write: uin=" ",uin=" ",非必须
  4998. * @param {String} params.GrantFullControl 赋予被授权者读写权限,格式x-cos-grant-full-control: uin=" ",uin=" ",非必须
  4999. * @param {Function} callback 回调函数,必须
  5000. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5001. * @return {Object} data 返回的数据
  5002. * @return {String} data.Location 操作地址
  5003. */
  5004. function putBucket(params, callback) {
  5005. var self = this;
  5006. var xml = '';
  5007. if (params['BucketAZConfig']) {
  5008. var CreateBucketConfiguration = {
  5009. BucketAZConfig: params.BucketAZConfig
  5010. };
  5011. xml = util.json2xml({ CreateBucketConfiguration: CreateBucketConfiguration });
  5012. }
  5013. submitRequest.call(this, {
  5014. Action: 'name/cos:PutBucket',
  5015. method: 'PUT',
  5016. Bucket: params.Bucket,
  5017. Region: params.Region,
  5018. headers: params.Headers,
  5019. body: xml
  5020. }, function (err, data) {
  5021. if (err) return callback(err);
  5022. var url = getUrl({
  5023. protocol: self.options.Protocol,
  5024. domain: self.options.Domain,
  5025. bucket: params.Bucket,
  5026. region: params.Region,
  5027. isLocation: true
  5028. });
  5029. callback(null, {
  5030. Location: url,
  5031. statusCode: data.statusCode,
  5032. headers: data.headers
  5033. });
  5034. });
  5035. }
  5036. /**
  5037. * 查看是否存在该Bucket,是否有权限访问
  5038. * @param {Object} params 参数对象,必须
  5039. * @param {String} params.Bucket Bucket名称,必须
  5040. * @param {String} params.Region 地域名称,必须
  5041. * @param {Function} callback 回调函数,必须
  5042. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5043. * @return {Object} data 返回的数据
  5044. * @return {Boolean} data.BucketExist Bucket是否存在
  5045. * @return {Boolean} data.BucketAuth 是否有 Bucket 的访问权限
  5046. */
  5047. function headBucket(params, callback) {
  5048. submitRequest.call(this, {
  5049. Action: 'name/cos:HeadBucket',
  5050. Bucket: params.Bucket,
  5051. Region: params.Region,
  5052. headers: params.Headers,
  5053. method: 'HEAD'
  5054. }, function (err, data) {
  5055. callback(err, data);
  5056. });
  5057. }
  5058. /**
  5059. * 获取 Bucket 下的 object 列表
  5060. * @param {Object} params 参数对象,必须
  5061. * @param {String} params.Bucket Bucket名称,必须
  5062. * @param {String} params.Region 地域名称,必须
  5063. * @param {String} params.Prefix 前缀匹配,用来规定返回的文件前缀地址,非必须
  5064. * @param {String} params.Delimiter 定界符为一个符号,如果有Prefix,则将Prefix到delimiter之间的相同路径归为一类,非必须
  5065. * @param {String} params.Marker 默认以UTF-8二进制顺序列出条目,所有列出条目从marker开始,非必须
  5066. * @param {String} params.MaxKeys 单次返回最大的条目数量,默认1000,非必须
  5067. * @param {String} params.EncodingType 规定返回值的编码方式,非必须
  5068. * @param {Function} callback 回调函数,必须
  5069. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5070. * @return {Object} data 返回的数据
  5071. * @return {Object} data.ListBucketResult 返回的 object 列表信息
  5072. */
  5073. function getBucket(params, callback) {
  5074. var reqParams = {};
  5075. reqParams['prefix'] = params['Prefix'] || '';
  5076. reqParams['delimiter'] = params['Delimiter'];
  5077. reqParams['marker'] = params['Marker'];
  5078. reqParams['max-keys'] = params['MaxKeys'];
  5079. reqParams['encoding-type'] = params['EncodingType'];
  5080. submitRequest.call(this, {
  5081. Action: 'name/cos:GetBucket',
  5082. ResourceKey: reqParams['prefix'],
  5083. method: 'GET',
  5084. Bucket: params.Bucket,
  5085. Region: params.Region,
  5086. headers: params.Headers,
  5087. qs: reqParams
  5088. }, function (err, data) {
  5089. if (err) return callback(err);
  5090. var ListBucketResult = data.ListBucketResult || {};
  5091. var Contents = ListBucketResult.Contents || [];
  5092. var CommonPrefixes = ListBucketResult.CommonPrefixes || [];
  5093. Contents = util.isArray(Contents) ? Contents : [Contents];
  5094. CommonPrefixes = util.isArray(CommonPrefixes) ? CommonPrefixes : [CommonPrefixes];
  5095. var result = util.clone(ListBucketResult);
  5096. util.extend(result, {
  5097. Contents: Contents,
  5098. CommonPrefixes: CommonPrefixes,
  5099. statusCode: data.statusCode,
  5100. headers: data.headers
  5101. });
  5102. callback(null, result);
  5103. });
  5104. }
  5105. /**
  5106. * 删除 Bucket
  5107. * @param {Object} params 参数对象,必须
  5108. * @param {String} params.Bucket Bucket名称,必须
  5109. * @param {String} params.Region 地域名称,必须
  5110. * @param {Function} callback 回调函数,必须
  5111. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5112. * @return {Object} data 返回的数据
  5113. * @return {String} data.Location 操作地址
  5114. */
  5115. function deleteBucket(params, callback) {
  5116. submitRequest.call(this, {
  5117. Action: 'name/cos:DeleteBucket',
  5118. Bucket: params.Bucket,
  5119. Region: params.Region,
  5120. headers: params.Headers,
  5121. method: 'DELETE'
  5122. }, function (err, data) {
  5123. if (err && err.statusCode === 204) {
  5124. return callback(null, { statusCode: err.statusCode });
  5125. } else if (err) {
  5126. return callback(err);
  5127. }
  5128. callback(null, {
  5129. statusCode: data.statusCode,
  5130. headers: data.headers
  5131. });
  5132. });
  5133. }
  5134. /**
  5135. * 设置 Bucket 的 权限列表
  5136. * @param {Object} params 参数对象,必须
  5137. * @param {String} params.Bucket Bucket名称,必须
  5138. * @param {String} params.Region 地域名称,必须
  5139. * @param {String} params.ACL 用户自定义文件权限,可以设置:private,public-read;默认值:private,非必须
  5140. * @param {String} params.GrantRead 赋予被授权者读的权限,格式x-cos-grant-read: uin=" ",uin=" ",非必须
  5141. * @param {String} params.GrantWrite 赋予被授权者写的权限,格式x-cos-grant-write: uin=" ",uin=" ",非必须
  5142. * @param {String} params.GrantFullControl 赋予被授权者读写权限,格式x-cos-grant-full-control: uin=" ",uin=" ",非必须
  5143. * @param {Function} callback 回调函数,必须
  5144. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5145. * @return {Object} data 返回的数据
  5146. */
  5147. function putBucketAcl(params, callback) {
  5148. var headers = params.Headers;
  5149. var xml = '';
  5150. if (params['AccessControlPolicy']) {
  5151. var AccessControlPolicy = util.clone(params['AccessControlPolicy'] || {});
  5152. var Grants = AccessControlPolicy.Grants || AccessControlPolicy.Grant;
  5153. Grants = util.isArray(Grants) ? Grants : [Grants];
  5154. delete AccessControlPolicy.Grant;
  5155. delete AccessControlPolicy.Grants;
  5156. AccessControlPolicy.AccessControlList = { Grant: Grants };
  5157. xml = util.json2xml({ AccessControlPolicy: AccessControlPolicy });
  5158. headers['Content-Type'] = 'application/xml';
  5159. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  5160. }
  5161. // Grant Header 去重
  5162. util.each(headers, function (val, key) {
  5163. if (key.indexOf('x-cos-grant-') === 0) {
  5164. headers[key] = uniqGrant(headers[key]);
  5165. }
  5166. });
  5167. submitRequest.call(this, {
  5168. Action: 'name/cos:PutBucketACL',
  5169. method: 'PUT',
  5170. Bucket: params.Bucket,
  5171. Region: params.Region,
  5172. headers: headers,
  5173. action: 'acl',
  5174. body: xml
  5175. }, function (err, data) {
  5176. if (err) return callback(err);
  5177. callback(null, {
  5178. statusCode: data.statusCode,
  5179. headers: data.headers
  5180. });
  5181. });
  5182. }
  5183. /**
  5184. * 获取 Bucket 的 权限列表
  5185. * @param {Object} params 参数对象,必须
  5186. * @param {String} params.Bucket Bucket名称,必须
  5187. * @param {String} params.Region 地域名称,必须
  5188. * @param {Function} callback 回调函数,必须
  5189. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5190. * @return {Object} data 返回的数据
  5191. * @return {Object} data.AccessControlPolicy 访问权限信息
  5192. */
  5193. function getBucketAcl(params, callback) {
  5194. submitRequest.call(this, {
  5195. Action: 'name/cos:GetBucketACL',
  5196. method: 'GET',
  5197. Bucket: params.Bucket,
  5198. Region: params.Region,
  5199. headers: params.Headers,
  5200. action: 'acl'
  5201. }, function (err, data) {
  5202. if (err) return callback(err);
  5203. var AccessControlPolicy = data.AccessControlPolicy || {};
  5204. var Owner = AccessControlPolicy.Owner || {};
  5205. var Grant = AccessControlPolicy.AccessControlList.Grant || [];
  5206. Grant = util.isArray(Grant) ? Grant : [Grant];
  5207. var result = decodeAcl(AccessControlPolicy);
  5208. if (data.headers && data.headers['x-cos-acl']) {
  5209. result.ACL = data.headers['x-cos-acl'];
  5210. }
  5211. result = util.extend(result, {
  5212. Owner: Owner,
  5213. Grants: Grant,
  5214. statusCode: data.statusCode,
  5215. headers: data.headers
  5216. });
  5217. callback(null, result);
  5218. });
  5219. }
  5220. /**
  5221. * 设置 Bucket 的 跨域设置
  5222. * @param {Object} params 参数对象,必须
  5223. * @param {String} params.Bucket Bucket名称,必须
  5224. * @param {String} params.Region 地域名称,必须
  5225. * @param {Object} params.CORSConfiguration 相关的跨域设置,必须
  5226. * @param {Array} params.CORSConfiguration.CORSRules 对应的跨域规则
  5227. * @param {Function} callback 回调函数,必须
  5228. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5229. * @return {Object} data 返回的数据
  5230. */
  5231. function putBucketCors(params, callback) {
  5232. var CORSConfiguration = params['CORSConfiguration'] || {};
  5233. var CORSRules = CORSConfiguration['CORSRules'] || params['CORSRules'] || [];
  5234. CORSRules = util.clone(util.isArray(CORSRules) ? CORSRules : [CORSRules]);
  5235. util.each(CORSRules, function (rule) {
  5236. util.each(['AllowedOrigin', 'AllowedHeader', 'AllowedMethod', 'ExposeHeader'], function (key) {
  5237. var sKey = key + 's';
  5238. var val = rule[sKey] || rule[key] || [];
  5239. delete rule[sKey];
  5240. rule[key] = util.isArray(val) ? val : [val];
  5241. });
  5242. });
  5243. var xml = util.json2xml({ CORSConfiguration: { CORSRule: CORSRules } });
  5244. var headers = params.Headers;
  5245. headers['Content-Type'] = 'application/xml';
  5246. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  5247. submitRequest.call(this, {
  5248. Action: 'name/cos:PutBucketCORS',
  5249. method: 'PUT',
  5250. Bucket: params.Bucket,
  5251. Region: params.Region,
  5252. body: xml,
  5253. action: 'cors',
  5254. headers: headers
  5255. }, function (err, data) {
  5256. if (err) return callback(err);
  5257. callback(null, {
  5258. statusCode: data.statusCode,
  5259. headers: data.headers
  5260. });
  5261. });
  5262. }
  5263. /**
  5264. * 获取 Bucket 的 跨域设置
  5265. * @param {Object} params 参数对象,必须
  5266. * @param {String} params.Bucket Bucket名称,必须
  5267. * @param {String} params.Region 地域名称,必须
  5268. * @param {Function} callback 回调函数,必须
  5269. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5270. * @return {Object} data 返回的数据
  5271. * @return {Object} data.CORSRules Bucket的跨域设置
  5272. */
  5273. function getBucketCors(params, callback) {
  5274. submitRequest.call(this, {
  5275. Action: 'name/cos:GetBucketCORS',
  5276. method: 'GET',
  5277. Bucket: params.Bucket,
  5278. Region: params.Region,
  5279. headers: params.Headers,
  5280. action: 'cors'
  5281. }, function (err, data) {
  5282. if (err) {
  5283. if (err.statusCode === 404 && err.error && err.error.Code === 'NoSuchCORSConfiguration') {
  5284. var result = {
  5285. CORSRules: [],
  5286. statusCode: err.statusCode
  5287. };
  5288. err.headers && (result.headers = err.headers);
  5289. callback(null, result);
  5290. } else {
  5291. callback(err);
  5292. }
  5293. return;
  5294. }
  5295. var CORSConfiguration = data.CORSConfiguration || {};
  5296. var CORSRules = CORSConfiguration.CORSRules || CORSConfiguration.CORSRule || [];
  5297. CORSRules = util.clone(util.isArray(CORSRules) ? CORSRules : [CORSRules]);
  5298. util.each(CORSRules, function (rule) {
  5299. util.each(['AllowedOrigin', 'AllowedHeader', 'AllowedMethod', 'ExposeHeader'], function (key) {
  5300. var sKey = key + 's';
  5301. var val = rule[sKey] || rule[key] || [];
  5302. delete rule[key];
  5303. rule[sKey] = util.isArray(val) ? val : [val];
  5304. });
  5305. });
  5306. callback(null, {
  5307. CORSRules: CORSRules,
  5308. statusCode: data.statusCode,
  5309. headers: data.headers
  5310. });
  5311. });
  5312. }
  5313. /**
  5314. * 删除 Bucket 的 跨域设置
  5315. * @param {Object} params 参数对象,必须
  5316. * @param {String} params.Bucket Bucket名称,必须
  5317. * @param {String} params.Region 地域名称,必须
  5318. * @param {Function} callback 回调函数,必须
  5319. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5320. * @return {Object} data 返回的数据
  5321. */
  5322. function deleteBucketCors(params, callback) {
  5323. submitRequest.call(this, {
  5324. Action: 'name/cos:DeleteBucketCORS',
  5325. method: 'DELETE',
  5326. Bucket: params.Bucket,
  5327. Region: params.Region,
  5328. headers: params.Headers,
  5329. action: 'cors'
  5330. }, function (err, data) {
  5331. if (err && err.statusCode === 204) {
  5332. return callback(null, { statusCode: err.statusCode });
  5333. } else if (err) {
  5334. return callback(err);
  5335. }
  5336. callback(null, {
  5337. statusCode: data.statusCode || err.statusCode,
  5338. headers: data.headers
  5339. });
  5340. });
  5341. }
  5342. /**
  5343. * 获取 Bucket 的 地域信息
  5344. * @param {Object} params 参数对象,必须
  5345. * @param {String} params.Bucket Bucket名称,必须
  5346. * @param {String} params.Region 地域名称,必须
  5347. * @param {Function} callback 回调函数,必须
  5348. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5349. * @return {Object} data 返回数据,包含地域信息 LocationConstraint
  5350. */
  5351. function getBucketLocation(params, callback) {
  5352. submitRequest.call(this, {
  5353. Action: 'name/cos:GetBucketLocation',
  5354. method: 'GET',
  5355. Bucket: params.Bucket,
  5356. Region: params.Region,
  5357. headers: params.Headers,
  5358. action: 'location'
  5359. }, function (err, data) {
  5360. if (err) return callback(err);
  5361. callback(null, data);
  5362. });
  5363. }
  5364. function putBucketPolicy(params, callback) {
  5365. var Policy = params['Policy'];
  5366. var PolicyStr = Policy;
  5367. try {
  5368. if (typeof Policy === 'string') {
  5369. Policy = JSON.parse(PolicyStr);
  5370. } else {
  5371. PolicyStr = JSON.stringify(Policy);
  5372. }
  5373. } catch (e) {
  5374. callback({ error: 'Policy format error' });
  5375. }
  5376. var headers = params.Headers;
  5377. headers['Content-Type'] = 'application/json';
  5378. headers['Content-MD5'] = util.binaryBase64(util.md5(PolicyStr));
  5379. submitRequest.call(this, {
  5380. Action: 'name/cos:PutBucketPolicy',
  5381. method: 'PUT',
  5382. Bucket: params.Bucket,
  5383. Region: params.Region,
  5384. action: 'policy',
  5385. body: PolicyStr,
  5386. headers: headers,
  5387. json: true
  5388. }, function (err, data) {
  5389. if (err && err.statusCode === 204) {
  5390. return callback(null, { statusCode: err.statusCode });
  5391. } else if (err) {
  5392. return callback(err);
  5393. }
  5394. callback(null, {
  5395. statusCode: data.statusCode,
  5396. headers: data.headers
  5397. });
  5398. });
  5399. }
  5400. /**
  5401. * 获取 Bucket 的读取权限策略
  5402. * @param {Object} params 参数对象,必须
  5403. * @param {String} params.Bucket Bucket名称,必须
  5404. * @param {String} params.Region 地域名称,必须
  5405. * @param {Function} callback 回调函数,必须
  5406. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5407. * @return {Object} data 返回数据
  5408. */
  5409. function getBucketPolicy(params, callback) {
  5410. submitRequest.call(this, {
  5411. Action: 'name/cos:GetBucketPolicy',
  5412. method: 'GET',
  5413. Bucket: params.Bucket,
  5414. Region: params.Region,
  5415. headers: params.Headers,
  5416. action: 'policy',
  5417. rawBody: true
  5418. }, function (err, data) {
  5419. if (err) {
  5420. if (err.statusCode && err.statusCode === 403) {
  5421. return callback({ ErrorStatus: 'Access Denied' });
  5422. }
  5423. if (err.statusCode && err.statusCode === 405) {
  5424. return callback({ ErrorStatus: 'Method Not Allowed' });
  5425. }
  5426. if (err.statusCode && err.statusCode === 404) {
  5427. return callback({ ErrorStatus: 'Policy Not Found' });
  5428. }
  5429. return callback(err);
  5430. }
  5431. var Policy = {};
  5432. try {
  5433. Policy = JSON.parse(data.body);
  5434. } catch (e) {}
  5435. callback(null, {
  5436. Policy: Policy,
  5437. statusCode: data.statusCode,
  5438. headers: data.headers
  5439. });
  5440. });
  5441. }
  5442. /**
  5443. * 删除 Bucket 的 跨域设置
  5444. * @param {Object} params 参数对象,必须
  5445. * @param {String} params.Bucket Bucket名称,必须
  5446. * @param {String} params.Region 地域名称,必须
  5447. * @param {Function} callback 回调函数,必须
  5448. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5449. * @return {Object} data 返回的数据
  5450. */
  5451. function deleteBucketPolicy(params, callback) {
  5452. submitRequest.call(this, {
  5453. Action: 'name/cos:DeleteBucketPolicy',
  5454. method: 'DELETE',
  5455. Bucket: params.Bucket,
  5456. Region: params.Region,
  5457. headers: params.Headers,
  5458. action: 'policy'
  5459. }, function (err, data) {
  5460. if (err && err.statusCode === 204) {
  5461. return callback(null, { statusCode: err.statusCode });
  5462. } else if (err) {
  5463. return callback(err);
  5464. }
  5465. callback(null, {
  5466. statusCode: data.statusCode || err.statusCode,
  5467. headers: data.headers
  5468. });
  5469. });
  5470. }
  5471. /**
  5472. * 设置 Bucket 的标签
  5473. * @param {Object} params 参数对象,必须
  5474. * @param {String} params.Bucket Bucket名称,必须
  5475. * @param {String} params.Region 地域名称,必须
  5476. * @param {Array} params.TagSet 标签设置,必须
  5477. * @param {Function} callback 回调函数,必须
  5478. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5479. * @return {Object} data 返回数据
  5480. */
  5481. function putBucketTagging(params, callback) {
  5482. var Tagging = params['Tagging'] || {};
  5483. var Tags = Tagging.TagSet || Tagging.Tags || params['Tags'] || [];
  5484. Tags = util.clone(util.isArray(Tags) ? Tags : [Tags]);
  5485. var xml = util.json2xml({ Tagging: { TagSet: { Tag: Tags } } });
  5486. var headers = params.Headers;
  5487. headers['Content-Type'] = 'application/xml';
  5488. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  5489. submitRequest.call(this, {
  5490. Action: 'name/cos:PutBucketTagging',
  5491. method: 'PUT',
  5492. Bucket: params.Bucket,
  5493. Region: params.Region,
  5494. body: xml,
  5495. action: 'tagging',
  5496. headers: headers
  5497. }, function (err, data) {
  5498. if (err && err.statusCode === 204) {
  5499. return callback(null, { statusCode: err.statusCode });
  5500. } else if (err) {
  5501. return callback(err);
  5502. }
  5503. callback(null, {
  5504. statusCode: data.statusCode,
  5505. headers: data.headers
  5506. });
  5507. });
  5508. }
  5509. /**
  5510. * 获取 Bucket 的标签设置
  5511. * @param {Object} params 参数对象,必须
  5512. * @param {String} params.Bucket Bucket名称,必须
  5513. * @param {String} params.Region 地域名称,必须
  5514. * @param {Function} callback 回调函数,必须
  5515. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5516. * @return {Object} data 返回数据
  5517. */
  5518. function getBucketTagging(params, callback) {
  5519. submitRequest.call(this, {
  5520. Action: 'name/cos:GetBucketTagging',
  5521. method: 'GET',
  5522. Bucket: params.Bucket,
  5523. Region: params.Region,
  5524. headers: params.Headers,
  5525. action: 'tagging'
  5526. }, function (err, data) {
  5527. if (err) {
  5528. if (err.statusCode === 404 && err.error && (err.error === "Not Found" || err.error.Code === 'NoSuchTagSet')) {
  5529. var result = {
  5530. Tags: [],
  5531. statusCode: err.statusCode
  5532. };
  5533. err.headers && (result.headers = err.headers);
  5534. callback(null, result);
  5535. } else {
  5536. callback(err);
  5537. }
  5538. return;
  5539. }
  5540. var Tags = [];
  5541. try {
  5542. Tags = data.Tagging.TagSet.Tag || [];
  5543. } catch (e) {}
  5544. Tags = util.clone(util.isArray(Tags) ? Tags : [Tags]);
  5545. callback(null, {
  5546. Tags: Tags,
  5547. statusCode: data.statusCode,
  5548. headers: data.headers
  5549. });
  5550. });
  5551. }
  5552. /**
  5553. * 删除 Bucket 的 标签设置
  5554. * @param {Object} params 参数对象,必须
  5555. * @param {String} params.Bucket Bucket名称,必须
  5556. * @param {String} params.Region 地域名称,必须
  5557. * @param {Function} callback 回调函数,必须
  5558. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5559. * @return {Object} data 返回的数据
  5560. */
  5561. function deleteBucketTagging(params, callback) {
  5562. submitRequest.call(this, {
  5563. Action: 'name/cos:DeleteBucketTagging',
  5564. method: 'DELETE',
  5565. Bucket: params.Bucket,
  5566. Region: params.Region,
  5567. headers: params.Headers,
  5568. action: 'tagging'
  5569. }, function (err, data) {
  5570. if (err && err.statusCode === 204) {
  5571. return callback(null, { statusCode: err.statusCode });
  5572. } else if (err) {
  5573. return callback(err);
  5574. }
  5575. callback(null, {
  5576. statusCode: data.statusCode,
  5577. headers: data.headers
  5578. });
  5579. });
  5580. }
  5581. function putBucketLifecycle(params, callback) {
  5582. var LifecycleConfiguration = params['LifecycleConfiguration'] || {};
  5583. var Rules = LifecycleConfiguration.Rules || params.Rules || [];
  5584. Rules = util.clone(Rules);
  5585. var xml = util.json2xml({ LifecycleConfiguration: { Rule: Rules } });
  5586. var headers = params.Headers;
  5587. headers['Content-Type'] = 'application/xml';
  5588. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  5589. submitRequest.call(this, {
  5590. Action: 'name/cos:PutBucketLifecycle',
  5591. method: 'PUT',
  5592. Bucket: params.Bucket,
  5593. Region: params.Region,
  5594. body: xml,
  5595. action: 'lifecycle',
  5596. headers: headers
  5597. }, function (err, data) {
  5598. if (err && err.statusCode === 204) {
  5599. return callback(null, { statusCode: err.statusCode });
  5600. } else if (err) {
  5601. return callback(err);
  5602. }
  5603. callback(null, {
  5604. statusCode: data.statusCode,
  5605. headers: data.headers
  5606. });
  5607. });
  5608. }
  5609. function getBucketLifecycle(params, callback) {
  5610. submitRequest.call(this, {
  5611. Action: 'name/cos:GetBucketLifecycle',
  5612. method: 'GET',
  5613. Bucket: params.Bucket,
  5614. Region: params.Region,
  5615. headers: params.Headers,
  5616. action: 'lifecycle'
  5617. }, function (err, data) {
  5618. if (err) {
  5619. if (err.statusCode === 404 && err.error && err.error.Code === 'NoSuchLifecycleConfiguration') {
  5620. var result = {
  5621. Rules: [],
  5622. statusCode: err.statusCode
  5623. };
  5624. err.headers && (result.headers = err.headers);
  5625. callback(null, result);
  5626. } else {
  5627. callback(err);
  5628. }
  5629. return;
  5630. }
  5631. var Rules = [];
  5632. try {
  5633. Rules = data.LifecycleConfiguration.Rule || [];
  5634. } catch (e) {}
  5635. Rules = util.clone(util.isArray(Rules) ? Rules : [Rules]);
  5636. callback(null, {
  5637. Rules: Rules,
  5638. statusCode: data.statusCode,
  5639. headers: data.headers
  5640. });
  5641. });
  5642. }
  5643. function deleteBucketLifecycle(params, callback) {
  5644. submitRequest.call(this, {
  5645. Action: 'name/cos:DeleteBucketLifecycle',
  5646. method: 'DELETE',
  5647. Bucket: params.Bucket,
  5648. Region: params.Region,
  5649. headers: params.Headers,
  5650. action: 'lifecycle'
  5651. }, function (err, data) {
  5652. if (err && err.statusCode === 204) {
  5653. return callback(null, { statusCode: err.statusCode });
  5654. } else if (err) {
  5655. return callback(err);
  5656. }
  5657. callback(null, {
  5658. statusCode: data.statusCode,
  5659. headers: data.headers
  5660. });
  5661. });
  5662. }
  5663. function putBucketVersioning(params, callback) {
  5664. if (!params['VersioningConfiguration']) {
  5665. callback({ error: 'missing param VersioningConfiguration' });
  5666. return;
  5667. }
  5668. var VersioningConfiguration = params['VersioningConfiguration'] || {};
  5669. var xml = util.json2xml({ VersioningConfiguration: VersioningConfiguration });
  5670. var headers = params.Headers;
  5671. headers['Content-Type'] = 'application/xml';
  5672. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  5673. submitRequest.call(this, {
  5674. Action: 'name/cos:PutBucketVersioning',
  5675. method: 'PUT',
  5676. Bucket: params.Bucket,
  5677. Region: params.Region,
  5678. body: xml,
  5679. action: 'versioning',
  5680. headers: headers
  5681. }, function (err, data) {
  5682. if (err && err.statusCode === 204) {
  5683. return callback(null, { statusCode: err.statusCode });
  5684. } else if (err) {
  5685. return callback(err);
  5686. }
  5687. callback(null, {
  5688. statusCode: data.statusCode,
  5689. headers: data.headers
  5690. });
  5691. });
  5692. }
  5693. function getBucketVersioning(params, callback) {
  5694. submitRequest.call(this, {
  5695. Action: 'name/cos:GetBucketVersioning',
  5696. method: 'GET',
  5697. Bucket: params.Bucket,
  5698. Region: params.Region,
  5699. headers: params.Headers,
  5700. action: 'versioning'
  5701. }, function (err, data) {
  5702. if (!err) {
  5703. !data.VersioningConfiguration && (data.VersioningConfiguration = {});
  5704. }
  5705. callback(err, data);
  5706. });
  5707. }
  5708. function putBucketReplication(params, callback) {
  5709. var ReplicationConfiguration = util.clone(params.ReplicationConfiguration);
  5710. var xml = util.json2xml({ ReplicationConfiguration: ReplicationConfiguration });
  5711. xml = xml.replace(/<(\/?)Rules>/ig, '<$1Rule>');
  5712. xml = xml.replace(/<(\/?)Tags>/ig, '<$1Tag>');
  5713. var headers = params.Headers;
  5714. headers['Content-Type'] = 'application/xml';
  5715. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  5716. submitRequest.call(this, {
  5717. Action: 'name/cos:PutBucketReplication',
  5718. method: 'PUT',
  5719. Bucket: params.Bucket,
  5720. Region: params.Region,
  5721. body: xml,
  5722. action: 'replication',
  5723. headers: headers
  5724. }, function (err, data) {
  5725. if (err && err.statusCode === 204) {
  5726. return callback(null, { statusCode: err.statusCode });
  5727. } else if (err) {
  5728. return callback(err);
  5729. }
  5730. callback(null, {
  5731. statusCode: data.statusCode,
  5732. headers: data.headers
  5733. });
  5734. });
  5735. }
  5736. function getBucketReplication(params, callback) {
  5737. submitRequest.call(this, {
  5738. Action: 'name/cos:GetBucketReplication',
  5739. method: 'GET',
  5740. Bucket: params.Bucket,
  5741. Region: params.Region,
  5742. headers: params.Headers,
  5743. action: 'replication'
  5744. }, function (err, data) {
  5745. if (err) {
  5746. if (err.statusCode === 404 && err.error && (err.error === 'Not Found' || err.error.Code === 'ReplicationConfigurationnotFoundError')) {
  5747. var result = {
  5748. ReplicationConfiguration: { Rules: [] },
  5749. statusCode: err.statusCode
  5750. };
  5751. err.headers && (result.headers = err.headers);
  5752. callback(null, result);
  5753. } else {
  5754. callback(err);
  5755. }
  5756. return;
  5757. }
  5758. if (!err) {
  5759. !data.ReplicationConfiguration && (data.ReplicationConfiguration = {});
  5760. }
  5761. if (data.ReplicationConfiguration.Rule) {
  5762. data.ReplicationConfiguration.Rules = data.ReplicationConfiguration.Rule;
  5763. delete data.ReplicationConfiguration.Rule;
  5764. }
  5765. callback(err, data);
  5766. });
  5767. }
  5768. function deleteBucketReplication(params, callback) {
  5769. submitRequest.call(this, {
  5770. Action: 'name/cos:DeleteBucketReplication',
  5771. method: 'DELETE',
  5772. Bucket: params.Bucket,
  5773. Region: params.Region,
  5774. headers: params.Headers,
  5775. action: 'replication'
  5776. }, function (err, data) {
  5777. if (err && err.statusCode === 204) {
  5778. return callback(null, { statusCode: err.statusCode });
  5779. } else if (err) {
  5780. return callback(err);
  5781. }
  5782. callback(null, {
  5783. statusCode: data.statusCode,
  5784. headers: data.headers
  5785. });
  5786. });
  5787. }
  5788. /**
  5789. * 设置 Bucket 静态网站配置信息
  5790. * @param {Object} params 参数对象,必须
  5791. * @param {String} params.Bucket Bucket名称,必须
  5792. * @param {String} params.Region 地域名称,必须
  5793. * @param {Object} params.WebsiteConfiguration 地域名称,必须
  5794. * @param {Object} WebsiteConfiguration.IndexDocument 索引文档,必须
  5795. * @param {Object} WebsiteConfiguration.ErrorDocument 错误文档,非必须
  5796. * @param {Object} WebsiteConfiguration.RedirectAllRequestsTo 重定向所有请求,非必须
  5797. * @param {Array} params.RoutingRules 重定向规则,非必须
  5798. * @param {Function} callback 回调函数,必须
  5799. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5800. * @return {Object} data 返回数据
  5801. */
  5802. function putBucketWebsite(params, callback) {
  5803. if (!params['WebsiteConfiguration']) {
  5804. callback({ error: 'missing param WebsiteConfiguration' });
  5805. return;
  5806. }
  5807. var WebsiteConfiguration = util.clone(params['WebsiteConfiguration'] || {});
  5808. var RoutingRules = WebsiteConfiguration['RoutingRules'] || WebsiteConfiguration['RoutingRule'] || [];
  5809. RoutingRules = util.isArray(RoutingRules) ? RoutingRules : [RoutingRules];
  5810. delete WebsiteConfiguration.RoutingRule;
  5811. delete WebsiteConfiguration.RoutingRules;
  5812. if (RoutingRules.length) WebsiteConfiguration.RoutingRules = { RoutingRule: RoutingRules };
  5813. var xml = util.json2xml({ WebsiteConfiguration: WebsiteConfiguration });
  5814. var headers = params.Headers;
  5815. headers['Content-Type'] = 'application/xml';
  5816. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  5817. submitRequest.call(this, {
  5818. Action: 'name/cos:PutBucketWebsite',
  5819. method: 'PUT',
  5820. Bucket: params.Bucket,
  5821. Region: params.Region,
  5822. body: xml,
  5823. action: 'website',
  5824. headers: headers
  5825. }, function (err, data) {
  5826. if (err && err.statusCode === 204) {
  5827. return callback(null, { statusCode: err.statusCode });
  5828. } else if (err) {
  5829. return callback(err);
  5830. }
  5831. callback(null, {
  5832. statusCode: data.statusCode,
  5833. headers: data.headers
  5834. });
  5835. });
  5836. }
  5837. /**
  5838. * 获取 Bucket 的静态网站配置信息
  5839. * @param {Object} params 参数对象,必须
  5840. * @param {String} params.Bucket Bucket名称,必须
  5841. * @param {String} params.Region 地域名称,必须
  5842. * @param {Function} callback 回调函数,必须
  5843. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5844. * @return {Object} data 返回数据
  5845. */
  5846. function getBucketWebsite(params, callback) {
  5847. submitRequest.call(this, {
  5848. Action: 'name/cos:GetBucketWebsite',
  5849. method: 'GET',
  5850. Bucket: params.Bucket,
  5851. Region: params.Region,
  5852. Key: params.Key,
  5853. headers: params.Headers,
  5854. action: 'website'
  5855. }, function (err, data) {
  5856. if (err) {
  5857. if (err.statusCode === 404 && err.error.Code === 'NoSuchWebsiteConfiguration') {
  5858. var result = {
  5859. WebsiteConfiguration: {},
  5860. statusCode: err.statusCode
  5861. };
  5862. err.headers && (result.headers = err.headers);
  5863. callback(null, result);
  5864. } else {
  5865. callback(err);
  5866. }
  5867. return;
  5868. }
  5869. var WebsiteConfiguration = data.WebsiteConfiguration || {};
  5870. if (WebsiteConfiguration['RoutingRules']) {
  5871. var RoutingRules = util.clone(WebsiteConfiguration['RoutingRules'].RoutingRule || []);
  5872. RoutingRules = util.makeArray(RoutingRules);
  5873. WebsiteConfiguration.RoutingRules = RoutingRules;
  5874. }
  5875. callback(null, {
  5876. WebsiteConfiguration: WebsiteConfiguration,
  5877. statusCode: data.statusCode,
  5878. headers: data.headers
  5879. });
  5880. });
  5881. }
  5882. /**
  5883. * 删除 Bucket 的静态网站配置
  5884. * @param {Object} params 参数对象,必须
  5885. * @param {String} params.Bucket Bucket名称,必须
  5886. * @param {String} params.Region 地域名称,必须
  5887. * @param {Function} callback 回调函数,必须
  5888. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5889. * @return {Object} data 返回数据
  5890. */
  5891. function deleteBucketWebsite(params, callback) {
  5892. submitRequest.call(this, {
  5893. Action: 'name/cos:DeleteBucketWebsite',
  5894. method: 'DELETE',
  5895. Bucket: params.Bucket,
  5896. Region: params.Region,
  5897. headers: params.Headers,
  5898. action: 'website'
  5899. }, function (err, data) {
  5900. if (err && err.statusCode === 204) {
  5901. return callback(null, { statusCode: err.statusCode });
  5902. } else if (err) {
  5903. return callback(err);
  5904. }
  5905. callback(null, {
  5906. statusCode: data.statusCode,
  5907. headers: data.headers
  5908. });
  5909. });
  5910. }
  5911. /**
  5912. * 设置 Bucket 的防盗链白名单或者黑名单
  5913. * @param {Object} params 参数对象,必须
  5914. * @param {String} params.Bucket Bucket名称,必须
  5915. * @param {String} params.Region 地域名称,必须
  5916. * @param {Object} params.RefererConfiguration 地域名称,必须
  5917. * @param {String} RefererConfiguration.Status 是否开启防盗链,枚举值:Enabled、Disabled
  5918. * @param {String} RefererConfiguration.RefererType 防盗链类型,枚举值:Black-List、White-List,必须
  5919. * @param {Array} RefererConfiguration.DomianList.Domain 生效域名,必须
  5920. * @param {String} RefererConfiguration.EmptyReferConfiguration ,非必须
  5921. * @param {Function} callback 回调函数,必须
  5922. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5923. * @return {Object} data 返回数据
  5924. */
  5925. function putBucketReferer(params, callback) {
  5926. if (!params['RefererConfiguration']) {
  5927. callback({ error: 'missing param RefererConfiguration' });
  5928. return;
  5929. }
  5930. var RefererConfiguration = util.clone(params['RefererConfiguration'] || {});
  5931. var DomainList = RefererConfiguration['DomainList'] || {};
  5932. var Domains = DomainList['Domains'] || DomainList['Domain'] || [];
  5933. Domains = util.isArray(Domains) ? Domains : [Domains];
  5934. if (Domains.length) RefererConfiguration.DomainList = { Domain: Domains };
  5935. var xml = util.json2xml({ RefererConfiguration: RefererConfiguration });
  5936. var headers = params.Headers;
  5937. headers['Content-Type'] = 'application/xml';
  5938. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  5939. submitRequest.call(this, {
  5940. Action: 'name/cos:PutBucketReferer',
  5941. method: 'PUT',
  5942. Bucket: params.Bucket,
  5943. Region: params.Region,
  5944. body: xml,
  5945. action: 'referer',
  5946. headers: headers
  5947. }, function (err, data) {
  5948. if (err && err.statusCode === 204) {
  5949. return callback(null, { statusCode: err.statusCode });
  5950. } else if (err) {
  5951. return callback(err);
  5952. }
  5953. callback(null, {
  5954. statusCode: data.statusCode,
  5955. headers: data.headers
  5956. });
  5957. });
  5958. }
  5959. /**
  5960. * 获取 Bucket 的防盗链白名单或者黑名单
  5961. * @param {Object} params 参数对象,必须
  5962. * @param {String} params.Bucket Bucket名称,必须
  5963. * @param {String} params.Region 地域名称,必须
  5964. * @param {Function} callback 回调函数,必须
  5965. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5966. * @return {Object} data 返回数据
  5967. */
  5968. function getBucketReferer(params, callback) {
  5969. submitRequest.call(this, {
  5970. Action: 'name/cos:GetBucketReferer',
  5971. method: 'GET',
  5972. Bucket: params.Bucket,
  5973. Region: params.Region,
  5974. Key: params.Key,
  5975. headers: params.Headers,
  5976. action: 'referer'
  5977. }, function (err, data) {
  5978. if (err) {
  5979. if (err.statusCode === 404 && err.error.Code === 'NoSuchRefererConfiguration') {
  5980. var result = {
  5981. WebsiteConfiguration: {},
  5982. statusCode: err.statusCode
  5983. };
  5984. err.headers && (result.headers = err.headers);
  5985. callback(null, result);
  5986. } else {
  5987. callback(err);
  5988. }
  5989. return;
  5990. }
  5991. var RefererConfiguration = data.RefererConfiguration || {};
  5992. if (RefererConfiguration['DomainList']) {
  5993. var Domains = util.makeArray(RefererConfiguration['DomainList'].Domain || []);
  5994. RefererConfiguration.DomainList = { Domains: Domains };
  5995. }
  5996. callback(null, {
  5997. RefererConfiguration: RefererConfiguration,
  5998. statusCode: data.statusCode,
  5999. headers: data.headers
  6000. });
  6001. });
  6002. }
  6003. /**
  6004. * 设置 Bucket 自定义域名
  6005. * @param {Object} params 参数对象,必须
  6006. * @param {String} params.Bucket Bucket名称,必须
  6007. * @param {String} params.Region 地域名称,必须
  6008. * @param {Function} callback 回调函数,必须
  6009. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6010. * @return {Object} data 返回数据
  6011. */
  6012. function putBucketDomain(params, callback) {
  6013. var DomainConfiguration = params['DomainConfiguration'] || {};
  6014. var DomainRule = DomainConfiguration.DomainRule || params.DomainRule || [];
  6015. DomainRule = util.clone(DomainRule);
  6016. var xml = util.json2xml({ DomainConfiguration: { DomainRule: DomainRule } });
  6017. var headers = params.Headers;
  6018. headers['Content-Type'] = 'application/xml';
  6019. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  6020. submitRequest.call(this, {
  6021. Action: 'name/cos:PutBucketDomain',
  6022. method: 'PUT',
  6023. Bucket: params.Bucket,
  6024. Region: params.Region,
  6025. body: xml,
  6026. action: 'domain',
  6027. headers: headers
  6028. }, function (err, data) {
  6029. if (err && err.statusCode === 204) {
  6030. return callback(null, { statusCode: err.statusCode });
  6031. } else if (err) {
  6032. return callback(err);
  6033. }
  6034. callback(null, {
  6035. statusCode: data.statusCode,
  6036. headers: data.headers
  6037. });
  6038. });
  6039. }
  6040. /**
  6041. * 获取 Bucket 的自定义域名
  6042. * @param {Object} params 参数对象,必须
  6043. * @param {String} params.Bucket Bucket名称,必须
  6044. * @param {String} params.Region 地域名称,必须
  6045. * @param {Function} callback 回调函数,必须
  6046. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6047. * @return {Object} data 返回数据
  6048. */
  6049. function getBucketDomain(params, callback) {
  6050. submitRequest.call(this, {
  6051. Action: 'name/cos:GetBucketDomain',
  6052. method: 'GET',
  6053. Bucket: params.Bucket,
  6054. Region: params.Region,
  6055. headers: params.Headers,
  6056. action: 'domain'
  6057. }, function (err, data) {
  6058. if (err) return callback(err);
  6059. var DomainRule = [];
  6060. try {
  6061. DomainRule = data.DomainConfiguration.DomainRule || [];
  6062. } catch (e) {}
  6063. DomainRule = util.clone(util.isArray(DomainRule) ? DomainRule : [DomainRule]);
  6064. callback(null, {
  6065. DomainRule: DomainRule,
  6066. statusCode: data.statusCode,
  6067. headers: data.headers
  6068. });
  6069. });
  6070. }
  6071. /**
  6072. * 删除 Bucket 自定义域名
  6073. * @param {Object} params 参数对象,必须
  6074. * @param {String} params.Bucket Bucket名称,必须
  6075. * @param {String} params.Region 地域名称,必须
  6076. * @param {Function} callback 回调函数,必须
  6077. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6078. * @return {Object} data 返回数据
  6079. */
  6080. function deleteBucketDomain(params, callback) {
  6081. submitRequest.call(this, {
  6082. Action: 'name/cos:DeleteBucketDomain',
  6083. method: 'DELETE',
  6084. Bucket: params.Bucket,
  6085. Region: params.Region,
  6086. headers: params.Headers,
  6087. action: 'domain'
  6088. }, function (err, data) {
  6089. if (err && err.statusCode === 204) {
  6090. return callback(null, { statusCode: err.statusCode });
  6091. } else if (err) {
  6092. return callback(err);
  6093. }
  6094. callback(null, {
  6095. statusCode: data.statusCode,
  6096. headers: data.headers
  6097. });
  6098. });
  6099. }
  6100. /**
  6101. * 设置 Bucket 的回源
  6102. * @param {Object} params 参数对象,必须
  6103. * @param {String} params.Bucket Bucket名称,必须
  6104. * @param {String} params.Region 地域名称,必须
  6105. * @param {Function} callback 回调函数,必须
  6106. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6107. * @return {Object} data 返回数据
  6108. */
  6109. function putBucketOrigin(params, callback) {
  6110. var OriginConfiguration = params['OriginConfiguration'] || {};
  6111. var OriginRule = OriginConfiguration.OriginRule || params.OriginRule || [];
  6112. OriginRule = util.clone(OriginRule);
  6113. var xml = util.json2xml({ OriginConfiguration: { OriginRule: OriginRule } });
  6114. var headers = params.Headers;
  6115. headers['Content-Type'] = 'application/xml';
  6116. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  6117. submitRequest.call(this, {
  6118. Action: 'name/cos:PutBucketOrigin',
  6119. method: 'PUT',
  6120. Bucket: params.Bucket,
  6121. Region: params.Region,
  6122. body: xml,
  6123. action: 'origin',
  6124. headers: headers
  6125. }, function (err, data) {
  6126. if (err && err.statusCode === 204) {
  6127. return callback(null, { statusCode: err.statusCode });
  6128. } else if (err) {
  6129. return callback(err);
  6130. }
  6131. callback(null, {
  6132. statusCode: data.statusCode,
  6133. headers: data.headers
  6134. });
  6135. });
  6136. }
  6137. /**
  6138. * 获取 Bucket 的回源
  6139. * @param {Object} params 参数对象,必须
  6140. * @param {String} params.Bucket Bucket名称,必须
  6141. * @param {String} params.Region 地域名称,必须
  6142. * @param {Function} callback 回调函数,必须
  6143. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6144. * @return {Object} data 返回数据
  6145. */
  6146. function getBucketOrigin(params, callback) {
  6147. submitRequest.call(this, {
  6148. Action: 'name/cos:GetBucketOrigin',
  6149. method: 'GET',
  6150. Bucket: params.Bucket,
  6151. Region: params.Region,
  6152. headers: params.Headers,
  6153. action: 'origin'
  6154. }, function (err, data) {
  6155. if (err) return callback(err);
  6156. var OriginRule = [];
  6157. try {
  6158. OriginRule = data.OriginConfiguration.OriginRule || [];
  6159. } catch (e) {}
  6160. OriginRule = util.clone(util.isArray(OriginRule) ? OriginRule : [OriginRule]);
  6161. callback(null, {
  6162. OriginRule: OriginRule,
  6163. statusCode: data.statusCode,
  6164. headers: data.headers
  6165. });
  6166. });
  6167. }
  6168. /**
  6169. * 删除 Bucket 的回源
  6170. * @param {Object} params 参数对象,必须
  6171. * @param {String} params.Bucket Bucket名称,必须
  6172. * @param {String} params.Region 地域名称,必须
  6173. * @param {Function} callback 回调函数,必须
  6174. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6175. * @return {Object} data 返回数据
  6176. */
  6177. function deleteBucketOrigin(params, callback) {
  6178. submitRequest.call(this, {
  6179. Action: 'name/cos:DeleteBucketOrigin',
  6180. method: 'DELETE',
  6181. Bucket: params.Bucket,
  6182. Region: params.Region,
  6183. headers: params.Headers,
  6184. action: 'origin'
  6185. }, function (err, data) {
  6186. if (err && err.statusCode === 204) {
  6187. return callback(null, { statusCode: err.statusCode });
  6188. } else if (err) {
  6189. return callback(err);
  6190. }
  6191. callback(null, {
  6192. statusCode: data.statusCode,
  6193. headers: data.headers
  6194. });
  6195. });
  6196. }
  6197. /**
  6198. * 设置 Bucket 的日志记录
  6199. * @param {Object} params 参数对象,必须
  6200. * @param {String} params.Bucket Bucket名称,必须
  6201. * @param {String} params.Region 地域名称,必须
  6202. * @param {(Object|String)} params.BucketLoggingStatus 说明日志记录配置的状态,如果无子节点信息则意为关闭日志记录,必须
  6203. * @param {Function} callback 回调函数,必须
  6204. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6205. * @return {Object} data 返回数据
  6206. */
  6207. function putBucketLogging(params, callback) {
  6208. var xml = util.json2xml({
  6209. BucketLoggingStatus: params['BucketLoggingStatus'] || ''
  6210. });
  6211. var headers = params.Headers;
  6212. headers['Content-Type'] = 'application/xml';
  6213. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  6214. submitRequest.call(this, {
  6215. Action: 'name/cos:PutBucketLogging',
  6216. method: 'PUT',
  6217. Bucket: params.Bucket,
  6218. Region: params.Region,
  6219. body: xml,
  6220. action: 'logging',
  6221. headers: headers
  6222. }, function (err, data) {
  6223. if (err && err.statusCode === 204) {
  6224. return callback(null, { statusCode: err.statusCode });
  6225. } else if (err) {
  6226. return callback(err);
  6227. }
  6228. callback(null, {
  6229. statusCode: data.statusCode,
  6230. headers: data.headers
  6231. });
  6232. });
  6233. }
  6234. /**
  6235. * 获取 Bucket 的日志记录
  6236. * @param {Object} params 参数对象,必须
  6237. * @param {String} params.Bucket Bucket名称,必须
  6238. * @param {String} params.Region 地域名称,必须
  6239. * @param {Function} callback 回调函数,必须
  6240. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6241. * @return {Object} data 返回数据
  6242. */
  6243. function getBucketLogging(params, callback) {
  6244. submitRequest.call(this, {
  6245. Action: 'name/cos:GetBucketLogging',
  6246. method: 'GET',
  6247. Bucket: params.Bucket,
  6248. Region: params.Region,
  6249. headers: params.Headers,
  6250. action: 'logging'
  6251. }, function (err, data) {
  6252. if (err) return callback(err);
  6253. delete data.BucketLoggingStatus._xmlns;
  6254. callback(null, {
  6255. BucketLoggingStatus: data.BucketLoggingStatus,
  6256. statusCode: data.statusCode,
  6257. headers: data.headers
  6258. });
  6259. });
  6260. }
  6261. /**
  6262. * 创建/编辑 Bucket 的清单任务
  6263. * @param {Object} params 参数对象,必须
  6264. * @param {String} params.Bucket Bucket名称,必须
  6265. * @param {String} params.Region 地域名称,必须
  6266. * @param {String} params.Id 清单任务的名称,必须
  6267. * @param {Object} params.InventoryConfiguration 包含清单的配置参数,必须
  6268. * @param {Function} callback 回调函数,必须
  6269. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6270. * @return {Object} data 返回数据
  6271. */
  6272. function putBucketInventory(params, callback) {
  6273. var InventoryConfiguration = util.clone(params['InventoryConfiguration']);
  6274. if (InventoryConfiguration.OptionalFields) {
  6275. var Field = InventoryConfiguration.OptionalFields || [];
  6276. InventoryConfiguration.OptionalFields = {
  6277. Field: Field
  6278. };
  6279. }
  6280. if (InventoryConfiguration.Destination && InventoryConfiguration.Destination.COSBucketDestination && InventoryConfiguration.Destination.COSBucketDestination.Encryption) {
  6281. var Encryption = InventoryConfiguration.Destination.COSBucketDestination.Encryption;
  6282. if (Object.keys(Encryption).indexOf('SSECOS') > -1) {
  6283. Encryption['SSE-COS'] = Encryption['SSECOS'];
  6284. delete Encryption['SSECOS'];
  6285. }
  6286. }
  6287. var xml = util.json2xml({
  6288. InventoryConfiguration: InventoryConfiguration
  6289. });
  6290. var headers = params.Headers;
  6291. headers['Content-Type'] = 'application/xml';
  6292. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  6293. submitRequest.call(this, {
  6294. Action: 'name/cos:PutBucketInventory',
  6295. method: 'PUT',
  6296. Bucket: params.Bucket,
  6297. Region: params.Region,
  6298. body: xml,
  6299. action: 'inventory',
  6300. qs: {
  6301. id: params['Id']
  6302. },
  6303. headers: headers
  6304. }, function (err, data) {
  6305. if (err && err.statusCode === 204) {
  6306. return callback(null, { statusCode: err.statusCode });
  6307. } else if (err) {
  6308. return callback(err);
  6309. }
  6310. callback(null, {
  6311. statusCode: data.statusCode,
  6312. headers: data.headers
  6313. });
  6314. });
  6315. }
  6316. /**
  6317. * 获取 Bucket 的清单任务信息
  6318. * @param {Object} params 参数对象,必须
  6319. * @param {String} params.Bucket Bucket名称,必须
  6320. * @param {String} params.Region 地域名称,必须
  6321. * @param {String} params.Id 清单任务的名称,必须
  6322. * @param {Function} callback 回调函数,必须
  6323. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6324. * @return {Object} data 返回数据
  6325. */
  6326. function getBucketInventory(params, callback) {
  6327. submitRequest.call(this, {
  6328. Action: 'name/cos:GetBucketInventory',
  6329. method: 'GET',
  6330. Bucket: params.Bucket,
  6331. Region: params.Region,
  6332. headers: params.Headers,
  6333. action: 'inventory',
  6334. qs: {
  6335. id: params['Id']
  6336. }
  6337. }, function (err, data) {
  6338. if (err) return callback(err);
  6339. var InventoryConfiguration = data['InventoryConfiguration'];
  6340. if (InventoryConfiguration && InventoryConfiguration.OptionalFields && InventoryConfiguration.OptionalFields.Field) {
  6341. var Field = InventoryConfiguration.OptionalFields.Field;
  6342. if (!util.isArray(Field)) {
  6343. Field = [Field];
  6344. }
  6345. InventoryConfiguration.OptionalFields = Field;
  6346. }
  6347. if (InventoryConfiguration.Destination && InventoryConfiguration.Destination.COSBucketDestination && InventoryConfiguration.Destination.COSBucketDestination.Encryption) {
  6348. var Encryption = InventoryConfiguration.Destination.COSBucketDestination.Encryption;
  6349. if (Object.keys(Encryption).indexOf('SSE-COS') > -1) {
  6350. Encryption['SSECOS'] = Encryption['SSE-COS'];
  6351. delete Encryption['SSE-COS'];
  6352. }
  6353. }
  6354. callback(null, {
  6355. InventoryConfiguration: InventoryConfiguration,
  6356. statusCode: data.statusCode,
  6357. headers: data.headers
  6358. });
  6359. });
  6360. }
  6361. /**
  6362. * 获取 Bucket 的清单任务信息
  6363. * @param {Object} params 参数对象,必须
  6364. * @param {String} params.Bucket Bucket名称,必须
  6365. * @param {String} params.Region 地域名称,必须
  6366. * @param {String} params.ContinuationToken 当 COS 响应体中 IsTruncated 为 true,且 NextContinuationToken 节点中存在参数值时,您可以将这个参数作为 continuation-token 参数值,以获取下一页的清单任务信息,非必须
  6367. * @param {Function} callback 回调函数,必须
  6368. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6369. * @return {Object} data 返回数据
  6370. */
  6371. function listBucketInventory(params, callback) {
  6372. submitRequest.call(this, {
  6373. Action: 'name/cos:ListBucketInventory',
  6374. method: 'GET',
  6375. Bucket: params.Bucket,
  6376. Region: params.Region,
  6377. headers: params.Headers,
  6378. action: 'inventory',
  6379. qs: {
  6380. 'continuation-token': params['ContinuationToken']
  6381. }
  6382. }, function (err, data) {
  6383. if (err) return callback(err);
  6384. var ListInventoryConfigurationResult = data['ListInventoryConfigurationResult'];
  6385. var InventoryConfigurations = ListInventoryConfigurationResult.InventoryConfiguration || [];
  6386. InventoryConfigurations = util.isArray(InventoryConfigurations) ? InventoryConfigurations : [InventoryConfigurations];
  6387. delete ListInventoryConfigurationResult['InventoryConfiguration'];
  6388. util.each(InventoryConfigurations, function (InventoryConfiguration) {
  6389. if (InventoryConfiguration && InventoryConfiguration.OptionalFields && InventoryConfiguration.OptionalFields.Field) {
  6390. var Field = InventoryConfiguration.OptionalFields.Field;
  6391. if (!util.isArray(Field)) {
  6392. Field = [Field];
  6393. }
  6394. InventoryConfiguration.OptionalFields = Field;
  6395. }
  6396. if (InventoryConfiguration.Destination && InventoryConfiguration.Destination.COSBucketDestination && InventoryConfiguration.Destination.COSBucketDestination.Encryption) {
  6397. var Encryption = InventoryConfiguration.Destination.COSBucketDestination.Encryption;
  6398. if (Object.keys(Encryption).indexOf('SSE-COS') > -1) {
  6399. Encryption['SSECOS'] = Encryption['SSE-COS'];
  6400. delete Encryption['SSE-COS'];
  6401. }
  6402. }
  6403. });
  6404. ListInventoryConfigurationResult.InventoryConfigurations = InventoryConfigurations;
  6405. util.extend(ListInventoryConfigurationResult, {
  6406. statusCode: data.statusCode,
  6407. headers: data.headers
  6408. });
  6409. callback(null, ListInventoryConfigurationResult);
  6410. });
  6411. }
  6412. /**
  6413. * 删除 Bucket 的清单任务
  6414. * @param {Object} params 参数对象,必须
  6415. * @param {String} params.Bucket Bucket名称,必须
  6416. * @param {String} params.Region 地域名称,必须
  6417. * @param {String} params.Id 清单任务的名称,必须
  6418. * @param {Function} callback 回调函数,必须
  6419. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6420. * @return {Object} data 返回数据
  6421. */
  6422. function deleteBucketInventory(params, callback) {
  6423. submitRequest.call(this, {
  6424. Action: 'name/cos:DeleteBucketInventory',
  6425. method: 'DELETE',
  6426. Bucket: params.Bucket,
  6427. Region: params.Region,
  6428. headers: params.Headers,
  6429. action: 'inventory',
  6430. qs: {
  6431. id: params['Id']
  6432. }
  6433. }, function (err, data) {
  6434. if (err && err.statusCode === 204) {
  6435. return callback(null, { statusCode: err.statusCode });
  6436. } else if (err) {
  6437. return callback(err);
  6438. }
  6439. callback(null, {
  6440. statusCode: data.statusCode,
  6441. headers: data.headers
  6442. });
  6443. });
  6444. }
  6445. /* 全球加速 */
  6446. function putBucketAccelerate(params, callback) {
  6447. if (!params['AccelerateConfiguration']) {
  6448. callback({ error: 'missing param AccelerateConfiguration' });
  6449. return;
  6450. }
  6451. var configuration = { AccelerateConfiguration: params.AccelerateConfiguration || {} };
  6452. var xml = util.json2xml(configuration);
  6453. var headers = {};
  6454. headers['Content-Type'] = 'application/xml';
  6455. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  6456. submitRequest.call(this, {
  6457. Interface: 'putBucketAccelerate',
  6458. Action: 'name/cos:PutBucketAccelerate',
  6459. method: 'PUT',
  6460. Bucket: params.Bucket,
  6461. Region: params.Region,
  6462. body: xml,
  6463. action: 'accelerate',
  6464. headers: headers
  6465. }, function (err, data) {
  6466. if (err) return callback(err);
  6467. callback(null, {
  6468. statusCode: data.statusCode,
  6469. headers: data.headers
  6470. });
  6471. });
  6472. }
  6473. function getBucketAccelerate(params, callback) {
  6474. submitRequest.call(this, {
  6475. Interface: 'getBucketAccelerate',
  6476. Action: 'name/cos:GetBucketAccelerate',
  6477. method: 'GET',
  6478. Bucket: params.Bucket,
  6479. Region: params.Region,
  6480. action: 'accelerate'
  6481. }, function (err, data) {
  6482. if (!err) {
  6483. !data.AccelerateConfiguration && (data.AccelerateConfiguration = {});
  6484. }
  6485. callback(err, data);
  6486. });
  6487. }
  6488. // Object 相关
  6489. /**
  6490. * 取回对应Object的元数据,Head的权限与Get的权限一致
  6491. * @param {Object} params 参数对象,必须
  6492. * @param {String} params.Bucket Bucket名称,必须
  6493. * @param {String} params.Region 地域名称,必须
  6494. * @param {String} params.Key 文件名称,必须
  6495. * @param {String} params.IfModifiedSince 当Object在指定时间后被修改,则返回对应Object元信息,否则返回304,非必须
  6496. * @param {Function} callback 回调函数,必须
  6497. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6498. * @return {Object} data 为指定 object 的元数据,如果设置了 IfModifiedSince ,且文件未修改,则返回一个对象,NotModified 属性为 true
  6499. * @return {Boolean} data.NotModified 是否在 IfModifiedSince 时间点之后未修改该 object,则为 true
  6500. */
  6501. function headObject(params, callback) {
  6502. submitRequest.call(this, {
  6503. Action: 'name/cos:HeadObject',
  6504. method: 'HEAD',
  6505. Bucket: params.Bucket,
  6506. Region: params.Region,
  6507. Key: params.Key,
  6508. VersionId: params.VersionId,
  6509. headers: params.Headers
  6510. }, function (err, data) {
  6511. if (err) {
  6512. var statusCode = err.statusCode;
  6513. if (params.Headers['If-Modified-Since'] && statusCode && statusCode === 304) {
  6514. return callback(null, {
  6515. NotModified: true,
  6516. statusCode: statusCode
  6517. });
  6518. }
  6519. return callback(err);
  6520. }
  6521. data.ETag = util.attr(data.headers, 'etag', '');
  6522. callback(null, data);
  6523. });
  6524. }
  6525. function listObjectVersions(params, callback) {
  6526. var reqParams = {};
  6527. reqParams['prefix'] = params['Prefix'] || '';
  6528. reqParams['delimiter'] = params['Delimiter'];
  6529. reqParams['key-marker'] = params['KeyMarker'];
  6530. reqParams['version-id-marker'] = params['VersionIdMarker'];
  6531. reqParams['max-keys'] = params['MaxKeys'];
  6532. reqParams['encoding-type'] = params['EncodingType'];
  6533. submitRequest.call(this, {
  6534. Action: 'name/cos:GetBucketObjectVersions',
  6535. ResourceKey: reqParams['prefix'],
  6536. method: 'GET',
  6537. Bucket: params.Bucket,
  6538. Region: params.Region,
  6539. headers: params.Headers,
  6540. qs: reqParams,
  6541. action: 'versions'
  6542. }, function (err, data) {
  6543. if (err) return callback(err);
  6544. var ListVersionsResult = data.ListVersionsResult || {};
  6545. var DeleteMarkers = ListVersionsResult.DeleteMarker || [];
  6546. DeleteMarkers = util.isArray(DeleteMarkers) ? DeleteMarkers : [DeleteMarkers];
  6547. var Versions = ListVersionsResult.Version || [];
  6548. Versions = util.isArray(Versions) ? Versions : [Versions];
  6549. var result = util.clone(ListVersionsResult);
  6550. delete result.DeleteMarker;
  6551. delete result.Version;
  6552. util.extend(result, {
  6553. DeleteMarkers: DeleteMarkers,
  6554. Versions: Versions,
  6555. statusCode: data.statusCode,
  6556. headers: data.headers
  6557. });
  6558. callback(null, result);
  6559. });
  6560. }
  6561. /**
  6562. * 下载 object
  6563. * @param {Object} params 参数对象,必须
  6564. * @param {String} params.Bucket Bucket名称,必须
  6565. * @param {String} params.Region 地域名称,必须
  6566. * @param {String} params.Key 文件名称,必须
  6567. * @param {WriteStream} params.Output 文件写入流,非必须
  6568. * @param {String} params.IfModifiedSince 当Object在指定时间后被修改,则返回对应Object元信息,否则返回304,非必须
  6569. * @param {String} params.IfUnmodifiedSince 如果文件修改时间早于或等于指定时间,才返回文件内容。否则返回 412 (precondition failed),非必须
  6570. * @param {String} params.IfMatch 当 ETag 与指定的内容一致,才返回文件。否则返回 412 (precondition failed),非必须
  6571. * @param {String} params.IfNoneMatch 当 ETag 与指定的内容不一致,才返回文件。否则返回304 (not modified),非必须
  6572. * @param {String} params.ResponseContentType 设置返回头部中的 Content-Type 参数,非必须
  6573. * @param {String} params.ResponseContentLanguage 设置返回头部中的 Content-Language 参数,非必须
  6574. * @param {String} params.ResponseExpires 设置返回头部中的 Content-Expires 参数,非必须
  6575. * @param {String} params.ResponseCacheControl 设置返回头部中的 Cache-Control 参数,非必须
  6576. * @param {String} params.ResponseContentDisposition 设置返回头部中的 Content-Disposition 参数,非必须
  6577. * @param {String} params.ResponseContentEncoding 设置返回头部中的 Content-Encoding 参数,非必须
  6578. * @param {Function} callback 回调函数,必须
  6579. * @param {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6580. * @param {Object} data 为对应的 object 数据,包括 body 和 headers
  6581. */
  6582. function getObject(params, callback) {
  6583. var reqParams = params.Query || {};
  6584. var reqParamsStr = params.QueryString || '';
  6585. reqParams['response-content-type'] = params['ResponseContentType'];
  6586. reqParams['response-content-language'] = params['ResponseContentLanguage'];
  6587. reqParams['response-expires'] = params['ResponseExpires'];
  6588. reqParams['response-cache-control'] = params['ResponseCacheControl'];
  6589. reqParams['response-content-disposition'] = params['ResponseContentDisposition'];
  6590. reqParams['response-content-encoding'] = params['ResponseContentEncoding'];
  6591. // 如果用户自己传入了 output
  6592. submitRequest.call(this, {
  6593. Action: 'name/cos:GetObject',
  6594. method: 'GET',
  6595. Bucket: params.Bucket,
  6596. Region: params.Region,
  6597. Key: params.Key,
  6598. VersionId: params.VersionId,
  6599. headers: params.Headers,
  6600. qs: reqParams,
  6601. qsStr: reqParamsStr,
  6602. rawBody: true
  6603. }, function (err, data) {
  6604. if (err) {
  6605. var statusCode = err.statusCode;
  6606. if (params.Headers['If-Modified-Since'] && statusCode && statusCode === 304) {
  6607. return callback(null, {
  6608. NotModified: true
  6609. });
  6610. }
  6611. return callback(err);
  6612. }
  6613. callback(null, {
  6614. Body: data.body,
  6615. ETag: util.attr(data.headers, 'etag', ''),
  6616. statusCode: data.statusCode,
  6617. headers: data.headers
  6618. });
  6619. });
  6620. }
  6621. /**
  6622. * 上传 object
  6623. * @param {Object} params 参数对象,必须
  6624. * @param {String} params.Bucket Bucket名称,必须
  6625. * @param {String} params.Region 地域名称,必须
  6626. * @param {String} params.Key 文件名称,必须
  6627. * @param {String} params.Body 上传文件的内容,只支持字符串
  6628. * @param {String} params.CacheControl RFC 2616 中定义的缓存策略,将作为 Object 元数据保存,非必须
  6629. * @param {String} params.ContentDisposition RFC 2616 中定义的文件名称,将作为 Object 元数据保存,非必须
  6630. * @param {String} params.ContentEncoding RFC 2616 中定义的编码格式,将作为 Object 元数据保存,非必须
  6631. * @param {String} params.ContentLength RFC 2616 中定义的 HTTP 请求内容长度(字节),必须
  6632. * @param {String} params.ContentType RFC 2616 中定义的内容类型(MIME),将作为 Object 元数据保存,非必须
  6633. * @param {String} params.Expect 当使用 Expect: 100-continue 时,在收到服务端确认后,才会发送请求内容,非必须
  6634. * @param {String} params.Expires RFC 2616 中定义的过期时间,将作为 Object 元数据保存,非必须
  6635. * @param {String} params.ContentSha1 RFC 3174 中定义的 160-bit 内容 SHA-1 算法校验,非必须
  6636. * @param {String} params.ACL 允许用户自定义文件权限,有效值:private | public-read,非必须
  6637. * @param {String} params.GrantRead 赋予被授权者读的权限,格式 x-cos-grant-read: uin=" ",uin=" ",非必须
  6638. * @param {String} params.GrantWrite 赋予被授权者写的权限,格式 x-cos-grant-write: uin=" ",uin=" ",非必须
  6639. * @param {String} params.GrantFullControl 赋予被授权者读写权限,格式 x-cos-grant-full-control: uin=" ",uin=" ",非必须
  6640. * @param {String} params.ServerSideEncryption 支持按照指定的加密算法进行服务端数据加密,格式 x-cos-server-side-encryption: "AES256",非必须
  6641. * @param {Function} params.onProgress 上传进度回调函数
  6642. * @param {Function} callback 回调函数,必须
  6643. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6644. * @return {Object} data 为对应的 object 数据
  6645. * @return {String} data.ETag 为对应上传文件的 ETag 值
  6646. */
  6647. function putObject(params, callback) {
  6648. var self = this;
  6649. var FileSize = params.ContentLength;
  6650. var onProgress = util.throttleOnProgress.call(self, FileSize, params.onProgress);
  6651. // 特殊处理 Cache-Control、Content-Type,避免代理更改这两个字段导致写入到 Object 属性里
  6652. var headers = params.Headers;
  6653. if (!headers['Cache-Control'] && !headers['cache-control']) headers['Cache-Control'] = '';
  6654. if (!headers['Content-Type'] && !headers['content-type']) headers['Content-Type'] = mime.getType(params.Key) || 'application/octet-stream';
  6655. util.getBodyMd5(self.options.UploadCheckContentMd5, params.Body, function (md5) {
  6656. if (md5) headers['Content-MD5'] = util.binaryBase64(md5);
  6657. if (params.ContentLength !== undefined) headers['Content-Length'] = params.ContentLength;
  6658. onProgress(null, true); // 任务状态开始 uploading
  6659. submitRequest.call(self, {
  6660. Action: 'name/cos:PutObject',
  6661. TaskId: params.TaskId,
  6662. method: 'PUT',
  6663. Bucket: params.Bucket,
  6664. Region: params.Region,
  6665. Key: params.Key,
  6666. headers: params.Headers,
  6667. qs: params.Query,
  6668. body: params.Body,
  6669. onProgress: onProgress
  6670. }, function (err, data) {
  6671. if (err) {
  6672. onProgress(null, true);
  6673. return callback(err);
  6674. }
  6675. onProgress({ loaded: FileSize, total: FileSize }, true);
  6676. var url = getUrl({
  6677. ForcePathStyle: self.options.ForcePathStyle,
  6678. protocol: self.options.Protocol,
  6679. domain: self.options.Domain,
  6680. bucket: params.Bucket,
  6681. region: !self.options.UseAccelerate ? params.Region : 'accelerate',
  6682. object: params.Key
  6683. });
  6684. url = url.substr(url.indexOf('://') + 3);
  6685. data.Location = url;
  6686. data.ETag = util.attr(data.headers, 'etag', '');
  6687. callback(null, data);
  6688. });
  6689. });
  6690. }
  6691. /**
  6692. * 上传 object
  6693. * @param {Object} params 参数对象,必须
  6694. * @param {String} params.Bucket Bucket名称,必须
  6695. * @param {String} params.Region 地域名称,必须
  6696. * @param {String} params.Key 文件名称,必须
  6697. * @param {FilePath} params.FilePath 要上传的文件路径
  6698. * @param {Function} params.onProgress 上传进度回调函数
  6699. * @param {Function} callback 回调函数,必须
  6700. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6701. * @return {Object} data 为对应的 object 数据
  6702. * @return {String} data.ETag 为对应上传文件的 ETag 值
  6703. */
  6704. function postObject(params, callback) {
  6705. var self = this;
  6706. var headers = {};
  6707. var filePath = params.FilePath;
  6708. if (!filePath) {
  6709. callback({ error: 'missing param FilePath' });
  6710. return;
  6711. }
  6712. headers['Cache-Control'] = params['CacheControl'];
  6713. headers['Content-Disposition'] = params['ContentDisposition'];
  6714. headers['Content-Encoding'] = params['ContentEncoding'];
  6715. headers['Content-MD5'] = params['ContentMD5'];
  6716. headers['Content-Length'] = params['ContentLength'];
  6717. headers['Content-Type'] = params['ContentType'];
  6718. headers['Expect'] = params['Expect'];
  6719. headers['Expires'] = params['Expires'];
  6720. headers['x-cos-acl'] = params['ACL'];
  6721. headers['x-cos-grant-read'] = params['GrantRead'];
  6722. headers['x-cos-grant-write'] = params['GrantWrite'];
  6723. headers['x-cos-grant-full-control'] = params['GrantFullControl'];
  6724. headers['x-cos-storage-class'] = params['StorageClass'];
  6725. headers['x-cos-mime-limit'] = params['MimeLimit'];
  6726. headers['x-cos-traffic-limit'] = params['TrafficLimit'];
  6727. // SSE-C
  6728. headers['x-cos-server-side-encryption-customer-algorithm'] = params['SSECustomerAlgorithm'];
  6729. headers['x-cos-server-side-encryption-customer-key'] = params['SSECustomerKey'];
  6730. headers['x-cos-server-side-encryption-customer-key-MD5'] = params['SSECustomerKeyMD5'];
  6731. // SSE-COS、SSE-KMS
  6732. headers['x-cos-server-side-encryption'] = params['ServerSideEncryption'];
  6733. headers['x-cos-server-side-encryption-cos-kms-key-id'] = params['SSEKMSKeyId'];
  6734. headers['x-cos-server-side-encryption-context'] = params['SSEContext'];
  6735. // 删除 Content-Length 避免签名错误
  6736. delete headers['Content-Length'];
  6737. delete headers['content-length'];
  6738. for (var key in params) {
  6739. if (key.indexOf('x-cos-meta-') > -1) {
  6740. headers[key] = params[key];
  6741. }
  6742. }
  6743. var onProgress = util.throttleOnProgress.call(self, headers['Content-Length'], params.onProgress);
  6744. submitRequest.call(this, {
  6745. Action: 'name/cos:PostObject',
  6746. method: 'POST',
  6747. Bucket: params.Bucket,
  6748. Region: params.Region,
  6749. Key: params.Key,
  6750. headers: headers,
  6751. qs: params.Query,
  6752. filePath: filePath,
  6753. onProgress: onProgress
  6754. }, function (err, data) {
  6755. onProgress(null, true);
  6756. if (err) return callback(err);
  6757. if (data && data.headers) {
  6758. var headers = data.headers;
  6759. var ETag = headers.etag || headers.Etag || headers.ETag || '';
  6760. var filename = filePath.substr(filePath.lastIndexOf('/') + 1);
  6761. var url = getUrl({
  6762. ForcePathStyle: self.options.ForcePathStyle,
  6763. protocol: self.options.Protocol,
  6764. domain: self.options.Domain,
  6765. bucket: params.Bucket,
  6766. region: params.Region,
  6767. object: params.Key.replace(/\$\{filename\}/g, filename),
  6768. isLocation: true
  6769. });
  6770. return callback(null, {
  6771. Location: url,
  6772. statusCode: data.statusCode,
  6773. headers: headers,
  6774. ETag: ETag
  6775. });
  6776. }
  6777. callback(null, data);
  6778. });
  6779. }
  6780. /**
  6781. * 删除 object
  6782. * @param {Object} params 参数对象,必须
  6783. * @param {String} params.Bucket Bucket名称,必须
  6784. * @param {String} params.Region 地域名称,必须
  6785. * @param {String} params.Key object名称,必须
  6786. * @param {Function} callback 回调函数,必须
  6787. * @param {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6788. * @param {Object} data 删除操作成功之后返回的数据
  6789. */
  6790. function deleteObject(params, callback) {
  6791. submitRequest.call(this, {
  6792. Action: 'name/cos:DeleteObject',
  6793. method: 'DELETE',
  6794. Bucket: params.Bucket,
  6795. Region: params.Region,
  6796. Key: params.Key,
  6797. headers: params.Headers,
  6798. VersionId: params.VersionId
  6799. }, function (err, data) {
  6800. if (err) {
  6801. var statusCode = err.statusCode;
  6802. if (statusCode && statusCode === 204) {
  6803. return callback(null, { statusCode: statusCode });
  6804. } else if (statusCode && statusCode === 404) {
  6805. return callback(null, { BucketNotFound: true, statusCode: statusCode });
  6806. } else {
  6807. return callback(err);
  6808. }
  6809. }
  6810. callback(null, {
  6811. statusCode: data.statusCode,
  6812. headers: data.headers
  6813. });
  6814. });
  6815. }
  6816. /**
  6817. * 获取 object 的 权限列表
  6818. * @param {Object} params 参数对象,必须
  6819. * @param {String} params.Bucket Bucket名称,必须
  6820. * @param {String} params.Region 地域名称,必须
  6821. * @param {String} params.Key object名称,必须
  6822. * @param {Function} callback 回调函数,必须
  6823. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6824. * @return {Object} data 返回的数据
  6825. * @return {Object} data.AccessControlPolicy 权限列表
  6826. */
  6827. function getObjectAcl(params, callback) {
  6828. submitRequest.call(this, {
  6829. Action: 'name/cos:GetObjectACL',
  6830. method: 'GET',
  6831. Bucket: params.Bucket,
  6832. Region: params.Region,
  6833. Key: params.Key,
  6834. headers: params.Headers,
  6835. action: 'acl'
  6836. }, function (err, data) {
  6837. if (err) return callback(err);
  6838. var AccessControlPolicy = data.AccessControlPolicy || {};
  6839. var Owner = AccessControlPolicy.Owner || {};
  6840. var Grant = AccessControlPolicy.AccessControlList && AccessControlPolicy.AccessControlList.Grant || [];
  6841. Grant = util.isArray(Grant) ? Grant : [Grant];
  6842. var result = decodeAcl(AccessControlPolicy);
  6843. if (data.headers && data.headers['x-cos-acl']) {
  6844. result.ACL = data.headers['x-cos-acl'];
  6845. }
  6846. result = util.extend(result, {
  6847. Owner: Owner,
  6848. Grants: Grant,
  6849. statusCode: data.statusCode,
  6850. headers: data.headers
  6851. });
  6852. callback(null, result);
  6853. });
  6854. }
  6855. /**
  6856. * 设置 object 的 权限列表
  6857. * @param {Object} params 参数对象,必须
  6858. * @param {String} params.Bucket Bucket名称,必须
  6859. * @param {String} params.Region 地域名称,必须
  6860. * @param {String} params.Key object名称,必须
  6861. * @param {Function} callback 回调函数,必须
  6862. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6863. * @return {Object} data 返回的数据
  6864. */
  6865. function putObjectAcl(params, callback) {
  6866. var headers = params.Headers;
  6867. var xml = '';
  6868. if (params['AccessControlPolicy']) {
  6869. var AccessControlPolicy = util.clone(params['AccessControlPolicy'] || {});
  6870. var Grants = AccessControlPolicy.Grants || AccessControlPolicy.Grant;
  6871. Grants = util.isArray(Grants) ? Grants : [Grants];
  6872. delete AccessControlPolicy.Grant;
  6873. delete AccessControlPolicy.Grants;
  6874. AccessControlPolicy.AccessControlList = { Grant: Grants };
  6875. xml = util.json2xml({ AccessControlPolicy: AccessControlPolicy });
  6876. headers['Content-Type'] = 'application/xml';
  6877. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  6878. }
  6879. // Grant Header 去重
  6880. util.each(headers, function (val, key) {
  6881. if (key.indexOf('x-cos-grant-') === 0) {
  6882. headers[key] = uniqGrant(headers[key]);
  6883. }
  6884. });
  6885. submitRequest.call(this, {
  6886. Action: 'name/cos:PutObjectACL',
  6887. method: 'PUT',
  6888. Bucket: params.Bucket,
  6889. Region: params.Region,
  6890. Key: params.Key,
  6891. action: 'acl',
  6892. headers: headers,
  6893. body: xml
  6894. }, function (err, data) {
  6895. if (err) return callback(err);
  6896. callback(null, {
  6897. statusCode: data.statusCode,
  6898. headers: data.headers
  6899. });
  6900. });
  6901. }
  6902. /**
  6903. * Options Object请求实现跨域访问的预请求。即发出一个 OPTIONS 请求给服务器以确认是否可以进行跨域操作。
  6904. * @param {Object} params 参数对象,必须
  6905. * @param {String} params.Bucket Bucket名称,必须
  6906. * @param {String} params.Region 地域名称,必须
  6907. * @param {String} params.Key object名称,必须
  6908. * @param {Function} callback 回调函数,必须
  6909. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6910. * @return {Object} data 返回的数据
  6911. */
  6912. function optionsObject(params, callback) {
  6913. var headers = params.Headers;
  6914. headers['Origin'] = params['Origin'];
  6915. headers['Access-Control-Request-Method'] = params['AccessControlRequestMethod'];
  6916. headers['Access-Control-Request-Headers'] = params['AccessControlRequestHeaders'];
  6917. submitRequest.call(this, {
  6918. Action: 'name/cos:OptionsObject',
  6919. method: 'OPTIONS',
  6920. Bucket: params.Bucket,
  6921. Region: params.Region,
  6922. Key: params.Key,
  6923. headers: headers
  6924. }, function (err, data) {
  6925. if (err) {
  6926. if (err.statusCode && err.statusCode === 403) {
  6927. return callback(null, {
  6928. OptionsForbidden: true,
  6929. statusCode: err.statusCode
  6930. });
  6931. }
  6932. return callback(err);
  6933. }
  6934. var headers = data.headers || {};
  6935. callback(null, {
  6936. AccessControlAllowOrigin: headers['access-control-allow-origin'],
  6937. AccessControlAllowMethods: headers['access-control-allow-methods'],
  6938. AccessControlAllowHeaders: headers['access-control-allow-headers'],
  6939. AccessControlExposeHeaders: headers['access-control-expose-headers'],
  6940. AccessControlMaxAge: headers['access-control-max-age'],
  6941. statusCode: data.statusCode,
  6942. headers: data.headers
  6943. });
  6944. });
  6945. }
  6946. /**
  6947. * @param {Object} 参数列表
  6948. * @param {String} Bucket Bucket 名称
  6949. * @param {String} Region 地域名称
  6950. * @param {String} Key 文件名称
  6951. * @param {String} CopySource 源文件URL绝对路径,可以通过versionid子资源指定历史版本
  6952. * @param {String} ACL 允许用户自定义文件权限。有效值:private,public-read默认值:private。
  6953. * @param {String} GrantRead 赋予被授权者读的权限,格式 x-cos-grant-read: uin=" ",uin=" ",当需要给子账户授权时,uin="RootAcountID/SubAccountID",当需要给根账户授权时,uin="RootAcountID"。
  6954. * @param {String} GrantWrite 赋予被授权者写的权限,格式 x-cos-grant-write: uin=" ",uin=" ",当需要给子账户授权时,uin="RootAcountID/SubAccountID",当需要给根账户授权时,uin="RootAcountID"。
  6955. * @param {String} GrantFullControl 赋予被授权者读写权限,格式 x-cos-grant-full-control: uin=" ",uin=" ",当需要给子账户授权时,uin="RootAcountID/SubAccountID",当需要给根账户授权时,uin="RootAcountID"。
  6956. * @param {String} MetadataDirective 是否拷贝元数据,枚举值:Copy, Replaced,默认值Copy。假如标记为Copy,忽略Header中的用户元数据信息直接复制;假如标记为Replaced,按Header信息修改元数据。当目标路径和原路径一致,即用户试图修改元数据时,必须为Replaced
  6957. * @param {String} CopySourceIfModifiedSince 当Object在指定时间后被修改,则执行操作,否则返回412。可与x-cos-copy-source-If-None-Match一起使用,与其他条件联合使用返回冲突。
  6958. * @param {String} CopySourceIfUnmodifiedSince 当Object在指定时间后未被修改,则执行操作,否则返回412。可与x-cos-copy-source-If-Match一起使用,与其他条件联合使用返回冲突。
  6959. * @param {String} CopySourceIfMatch 当Object的ETag和给定一致时,则执行操作,否则返回412。可与x-cos-copy-source-If-Unmodified-Since一起使用,与其他条件联合使用返回冲突。
  6960. * @param {String} CopySourceIfNoneMatch 当Object的ETag和给定不一致时,则执行操作,否则返回412。可与x-cos-copy-source-If-Modified-Since一起使用,与其他条件联合使用返回冲突。
  6961. * @param {String} StorageClass 存储级别,枚举值:存储级别,枚举值:Standard, Standard_IA,Archive;默认值:Standard
  6962. * @param {String} CacheControl 指定所有缓存机制在整个请求/响应链中必须服从的指令。
  6963. * @param {String} ContentDisposition MIME 协议的扩展,MIME 协议指示 MIME 用户代理如何显示附加的文件
  6964. * @param {String} ContentEncoding HTTP 中用来对「采用何种编码格式传输正文」进行协定的一对头部字段
  6965. * @param {String} ContentLength 设置响应消息的实体内容的大小,单位为字节
  6966. * @param {String} ContentType RFC 2616 中定义的 HTTP 请求内容类型(MIME),例如text/plain
  6967. * @param {String} Expect 请求的特定的服务器行为
  6968. * @param {String} Expires 响应过期的日期和时间
  6969. * @param {String} params.ServerSideEncryption 支持按照指定的加密算法进行服务端数据加密,格式 x-cos-server-side-encryption: "AES256",非必须
  6970. * @param {String} ContentLanguage 指定内容语言
  6971. * @param {String} x-cos-meta-* 允许用户自定义的头部信息,将作为 Object 元数据返回。大小限制2K。
  6972. */
  6973. function putObjectCopy(params, callback) {
  6974. // 特殊处理 Cache-Control
  6975. var headers = params.Headers;
  6976. if (!headers['Cache-Control'] && !!headers['cache-control']) headers['Cache-Control'] = '';
  6977. var CopySource = params.CopySource || '';
  6978. var m = CopySource.match(/^([^.]+-\d+)\.cos(v6)?\.([^.]+)\.[^/]+\/(.+)$/);
  6979. if (!m) {
  6980. callback({ error: 'CopySource format error' });
  6981. return;
  6982. }
  6983. var SourceBucket = m[1];
  6984. var SourceRegion = m[3];
  6985. var SourceKey = decodeURIComponent(m[4]);
  6986. submitRequest.call(this, {
  6987. Scope: [{
  6988. action: 'name/cos:GetObject',
  6989. bucket: SourceBucket,
  6990. region: SourceRegion,
  6991. prefix: SourceKey
  6992. }, {
  6993. action: 'name/cos:PutObject',
  6994. bucket: params.Bucket,
  6995. region: params.Region,
  6996. prefix: params.Key
  6997. }],
  6998. method: 'PUT',
  6999. Bucket: params.Bucket,
  7000. Region: params.Region,
  7001. Key: params.Key,
  7002. VersionId: params.VersionId,
  7003. headers: params.Headers
  7004. }, function (err, data) {
  7005. if (err) return callback(err);
  7006. var result = util.clone(data.CopyObjectResult || {});
  7007. util.extend(result, {
  7008. statusCode: data.statusCode,
  7009. headers: data.headers
  7010. });
  7011. callback(null, result);
  7012. });
  7013. }
  7014. function uploadPartCopy(params, callback) {
  7015. var CopySource = params.CopySource || '';
  7016. var m = CopySource.match(/^([^.]+-\d+)\.cos(v6)?\.([^.]+)\.[^/]+\/(.+)$/);
  7017. if (!m) {
  7018. callback({ error: 'CopySource format error' });
  7019. return;
  7020. }
  7021. var SourceBucket = m[1];
  7022. var SourceRegion = m[3];
  7023. var SourceKey = decodeURIComponent(m[4]);
  7024. submitRequest.call(this, {
  7025. Scope: [{
  7026. action: 'name/cos:GetObject',
  7027. bucket: SourceBucket,
  7028. region: SourceRegion,
  7029. prefix: SourceKey
  7030. }, {
  7031. action: 'name/cos:PutObject',
  7032. bucket: params.Bucket,
  7033. region: params.Region,
  7034. prefix: params.Key
  7035. }],
  7036. method: 'PUT',
  7037. Bucket: params.Bucket,
  7038. Region: params.Region,
  7039. Key: params.Key,
  7040. VersionId: params.VersionId,
  7041. qs: {
  7042. partNumber: params['PartNumber'],
  7043. uploadId: params['UploadId']
  7044. },
  7045. headers: params.Headers
  7046. }, function (err, data) {
  7047. if (err) return callback(err);
  7048. var result = util.clone(data.CopyPartResult || {});
  7049. util.extend(result, {
  7050. statusCode: data.statusCode,
  7051. headers: data.headers
  7052. });
  7053. callback(null, result);
  7054. });
  7055. }
  7056. function deleteMultipleObject(params, callback) {
  7057. var Objects = params.Objects || [];
  7058. var Quiet = params.Quiet;
  7059. Objects = util.isArray(Objects) ? Objects : [Objects];
  7060. var xml = util.json2xml({ Delete: { Object: Objects, Quiet: Quiet || false } });
  7061. var headers = params.Headers;
  7062. headers['Content-Type'] = 'application/xml';
  7063. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  7064. var Scope = util.map(Objects, function (v) {
  7065. return {
  7066. action: 'name/cos:DeleteObject',
  7067. bucket: params.Bucket,
  7068. region: params.Region,
  7069. prefix: v.Key
  7070. };
  7071. });
  7072. submitRequest.call(this, {
  7073. Scope: Scope,
  7074. method: 'POST',
  7075. Bucket: params.Bucket,
  7076. Region: params.Region,
  7077. body: xml,
  7078. action: 'delete',
  7079. headers: headers
  7080. }, function (err, data) {
  7081. if (err) return callback(err);
  7082. var DeleteResult = data.DeleteResult || {};
  7083. var Deleted = DeleteResult.Deleted || [];
  7084. var Errors = DeleteResult.Error || [];
  7085. Deleted = util.isArray(Deleted) ? Deleted : [Deleted];
  7086. Errors = util.isArray(Errors) ? Errors : [Errors];
  7087. var result = util.clone(DeleteResult);
  7088. util.extend(result, {
  7089. Error: Errors,
  7090. Deleted: Deleted,
  7091. statusCode: data.statusCode,
  7092. headers: data.headers
  7093. });
  7094. callback(null, result);
  7095. });
  7096. }
  7097. function restoreObject(params, callback) {
  7098. var headers = params.Headers;
  7099. if (!params['RestoreRequest']) {
  7100. callback({ error: 'missing param RestoreRequest' });
  7101. return;
  7102. }
  7103. var RestoreRequest = params.RestoreRequest || {};
  7104. var xml = util.json2xml({ RestoreRequest: RestoreRequest });
  7105. headers['Content-Type'] = 'application/xml';
  7106. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  7107. submitRequest.call(this, {
  7108. Action: 'name/cos:RestoreObject',
  7109. method: 'POST',
  7110. Bucket: params.Bucket,
  7111. Region: params.Region,
  7112. Key: params.Key,
  7113. VersionId: params.VersionId,
  7114. body: xml,
  7115. action: 'restore',
  7116. headers: headers
  7117. }, function (err, data) {
  7118. callback(err, data);
  7119. });
  7120. }
  7121. /**
  7122. * 设置 Object 的标签
  7123. * @param {Object} params 参数对象,必须
  7124. * @param {String} params.Bucket Object名称,必须
  7125. * @param {String} params.Region 地域名称,必须
  7126. * @param {Array} params.TagSet 标签设置,必须
  7127. * @param {Function} callback 回调函数,必须
  7128. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/42998
  7129. * @return {Object} data 返回数据
  7130. */
  7131. function putObjectTagging(params, callback) {
  7132. var Tagging = params['Tagging'] || {};
  7133. var Tags = Tagging.TagSet || Tagging.Tags || params['Tags'] || [];
  7134. Tags = util.clone(util.isArray(Tags) ? Tags : [Tags]);
  7135. var xml = util.json2xml({ Tagging: { TagSet: { Tag: Tags } } });
  7136. var headers = params.Headers;
  7137. headers['Content-Type'] = 'application/xml';
  7138. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  7139. submitRequest.call(this, {
  7140. Interface: 'putObjectTagging',
  7141. Action: 'name/cos:PutObjectTagging',
  7142. method: 'PUT',
  7143. Bucket: params.Bucket,
  7144. Key: params.Key,
  7145. Region: params.Region,
  7146. body: xml,
  7147. action: 'tagging',
  7148. headers: headers,
  7149. VersionId: params.VersionId
  7150. }, function (err, data) {
  7151. if (err && err.statusCode === 204) {
  7152. return callback(null, { statusCode: err.statusCode });
  7153. } else if (err) {
  7154. return callback(err);
  7155. }
  7156. callback(null, {
  7157. statusCode: data.statusCode,
  7158. headers: data.headers
  7159. });
  7160. });
  7161. }
  7162. /**
  7163. * 获取 Object 的标签设置
  7164. * @param {Object} params 参数对象,必须
  7165. * @param {String} params.Bucket Bucket名称,必须
  7166. * @param {String} params.Region 地域名称,必须
  7167. * @param {Function} callback 回调函数,必须
  7168. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/42998
  7169. * @return {Object} data 返回数据
  7170. */
  7171. function getObjectTagging(params, callback) {
  7172. submitRequest.call(this, {
  7173. Interface: 'getObjectTagging',
  7174. Action: 'name/cos:GetObjectTagging',
  7175. method: 'GET',
  7176. Key: params.Key,
  7177. Bucket: params.Bucket,
  7178. Region: params.Region,
  7179. headers: params.Headers,
  7180. action: 'tagging',
  7181. VersionId: params.VersionId
  7182. }, function (err, data) {
  7183. if (err) {
  7184. if (err.statusCode === 404 && err.error && (err.error === "Not Found" || err.error.Code === 'NoSuchTagSet')) {
  7185. var result = {
  7186. Tags: [],
  7187. statusCode: err.statusCode
  7188. };
  7189. err.headers && (result.headers = err.headers);
  7190. callback(null, result);
  7191. } else {
  7192. callback(err);
  7193. }
  7194. return;
  7195. }
  7196. var Tags = [];
  7197. try {
  7198. Tags = data.Tagging.TagSet.Tag || [];
  7199. } catch (e) {}
  7200. Tags = util.clone(util.isArray(Tags) ? Tags : [Tags]);
  7201. callback(null, {
  7202. Tags: Tags,
  7203. statusCode: data.statusCode,
  7204. headers: data.headers
  7205. });
  7206. });
  7207. }
  7208. /**
  7209. * 删除 Object 的 标签设置
  7210. * @param {Object} params 参数对象,必须
  7211. * @param {String} params.Bucket Object名称,必须
  7212. * @param {String} params.Region 地域名称,必须
  7213. * @param {Function} callback 回调函数,必须
  7214. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/42998
  7215. * @return {Object} data 返回的数据
  7216. */
  7217. function deleteObjectTagging(params, callback) {
  7218. submitRequest.call(this, {
  7219. Interface: 'deleteObjectTagging',
  7220. Action: 'name/cos:DeleteObjectTagging',
  7221. method: 'DELETE',
  7222. Bucket: params.Bucket,
  7223. Region: params.Region,
  7224. Key: params.Key,
  7225. headers: params.Headers,
  7226. action: 'tagging',
  7227. VersionId: params.VersionId
  7228. }, function (err, data) {
  7229. if (err && err.statusCode === 204) {
  7230. return callback(null, { statusCode: err.statusCode });
  7231. } else if (err) {
  7232. return callback(err);
  7233. }
  7234. callback(null, {
  7235. statusCode: data.statusCode,
  7236. headers: data.headers
  7237. });
  7238. });
  7239. }
  7240. // 分块上传
  7241. /**
  7242. * 初始化分块上传
  7243. * @param {Object} params 参数对象,必须
  7244. * @param {String} params.Bucket Bucket名称,必须
  7245. * @param {String} params.Region 地域名称,必须
  7246. * @param {String} params.Key object名称,必须
  7247. * @param {String} params.UploadId object名称,必须
  7248. * @param {String} params.CacheControl RFC 2616 中定义的缓存策略,将作为 Object 元数据保存,非必须
  7249. * @param {String} params.ContentDisposition RFC 2616 中定义的文件名称,将作为 Object 元数据保存 ,非必须
  7250. * @param {String} params.ContentEncoding RFC 2616 中定义的编码格式,将作为 Object 元数据保存,非必须
  7251. * @param {String} params.ContentType RFC 2616 中定义的内容类型(MIME),将作为 Object 元数据保存,非必须
  7252. * @param {String} params.Expires RFC 2616 中定义的过期时间,将作为 Object 元数据保存,非必须
  7253. * @param {String} params.ACL 允许用户自定义文件权限,非必须
  7254. * @param {String} params.GrantRead 赋予被授权者读的权限 ,非必须
  7255. * @param {String} params.GrantWrite 赋予被授权者写的权限 ,非必须
  7256. * @param {String} params.GrantFullControl 赋予被授权者读写权限 ,非必须
  7257. * @param {String} params.StorageClass 设置Object的存储级别,枚举值:Standard,Standard_IA,Archive,非必须
  7258. * @param {String} params.ServerSideEncryption 支持按照指定的加密算法进行服务端数据加密,格式 x-cos-server-side-encryption: "AES256",非必须
  7259. * @param {Function} callback 回调函数,必须
  7260. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7261. * @return {Object} data 返回的数据
  7262. */
  7263. function multipartInit(params, callback) {
  7264. var self = this;
  7265. var headers = params.Headers;
  7266. // 特殊处理 Cache-Control、Content-Type
  7267. if (!headers['Cache-Control'] && !headers['cache-control']) headers['Cache-Control'] = '';
  7268. if (!headers['Content-Type'] && !headers['content-type']) headers['Content-Type'] = mime.getType(params.Key) || 'application/octet-stream';
  7269. submitRequest.call(self, {
  7270. Action: 'name/cos:InitiateMultipartUpload',
  7271. method: 'POST',
  7272. Bucket: params.Bucket,
  7273. Region: params.Region,
  7274. Key: params.Key,
  7275. action: 'uploads',
  7276. headers: params.Headers,
  7277. qs: params.Query
  7278. }, function (err, data) {
  7279. if (err) return callback(err);
  7280. data = util.clone(data || {});
  7281. if (data && data.InitiateMultipartUploadResult) {
  7282. return callback(null, util.extend(data.InitiateMultipartUploadResult, {
  7283. statusCode: data.statusCode,
  7284. headers: data.headers
  7285. }));
  7286. }
  7287. callback(null, data);
  7288. });
  7289. }
  7290. /**
  7291. * 分块上传
  7292. * @param {Object} params 参数对象,必须
  7293. * @param {String} params.Bucket Bucket名称,必须
  7294. * @param {String} params.Region 地域名称,必须
  7295. * @param {String} params.Key object名称,必须
  7296. * @param {String} params.Body 上传文件对象或字符串
  7297. * @param {String} params.ContentLength RFC 2616 中定义的 HTTP 请求内容长度(字节),非必须
  7298. * @param {String} params.Expect 当使用 Expect: 100-continue 时,在收到服务端确认后,才会发送请求内容,非必须
  7299. * @param {String} params.ServerSideEncryption 支持按照指定的加密算法进行服务端数据加密,格式 x-cos-server-side-encryption: "AES256",非必须
  7300. * @param {String} params.ContentSha1 RFC 3174 中定义的 160-bit 内容 SHA-1 算法校验值,非必须
  7301. * @param {Function} callback 回调函数,必须
  7302. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7303. * @return {Object} data 返回的数据
  7304. * @return {Object} data.ETag 返回的文件分块 sha1 值
  7305. */
  7306. function multipartUpload(params, callback) {
  7307. var self = this;
  7308. util.getFileSize('multipartUpload', params, function () {
  7309. util.getBodyMd5(self.options.UploadCheckContentMd5, params.Body, function (md5) {
  7310. if (md5) params.Headers['Content-MD5'] = util.binaryBase64(md5);
  7311. submitRequest.call(self, {
  7312. Action: 'name/cos:UploadPart',
  7313. TaskId: params.TaskId,
  7314. method: 'PUT',
  7315. Bucket: params.Bucket,
  7316. Region: params.Region,
  7317. Key: params.Key,
  7318. qs: {
  7319. partNumber: params['PartNumber'],
  7320. uploadId: params['UploadId']
  7321. },
  7322. headers: params.Headers,
  7323. onProgress: params.onProgress,
  7324. body: params.Body || null
  7325. }, function (err, data) {
  7326. if (err) return callback(err);
  7327. callback(null, {
  7328. ETag: util.attr(data.headers, 'etag', {}),
  7329. statusCode: data.statusCode,
  7330. headers: data.headers
  7331. });
  7332. });
  7333. });
  7334. });
  7335. }
  7336. /**
  7337. * 完成分块上传
  7338. * @param {Object} params 参数对象,必须
  7339. * @param {String} params.Bucket Bucket名称,必须
  7340. * @param {String} params.Region 地域名称,必须
  7341. * @param {String} params.Key object名称,必须
  7342. * @param {Array} params.Parts 分块信息列表,必须
  7343. * @param {String} params.Parts[i].PartNumber 块编号,必须
  7344. * @param {String} params.Parts[i].ETag 分块的 sha1 校验值
  7345. * @param {Function} callback 回调函数,必须
  7346. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7347. * @return {Object} data 返回的数据
  7348. * @return {Object} data.CompleteMultipartUpload 完成分块上传后的文件信息,包括Location, Bucket, Key 和 ETag
  7349. */
  7350. function multipartComplete(params, callback) {
  7351. var self = this;
  7352. var UploadId = params.UploadId;
  7353. var Parts = params['Parts'];
  7354. for (var i = 0, len = Parts.length; i < len; i++) {
  7355. if (Parts[i]['ETag'].indexOf('"') === 0) {
  7356. continue;
  7357. }
  7358. Parts[i]['ETag'] = '"' + Parts[i]['ETag'] + '"';
  7359. }
  7360. var xml = util.json2xml({ CompleteMultipartUpload: { Part: Parts } });
  7361. var headers = params.Headers;
  7362. headers['Content-Type'] = 'application/xml';
  7363. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  7364. submitRequest.call(this, {
  7365. Action: 'name/cos:CompleteMultipartUpload',
  7366. method: 'POST',
  7367. Bucket: params.Bucket,
  7368. Region: params.Region,
  7369. Key: params.Key,
  7370. qs: {
  7371. uploadId: UploadId
  7372. },
  7373. body: xml,
  7374. headers: headers
  7375. }, function (err, data) {
  7376. if (err) return callback(err);
  7377. var url = getUrl({
  7378. ForcePathStyle: self.options.ForcePathStyle,
  7379. protocol: self.options.Protocol,
  7380. domain: self.options.Domain,
  7381. bucket: params.Bucket,
  7382. region: params.Region,
  7383. object: params.Key,
  7384. isLocation: true
  7385. });
  7386. var CompleteMultipartUploadResult = data.CompleteMultipartUploadResult || {};
  7387. var result = util.extend(CompleteMultipartUploadResult, {
  7388. Location: url,
  7389. statusCode: data.statusCode,
  7390. headers: data.headers
  7391. });
  7392. callback(null, result);
  7393. });
  7394. }
  7395. /**
  7396. * 分块上传任务列表查询
  7397. * @param {Object} params 参数对象,必须
  7398. * @param {String} params.Bucket Bucket名称,必须
  7399. * @param {String} params.Region 地域名称,必须
  7400. * @param {String} params.Delimiter 定界符为一个符号,如果有Prefix,则将Prefix到delimiter之间的相同路径归为一类,定义为Common Prefix,然后列出所有Common Prefix。如果没有Prefix,则从路径起点开始,非必须
  7401. * @param {String} params.EncodingType 规定返回值的编码方式,非必须
  7402. * @param {String} params.Prefix 前缀匹配,用来规定返回的文件前缀地址,非必须
  7403. * @param {String} params.MaxUploads 单次返回最大的条目数量,默认1000,非必须
  7404. * @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的条目将被列出,非必须
  7405. * @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的条目将被列出,非必须
  7406. * @param {Function} callback 回调函数,必须
  7407. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7408. * @return {Object} data 返回的数据
  7409. * @return {Object} data.ListMultipartUploadsResult 分块上传任务信息
  7410. */
  7411. function multipartList(params, callback) {
  7412. var reqParams = {};
  7413. reqParams['delimiter'] = params['Delimiter'];
  7414. reqParams['encoding-type'] = params['EncodingType'];
  7415. reqParams['prefix'] = params['Prefix'] || '';
  7416. reqParams['max-uploads'] = params['MaxUploads'];
  7417. reqParams['key-marker'] = params['KeyMarker'];
  7418. reqParams['upload-id-marker'] = params['UploadIdMarker'];
  7419. reqParams = util.clearKey(reqParams);
  7420. submitRequest.call(this, {
  7421. Action: 'name/cos:ListMultipartUploads',
  7422. ResourceKey: reqParams['prefix'],
  7423. method: 'GET',
  7424. Bucket: params.Bucket,
  7425. Region: params.Region,
  7426. headers: params.Headers,
  7427. qs: reqParams,
  7428. action: 'uploads'
  7429. }, function (err, data) {
  7430. if (err) return callback(err);
  7431. if (data && data.ListMultipartUploadsResult) {
  7432. var Upload = data.ListMultipartUploadsResult.Upload || [];
  7433. var CommonPrefixes = data.ListMultipartUploadsResult.CommonPrefixes || [];
  7434. CommonPrefixes = util.isArray(CommonPrefixes) ? CommonPrefixes : [CommonPrefixes];
  7435. Upload = util.isArray(Upload) ? Upload : [Upload];
  7436. data.ListMultipartUploadsResult.Upload = Upload;
  7437. data.ListMultipartUploadsResult.CommonPrefixes = CommonPrefixes;
  7438. }
  7439. var result = util.clone(data.ListMultipartUploadsResult || {});
  7440. util.extend(result, {
  7441. statusCode: data.statusCode,
  7442. headers: data.headers
  7443. });
  7444. callback(null, result);
  7445. });
  7446. }
  7447. /**
  7448. * 上传的分块列表查询
  7449. * @param {Object} params 参数对象,必须
  7450. * @param {String} params.Bucket Bucket名称,必须
  7451. * @param {String} params.Region 地域名称,必须
  7452. * @param {String} params.Key object名称,必须
  7453. * @param {String} params.UploadId 标示本次分块上传的ID,必须
  7454. * @param {String} params.EncodingType 规定返回值的编码方式,非必须
  7455. * @param {String} params.MaxParts 单次返回最大的条目数量,默认1000,非必须
  7456. * @param {String} params.PartNumberMarker 默认以UTF-8二进制顺序列出条目,所有列出条目从marker开始,非必须
  7457. * @param {Function} callback 回调函数,必须
  7458. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7459. * @return {Object} data 返回的数据
  7460. * @return {Object} data.ListMultipartUploadsResult 分块信息
  7461. */
  7462. function multipartListPart(params, callback) {
  7463. var reqParams = {};
  7464. reqParams['uploadId'] = params['UploadId'];
  7465. reqParams['encoding-type'] = params['EncodingType'];
  7466. reqParams['max-parts'] = params['MaxParts'];
  7467. reqParams['part-number-marker'] = params['PartNumberMarker'];
  7468. submitRequest.call(this, {
  7469. Action: 'name/cos:ListParts',
  7470. method: 'GET',
  7471. Bucket: params.Bucket,
  7472. Region: params.Region,
  7473. Key: params.Key,
  7474. headers: params.Headers,
  7475. qs: reqParams
  7476. }, function (err, data) {
  7477. if (err) return callback(err);
  7478. var ListPartsResult = data.ListPartsResult || {};
  7479. var Part = ListPartsResult.Part || [];
  7480. Part = util.isArray(Part) ? Part : [Part];
  7481. ListPartsResult.Part = Part;
  7482. var result = util.clone(ListPartsResult);
  7483. util.extend(result, {
  7484. statusCode: data.statusCode,
  7485. headers: data.headers
  7486. });
  7487. callback(null, result);
  7488. });
  7489. }
  7490. /**
  7491. * 抛弃分块上传
  7492. * @param {Object} params 参数对象,必须
  7493. * @param {String} params.Bucket Bucket名称,必须
  7494. * @param {String} params.Region 地域名称,必须
  7495. * @param {String} params.Key object名称,必须
  7496. * @param {String} params.UploadId 标示本次分块上传的ID,必须
  7497. * @param {Function} callback 回调函数,必须
  7498. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7499. * @return {Object} data 返回的数据
  7500. */
  7501. function multipartAbort(params, callback) {
  7502. var reqParams = {};
  7503. reqParams['uploadId'] = params['UploadId'];
  7504. submitRequest.call(this, {
  7505. Action: 'name/cos:AbortMultipartUpload',
  7506. method: 'DELETE',
  7507. Bucket: params.Bucket,
  7508. Region: params.Region,
  7509. Key: params.Key,
  7510. headers: params.Headers,
  7511. qs: reqParams
  7512. }, function (err, data) {
  7513. if (err) return callback(err);
  7514. callback(null, {
  7515. statusCode: data.statusCode,
  7516. headers: data.headers
  7517. });
  7518. });
  7519. }
  7520. /**
  7521. * 追加上传
  7522. * @param {Object} params 参数对象,必须
  7523. * @param {String} params.Bucket Bucket名称,必须
  7524. * @param {String} params.Region 地域名称,必须
  7525. * @param {String} params.Key object名称,必须
  7526. * @param {String} params.Body 上传文件的内容,只支持字符串
  7527. * @param {Number} params.Position 追加操作的起始点,单位为字节,必须
  7528. * @param {String} params.CacheControl RFC 2616 中定义的缓存策略,将作为 Object 元数据保存,非必须
  7529. * @param {String} params.ContentDisposition RFC 2616 中定义的文件名称,将作为 Object 元数据保存,非必须
  7530. * @param {String} params.ContentEncoding RFC 2616 中定义的编码格式,将作为 Object 元数据保存,非必须
  7531. * @param {String} params.ContentLength RFC 2616 中定义的 HTTP 请求内容长度(字节),必须
  7532. * @param {String} params.ContentType RFC 2616 中定义的内容类型(MIME),将作为 Object 元数据保存,非必须
  7533. * @param {String} params.Expect 当使用 Expect: 100-continue 时,在收到服务端确认后,才会发送请求内容,非必须
  7534. * @param {String} params.Expires RFC 2616 中定义的过期时间,将作为 Object 元数据保存,非必须
  7535. * @param {String} params.ACL 允许用户自定义文件权限,有效值:private | public-read,非必须
  7536. * @param {String} params.GrantRead 赋予被授权者读取对象的权限,格式:id="[OwnerUin]",可使用半角逗号(,)分隔多组被授权者,非必须
  7537. * @param {String} params.GrantReadAcp 赋予被授权者读取对象的访问控制列表(ACL)的权限,格式:id="[OwnerUin]",可使用半角逗号(,)分隔多组被授权者,非必须
  7538. * @param {String} params.GrantWriteAcp 赋予被授权者写入对象的访问控制列表(ACL)的权限,格式:id="[OwnerUin]",可使用半角逗号(,)分隔多组被授权者,非必须
  7539. * @param {String} params.GrantFullControl 赋予被授权者操作对象的所有权限,格式:id="[OwnerUin]",可使用半角逗号(,)分隔多组被授权者,非必须
  7540. * @param {String} params.StorageClass 设置对象的存储级别,枚举值:STANDARD、STANDARD_IA、ARCHIVE,默认值:STANDARD,非必须
  7541. * @param {String} params.x-cos-meta-* 允许用户自定义的头部信息,将作为对象的元数据保存。大小限制2KB,非必须
  7542. * @param {String} params.ContentSha1 RFC 3174 中定义的 160-bit 内容 SHA-1 算法校验,非必须
  7543. * @param {String} params.ServerSideEncryption 支持按照指定的加密算法进行服务端数据加密,格式 x-cos-server-side-encryption: "AES256",非必须
  7544. * @param {Function} callback 回调函数,必须
  7545. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7546. * @return {Object} data 返回的数据
  7547. */
  7548. function appendObject(params, callback) {
  7549. submitRequest.call(this, {
  7550. Action: 'name/cos:AppendObject',
  7551. method: 'POST',
  7552. Bucket: params.Bucket,
  7553. Region: params.Region,
  7554. action: 'append',
  7555. Key: params.Key,
  7556. body: params.Body,
  7557. qs: {
  7558. position: params.Position
  7559. },
  7560. headers: params.Headers
  7561. }, function (err, data) {
  7562. if (err) return callback(err);
  7563. callback(null, data);
  7564. });
  7565. }
  7566. /**
  7567. * cos 内置请求
  7568. * @param {Object} params 参数对象,必须
  7569. * @param {String} params.Bucket Bucket名称,必须
  7570. * @param {String} params.Region 地域名称,必须
  7571. * @param {String} params.Key object名称,必须
  7572. * @param {Function} callback 回调函数,必须
  7573. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7574. * @return {Object} data 返回的数据
  7575. */
  7576. function request(params, callback) {
  7577. submitRequest.call(this, {
  7578. method: params.Method,
  7579. Bucket: params.Bucket,
  7580. Region: params.Region,
  7581. Key: params.Key,
  7582. action: params.Action,
  7583. headers: params.Headers,
  7584. qs: params.Query,
  7585. body: params.Body,
  7586. Url: params.Url,
  7587. rawBody: params.RawBody
  7588. }, function (err, data) {
  7589. if (err) return callback(err);
  7590. if (data && data.body) {
  7591. data.Body = data.body;
  7592. delete data.body;
  7593. }
  7594. callback(err, data);
  7595. });
  7596. }
  7597. /**
  7598. * 获取签名
  7599. * @param {Object} params 参数对象,必须
  7600. * @param {String} params.Method 请求方法,必须
  7601. * @param {String} params.Key object名称,必须
  7602. * @param {String} params.Expires 名超时时间,单位秒,可选
  7603. * @return {String} data 返回签名字符串
  7604. */
  7605. function getAuth(params) {
  7606. var self = this;
  7607. return util.getAuth({
  7608. SecretId: params.SecretId || this.options.SecretId || '',
  7609. SecretKey: params.SecretKey || this.options.SecretKey || '',
  7610. Bucket: params.Bucket,
  7611. Region: params.Region,
  7612. Method: params.Method,
  7613. Key: params.Key,
  7614. Query: params.Query,
  7615. Headers: params.Headers,
  7616. Expires: params.Expires,
  7617. SystemClockOffset: self.options.SystemClockOffset
  7618. });
  7619. }
  7620. /**
  7621. * 获取文件下载链接
  7622. * @param {Object} params 参数对象,必须
  7623. * @param {String} params.Bucket Bucket名称,必须
  7624. * @param {String} params.Region 地域名称,必须
  7625. * @param {String} params.Key object名称,必须
  7626. * @param {String} params.Method 请求的方法,可选
  7627. * @param {String} params.Expires 签名超时时间,单位秒,可选
  7628. * @param {Function} callback 回调函数,必须
  7629. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7630. * @return {Object} data 返回的数据
  7631. */
  7632. function getObjectUrl(params, callback) {
  7633. var self = this;
  7634. var url = getUrl({
  7635. ForcePathStyle: self.options.ForcePathStyle,
  7636. protocol: params.Protocol || self.options.Protocol,
  7637. domain: params.Domain || self.options.Domain,
  7638. bucket: params.Bucket,
  7639. region: params.Region,
  7640. object: params.Key
  7641. });
  7642. var queryParamsStr = '';
  7643. if (params.Query) {
  7644. queryParamsStr += util.obj2str(params.Query);
  7645. }
  7646. if (params.QueryString) {
  7647. queryParamsStr += (queryParamsStr ? '&' : '') + params.QueryString;
  7648. }
  7649. var syncUrl = url;
  7650. if (params.Sign !== undefined && !params.Sign) {
  7651. queryParamsStr && (syncUrl += '?' + queryParamsStr);
  7652. callback(null, { Url: syncUrl });
  7653. return syncUrl;
  7654. }
  7655. // 签名加上 Host,避免跨桶访问
  7656. var SignHost = getSignHost.call(this, { Bucket: params.Bucket, Region: params.Region, Url: url });
  7657. var AuthData = getAuthorizationAsync.call(this, {
  7658. Action: (params.Method || '').toUpperCase() === 'PUT' ? 'name/cos:PutObject' : 'name/cos:GetObject',
  7659. Bucket: params.Bucket || '',
  7660. Region: params.Region || '',
  7661. Method: params.Method || 'get',
  7662. Key: params.Key,
  7663. Expires: params.Expires,
  7664. Headers: params.Headers,
  7665. Query: params.Query,
  7666. SignHost: SignHost
  7667. }, function (err, AuthData) {
  7668. if (!callback) return;
  7669. if (err) {
  7670. callback(err);
  7671. return;
  7672. }
  7673. // 兼容万象url qUrlParamList需要再encode一次
  7674. var replaceUrlParamList = function replaceUrlParamList(url) {
  7675. var urlParams = url.match(/q-url-param-list.*?(?=&)/g)[0];
  7676. var encodedParams = 'q-url-param-list=' + encodeURIComponent(urlParams.replace(/q-url-param-list=/, '')).toLowerCase();
  7677. var reg = new RegExp(urlParams, 'g');
  7678. var replacedUrl = url.replace(reg, encodedParams);
  7679. return replacedUrl;
  7680. };
  7681. var signUrl = url;
  7682. signUrl += '?' + (AuthData.Authorization.indexOf('q-signature') > -1 ? replaceUrlParamList(AuthData.Authorization) : 'sign=' + encodeURIComponent(AuthData.Authorization));
  7683. AuthData.XCosSecurityToken && (signUrl += '&x-cos-security-token=' + AuthData.XCosSecurityToken);
  7684. AuthData.ClientIP && (signUrl += '&clientIP=' + AuthData.ClientIP);
  7685. AuthData.ClientUA && (signUrl += '&clientUA=' + AuthData.ClientUA);
  7686. AuthData.Token && (signUrl += '&token=' + AuthData.Token);
  7687. queryParamsStr && (signUrl += '&' + queryParamsStr);
  7688. setTimeout(function () {
  7689. callback(null, { Url: signUrl });
  7690. });
  7691. });
  7692. if (AuthData) {
  7693. syncUrl += '?' + AuthData.Authorization + (AuthData.XCosSecurityToken ? '&x-cos-security-token=' + AuthData.XCosSecurityToken : '');
  7694. queryParamsStr && (syncUrl += '&' + queryParamsStr);
  7695. } else {
  7696. queryParamsStr && (syncUrl += '?' + queryParamsStr);
  7697. }
  7698. return syncUrl;
  7699. }
  7700. /**
  7701. * 私有方法
  7702. */
  7703. function decodeAcl(AccessControlPolicy) {
  7704. var result = {
  7705. GrantFullControl: [],
  7706. GrantWrite: [],
  7707. GrantRead: [],
  7708. GrantReadAcp: [],
  7709. GrantWriteAcp: [],
  7710. ACL: ''
  7711. };
  7712. var GrantMap = {
  7713. 'FULL_CONTROL': 'GrantFullControl',
  7714. 'WRITE': 'GrantWrite',
  7715. 'READ': 'GrantRead',
  7716. 'READ_ACP': 'GrantReadAcp',
  7717. 'WRITE_ACP': 'GrantWriteAcp'
  7718. };
  7719. var AccessControlList = AccessControlPolicy && AccessControlPolicy.AccessControlList || {};
  7720. var Grant = AccessControlList.Grant;
  7721. if (Grant) {
  7722. Grant = util.isArray(Grant) ? Grant : [Grant];
  7723. }
  7724. var PublicAcl = { READ: 0, WRITE: 0, FULL_CONTROL: 0 };
  7725. Grant && Grant.length && util.each(Grant, function (item) {
  7726. if (item.Grantee.ID === 'qcs::cam::anyone:anyone' || item.Grantee.URI === 'http://cam.qcloud.com/groups/global/AllUsers') {
  7727. PublicAcl[item.Permission] = 1;
  7728. } else if (item.Grantee.ID !== AccessControlPolicy.Owner.ID) {
  7729. result[GrantMap[item.Permission]].push('id="' + item.Grantee.ID + '"');
  7730. }
  7731. });
  7732. if (PublicAcl.FULL_CONTROL || PublicAcl.WRITE && PublicAcl.READ) {
  7733. result.ACL = 'public-read-write';
  7734. } else if (PublicAcl.READ) {
  7735. result.ACL = 'public-read';
  7736. } else {
  7737. result.ACL = 'private';
  7738. }
  7739. util.each(GrantMap, function (item) {
  7740. result[item] = uniqGrant(result[item].join(','));
  7741. });
  7742. return result;
  7743. }
  7744. // Grant 去重
  7745. function uniqGrant(str) {
  7746. var arr = str.split(',');
  7747. var exist = {};
  7748. var i, item;
  7749. for (i = 0; i < arr.length;) {
  7750. item = arr[i].trim();
  7751. if (exist[item]) {
  7752. arr.splice(i, 1);
  7753. } else {
  7754. exist[item] = true;
  7755. arr[i] = item;
  7756. i++;
  7757. }
  7758. }
  7759. return arr.join(',');
  7760. }
  7761. // 生成操作 url
  7762. function getUrl(params) {
  7763. var longBucket = params.bucket;
  7764. var shortBucket = longBucket.substr(0, longBucket.lastIndexOf('-'));
  7765. var appId = longBucket.substr(longBucket.lastIndexOf('-') + 1);
  7766. var domain = params.domain;
  7767. var region = params.region;
  7768. var object = params.object;
  7769. var protocol = 'https:';
  7770. if (!domain) {
  7771. if (['cn-south', 'cn-south-2', 'cn-north', 'cn-east', 'cn-southwest', 'sg'].indexOf(region) > -1) {
  7772. domain = '{Region}.myqcloud.com';
  7773. } else {
  7774. domain = 'cos.{Region}.myqcloud.com';
  7775. }
  7776. if (!params.ForcePathStyle) {
  7777. domain = '{Bucket}.' + domain;
  7778. }
  7779. }
  7780. domain = domain.replace(/\{\{AppId\}\}/ig, appId).replace(/\{\{Bucket\}\}/ig, shortBucket).replace(/\{\{Region\}\}/ig, region).replace(/\{\{.*?\}\}/ig, '');
  7781. domain = domain.replace(/\{AppId\}/ig, appId).replace(/\{BucketName\}/ig, shortBucket).replace(/\{Bucket\}/ig, longBucket).replace(/\{Region\}/ig, region).replace(/\{.*?\}/ig, '');
  7782. if (!/^[a-zA-Z]+:\/\//.test(domain)) {
  7783. domain = protocol + '//' + domain;
  7784. }
  7785. // 去掉域名最后的斜杆
  7786. if (domain.slice(-1) === '/') {
  7787. domain = domain.slice(0, -1);
  7788. }
  7789. var url = domain;
  7790. if (params.ForcePathStyle) {
  7791. url += '/' + longBucket;
  7792. }
  7793. url += '/';
  7794. if (object) {
  7795. url += util.camSafeUrlEncode(object).replace(/%2F/g, '/');
  7796. }
  7797. if (params.isLocation) {
  7798. url = url.replace(/^https?:\/\//, '');
  7799. }
  7800. return url;
  7801. }
  7802. var getSignHost = function getSignHost(opt) {
  7803. if (!opt.Bucket || !opt.Region) return '';
  7804. var url = opt.Url || getUrl({
  7805. ForcePathStyle: this.options.ForcePathStyle,
  7806. protocol: this.options.Protocol,
  7807. domain: this.options.Domain,
  7808. bucket: opt.Bucket,
  7809. region: this.options.UseAccelerate ? 'accelerate' : opt.Region
  7810. });
  7811. var urlHost = url.replace(/^https?:\/\/([^/]+)(\/.*)?$/, '$1');
  7812. var standardHostReg = new RegExp('^([a-z\\d-]+-\\d+\\.)?(cos|cosv6|ci|pic)\\.([a-z\\d-]+)\\.myqcloud\\.com$');
  7813. if (standardHostReg.test(urlHost)) return urlHost;
  7814. return '';
  7815. };
  7816. // 异步获取签名
  7817. function getAuthorizationAsync(params, callback) {
  7818. var headers = util.clone(params.Headers);
  7819. var headerHost = '';
  7820. util.each(headers, function (v, k) {
  7821. (v === '' || ['content-type', 'cache-control'].indexOf(k.toLowerCase()) > -1) && delete headers[k];
  7822. if (k.toLowerCase() === 'host') headerHost = v;
  7823. });
  7824. // Host 加入签名计算
  7825. if (!headerHost && params.SignHost) headers.Host = params.SignHost;
  7826. var cb = function cb(AuthData) {
  7827. // 检查签名格式
  7828. var formatAllow = false;
  7829. var auth = AuthData.Authorization;
  7830. if (auth) {
  7831. if (auth.indexOf(' ') > -1) {
  7832. formatAllow = false;
  7833. } 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) {
  7834. formatAllow = true;
  7835. } else {
  7836. try {
  7837. auth = base64.atob(auth);
  7838. if (auth.indexOf('a=') > -1 && auth.indexOf('k=') > -1 && auth.indexOf('t=') > -1 && auth.indexOf('r=') > -1 && auth.indexOf('b=') > -1) {
  7839. formatAllow = true;
  7840. }
  7841. } catch (e) {}
  7842. }
  7843. }
  7844. if (formatAllow) {
  7845. callback && callback(null, AuthData);
  7846. } else {
  7847. callback && callback('authorization error');
  7848. }
  7849. };
  7850. var self = this;
  7851. var Bucket = params.Bucket || '';
  7852. var Region = params.Region || '';
  7853. // PathName
  7854. var KeyName = params.Action === 'name/cos:PostObject' || !params.Key ? '' : params.Key;
  7855. if (self.options.ForcePathStyle && Bucket) {
  7856. KeyName = Bucket + '/' + KeyName;
  7857. }
  7858. var Pathname = '/' + KeyName;
  7859. // Action、ResourceKey
  7860. var StsData = {};
  7861. var Scope = params.Scope;
  7862. if (!Scope) {
  7863. var Action = params.Action || '';
  7864. var ResourceKey = params.ResourceKey || params.Key || '';
  7865. Scope = params.Scope || [{
  7866. action: Action,
  7867. bucket: Bucket,
  7868. region: Region,
  7869. prefix: ResourceKey
  7870. }];
  7871. }
  7872. var ScopeKey = util.md5(JSON.stringify(Scope));
  7873. // STS
  7874. self._StsCache = self._StsCache || [];
  7875. (function () {
  7876. var i, AuthData;
  7877. for (i = self._StsCache.length - 1; i >= 0; i--) {
  7878. AuthData = self._StsCache[i];
  7879. var compareTime = Math.round(util.getSkewTime(self.options.SystemClockOffset) / 1000) + 30;
  7880. if (AuthData.StartTime && compareTime < AuthData.StartTime || compareTime >= AuthData.ExpiredTime) {
  7881. self._StsCache.splice(i, 1);
  7882. continue;
  7883. }
  7884. if (!AuthData.ScopeLimit || AuthData.ScopeLimit && AuthData.ScopeKey === ScopeKey) {
  7885. StsData = AuthData;
  7886. break;
  7887. }
  7888. }
  7889. })();
  7890. var calcAuthByTmpKey = function calcAuthByTmpKey() {
  7891. var KeyTime = StsData.StartTime && StsData.ExpiredTime ? StsData.StartTime + ';' + StsData.ExpiredTime : '';
  7892. var Authorization = util.getAuth({
  7893. SecretId: StsData.TmpSecretId,
  7894. SecretKey: StsData.TmpSecretKey,
  7895. Method: params.Method,
  7896. Pathname: Pathname,
  7897. Query: params.Query,
  7898. Headers: headers,
  7899. Expires: params.Expires,
  7900. SystemClockOffset: self.options.SystemClockOffset,
  7901. KeyTime: KeyTime
  7902. });
  7903. var AuthData = {
  7904. Authorization: Authorization,
  7905. XCosSecurityToken: StsData.XCosSecurityToken || '',
  7906. Token: StsData.Token || '',
  7907. ClientIP: StsData.ClientIP || '',
  7908. ClientUA: StsData.ClientUA || ''
  7909. };
  7910. cb(AuthData);
  7911. };
  7912. // 先判断是否有临时密钥
  7913. if (StsData.ExpiredTime && StsData.ExpiredTime - util.getSkewTime(self.options.SystemClockOffset) / 1000 > 60) {
  7914. // 如果缓存的临时密钥有效,并还有超过60秒有效期就直接使用
  7915. calcAuthByTmpKey();
  7916. } else if (self.options.getAuthorization) {
  7917. // 外部计算签名或获取临时密钥
  7918. self.options.getAuthorization.call(self, {
  7919. Bucket: Bucket,
  7920. Region: Region,
  7921. Method: params.Method,
  7922. Key: KeyName,
  7923. Pathname: Pathname,
  7924. Query: params.Query,
  7925. Headers: headers,
  7926. Scope: Scope,
  7927. SystemClockOffset: self.options.SystemClockOffset
  7928. }, function (AuthData) {
  7929. if (typeof AuthData === 'string') {
  7930. AuthData = { Authorization: AuthData };
  7931. }
  7932. if (AuthData.TmpSecretId && AuthData.TmpSecretKey && AuthData.XCosSecurityToken && AuthData.ExpiredTime) {
  7933. StsData = AuthData || {};
  7934. StsData.Scope = Scope;
  7935. StsData.ScopeKey = ScopeKey;
  7936. self._StsCache.push(StsData);
  7937. calcAuthByTmpKey();
  7938. } else {
  7939. cb(AuthData);
  7940. }
  7941. });
  7942. } else if (self.options.getSTS) {
  7943. // 外部获取临时密钥
  7944. self.options.getSTS.call(self, {
  7945. Bucket: Bucket,
  7946. Region: Region
  7947. }, function (data) {
  7948. StsData = data || {};
  7949. StsData.Scope = Scope;
  7950. StsData.ScopeKey = ScopeKey;
  7951. StsData.TmpSecretId = StsData.SecretId;
  7952. StsData.TmpSecretKey = StsData.SecretKey;
  7953. self._StsCache.push(StsData);
  7954. calcAuthByTmpKey();
  7955. });
  7956. } else {
  7957. // 内部计算获取签名
  7958. return function () {
  7959. var Authorization = util.getAuth({
  7960. SecretId: params.SecretId || self.options.SecretId,
  7961. SecretKey: params.SecretKey || self.options.SecretKey,
  7962. Method: params.Method,
  7963. Pathname: Pathname,
  7964. Query: params.Query,
  7965. Headers: headers,
  7966. Expires: params.Expires,
  7967. SystemClockOffset: self.options.SystemClockOffset
  7968. });
  7969. var AuthData = {
  7970. Authorization: Authorization,
  7971. XCosSecurityToken: self.options.XCosSecurityToken
  7972. };
  7973. cb(AuthData);
  7974. return AuthData;
  7975. }();
  7976. }
  7977. return '';
  7978. }
  7979. // 调整时间偏差
  7980. function allowRetry(err) {
  7981. var allowRetry = false;
  7982. var isTimeError = false;
  7983. var serverDate = err.headers && (err.headers.date || err.headers.Date) || err.error && err.error.ServerTime;
  7984. try {
  7985. var errorCode = err.error.Code;
  7986. var errorMessage = err.error.Message;
  7987. if (errorCode === 'RequestTimeTooSkewed' || errorCode === 'AccessDenied' && errorMessage === 'Request has expired') {
  7988. isTimeError = true;
  7989. }
  7990. } catch (e) {}
  7991. if (err) {
  7992. if (isTimeError && serverDate) {
  7993. var serverTime = Date.parse(serverDate);
  7994. if (this.options.CorrectClockSkew && Math.abs(util.getSkewTime(this.options.SystemClockOffset) - serverTime) >= 30000) {
  7995. console.error('error: Local time is too skewed.');
  7996. this.options.SystemClockOffset = serverTime - Date.now();
  7997. allowRetry = true;
  7998. }
  7999. } else if (Math.floor(err.statusCode / 100) === 5) {
  8000. allowRetry = true;
  8001. }
  8002. }
  8003. return allowRetry;
  8004. }
  8005. // 获取签名并发起请求
  8006. function submitRequest(params, callback) {
  8007. var self = this;
  8008. // 处理 headers
  8009. !params.headers && (params.headers = {});
  8010. // 处理 query
  8011. !params.qs && (params.qs = {});
  8012. params.VersionId && (params.qs.versionId = params.VersionId);
  8013. params.qs = util.clearKey(params.qs);
  8014. // 清理 undefined 和 null 字段
  8015. params.headers && (params.headers = util.clearKey(params.headers));
  8016. params.qs && (params.qs = util.clearKey(params.qs));
  8017. var Query = util.clone(params.qs);
  8018. params.action && (Query[params.action] = '');
  8019. var paramsUrl = params.url || params.Url;
  8020. var SignHost = params.SignHost || getSignHost.call(this, { Bucket: params.Bucket, Region: params.Region, Url: paramsUrl });
  8021. var next = function next(tryTimes) {
  8022. var oldClockOffset = self.options.SystemClockOffset;
  8023. getAuthorizationAsync.call(self, {
  8024. Bucket: params.Bucket || '',
  8025. Region: params.Region || '',
  8026. Method: params.method,
  8027. Key: params.Key,
  8028. Query: Query,
  8029. Headers: params.headers,
  8030. SignHost: SignHost,
  8031. Action: params.Action,
  8032. ResourceKey: params.ResourceKey,
  8033. Scope: params.Scope
  8034. }, function (err, AuthData) {
  8035. if (err) {
  8036. callback(err);
  8037. return;
  8038. }
  8039. params.AuthData = AuthData;
  8040. _submitRequest.call(self, params, function (err, data) {
  8041. if (err && tryTimes < 2 && (oldClockOffset !== self.options.SystemClockOffset || allowRetry.call(self, err))) {
  8042. if (params.headers) {
  8043. delete params.headers.Authorization;
  8044. delete params.headers['token'];
  8045. delete params.headers['clientIP'];
  8046. delete params.headers['clientUA'];
  8047. delete params.headers['x-cos-security-token'];
  8048. }
  8049. next(tryTimes + 1);
  8050. } else {
  8051. callback(err, data);
  8052. }
  8053. });
  8054. });
  8055. };
  8056. next(1);
  8057. }
  8058. // 发起请求
  8059. function _submitRequest(params, callback) {
  8060. var self = this;
  8061. var TaskId = params.TaskId;
  8062. if (TaskId && !self._isRunningTask(TaskId)) return;
  8063. var bucket = params.Bucket;
  8064. var region = params.Region;
  8065. var object = params.Key;
  8066. var method = params.method || 'GET';
  8067. var url = params.url || params.Url;
  8068. var body = params.body;
  8069. var json = params.json;
  8070. var rawBody = params.rawBody;
  8071. // url
  8072. if (self.options.UseAccelerate) {
  8073. region = 'accelerate';
  8074. }
  8075. url = url || getUrl({
  8076. ForcePathStyle: self.options.ForcePathStyle,
  8077. protocol: self.options.Protocol,
  8078. domain: self.options.Domain,
  8079. bucket: bucket,
  8080. region: region,
  8081. object: object
  8082. });
  8083. if (params.action) {
  8084. url = url + '?' + params.action;
  8085. }
  8086. if (params.qsStr) {
  8087. if (url.indexOf('?') > -1) {
  8088. url = url + '&' + params.qsStr;
  8089. } else {
  8090. url = url + '?' + params.qsStr;
  8091. }
  8092. }
  8093. var opt = {
  8094. method: method,
  8095. url: url,
  8096. headers: params.headers,
  8097. qs: params.qs,
  8098. filePath: params.filePath,
  8099. body: body,
  8100. json: json
  8101. };
  8102. // 兼容ci接口
  8103. var token = 'x-cos-security-token';
  8104. if (util.isCIHost(url)) {
  8105. token = 'x-ci-security-token';
  8106. }
  8107. // 获取签名
  8108. opt.headers.Authorization = params.AuthData.Authorization;
  8109. params.AuthData.Token && (opt.headers['token'] = params.AuthData.Token);
  8110. params.AuthData.ClientIP && (opt.headers['clientIP'] = params.AuthData.ClientIP);
  8111. params.AuthData.ClientUA && (opt.headers['clientUA'] = params.AuthData.ClientUA);
  8112. params.AuthData.XCosSecurityToken && (opt.headers[token] = params.AuthData.XCosSecurityToken);
  8113. // 清理 undefined 和 null 字段
  8114. opt.headers && (opt.headers = util.clearKey(opt.headers));
  8115. opt = util.clearKey(opt);
  8116. // progress
  8117. if (params.onProgress && typeof params.onProgress === 'function') {
  8118. opt.onProgress = function (e) {
  8119. if (TaskId && !self._isRunningTask(TaskId)) return;
  8120. var loaded = e ? e.loaded : 0;
  8121. params.onProgress({ loaded: loaded, total: e.total });
  8122. };
  8123. }
  8124. if (this.options.Timeout) {
  8125. opt.timeout = this.options.Timeout;
  8126. }
  8127. self.options.ForcePathStyle && (opt.pathStyle = self.options.ForcePathStyle);
  8128. self.emit('before-send', opt);
  8129. var sender = REQUEST(opt, function (err, response, body) {
  8130. if (err === 'abort') return;
  8131. // 返回内容添加 状态码 和 headers
  8132. var hasReturned;
  8133. var cb = function cb(err, data) {
  8134. TaskId && self.off('inner-kill-task', killTask);
  8135. if (hasReturned) return;
  8136. hasReturned = true;
  8137. var attrs = {};
  8138. response && response.statusCode && (attrs.statusCode = response.statusCode);
  8139. response && response.headers && (attrs.headers = response.headers);
  8140. if (err) {
  8141. err = util.extend(err || {}, attrs);
  8142. callback(err, null);
  8143. } else {
  8144. data = util.extend(data || {}, attrs);
  8145. callback(null, data);
  8146. }
  8147. sender = null;
  8148. };
  8149. // 请求错误,发生网络错误
  8150. if (err) {
  8151. cb({ error: err });
  8152. return;
  8153. }
  8154. // 不对 body 进行转换,body 直接挂载返回
  8155. var jsonRes;
  8156. if (rawBody) {
  8157. jsonRes = {};
  8158. jsonRes.body = body;
  8159. } else {
  8160. try {
  8161. jsonRes = body && body.indexOf('<') > -1 && body.indexOf('>') > -1 && util.xml2json(body) || {};
  8162. } catch (e) {
  8163. jsonRes = body || {};
  8164. }
  8165. }
  8166. // 请求返回码不为 200
  8167. var statusCode = response.statusCode;
  8168. var statusSuccess = Math.floor(statusCode / 100) === 2; // 200 202 204 206
  8169. if (!statusSuccess) {
  8170. cb({ error: jsonRes.Error || jsonRes });
  8171. return;
  8172. }
  8173. if (jsonRes.Error) {
  8174. cb({ error: jsonRes.Error });
  8175. return;
  8176. }
  8177. cb(null, jsonRes);
  8178. });
  8179. // kill task
  8180. var killTask = function killTask(data) {
  8181. if (data.TaskId === TaskId) {
  8182. sender && sender.abort && sender.abort();
  8183. self.off('inner-kill-task', killTask);
  8184. }
  8185. };
  8186. TaskId && self.on('inner-kill-task', killTask);
  8187. }
  8188. var API_MAP = {
  8189. // Bucket 相关方法
  8190. getService: getService, // Bucket
  8191. putBucket: putBucket,
  8192. headBucket: headBucket, // Bucket
  8193. getBucket: getBucket,
  8194. deleteBucket: deleteBucket,
  8195. putBucketAcl: putBucketAcl, // BucketACL
  8196. getBucketAcl: getBucketAcl,
  8197. putBucketCors: putBucketCors, // BucketCors
  8198. getBucketCors: getBucketCors,
  8199. deleteBucketCors: deleteBucketCors,
  8200. getBucketLocation: getBucketLocation, // BucketLocation
  8201. getBucketPolicy: getBucketPolicy, // BucketPolicy
  8202. putBucketPolicy: putBucketPolicy,
  8203. deleteBucketPolicy: deleteBucketPolicy,
  8204. putBucketTagging: putBucketTagging, // BucketTagging
  8205. getBucketTagging: getBucketTagging,
  8206. deleteBucketTagging: deleteBucketTagging,
  8207. putBucketLifecycle: putBucketLifecycle, // BucketLifecycle
  8208. getBucketLifecycle: getBucketLifecycle,
  8209. deleteBucketLifecycle: deleteBucketLifecycle,
  8210. putBucketVersioning: putBucketVersioning, // BucketVersioning
  8211. getBucketVersioning: getBucketVersioning,
  8212. putBucketReplication: putBucketReplication, // BucketReplication
  8213. getBucketReplication: getBucketReplication,
  8214. deleteBucketReplication: deleteBucketReplication,
  8215. putBucketWebsite: putBucketWebsite, // BucketWebsite
  8216. getBucketWebsite: getBucketWebsite,
  8217. deleteBucketWebsite: deleteBucketWebsite,
  8218. putBucketReferer: putBucketReferer, // BucketReferer
  8219. getBucketReferer: getBucketReferer,
  8220. putBucketDomain: putBucketDomain, // BucketDomain
  8221. getBucketDomain: getBucketDomain,
  8222. deleteBucketDomain: deleteBucketDomain,
  8223. putBucketOrigin: putBucketOrigin, // BucketOrigin
  8224. getBucketOrigin: getBucketOrigin,
  8225. deleteBucketOrigin: deleteBucketOrigin,
  8226. putBucketLogging: putBucketLogging, // BucketLogging
  8227. getBucketLogging: getBucketLogging,
  8228. putBucketInventory: putBucketInventory, // BucketInventory
  8229. getBucketInventory: getBucketInventory,
  8230. listBucketInventory: listBucketInventory,
  8231. deleteBucketInventory: deleteBucketInventory,
  8232. putBucketAccelerate: putBucketAccelerate,
  8233. getBucketAccelerate: getBucketAccelerate,
  8234. // Object 相关方法
  8235. getObject: getObject,
  8236. headObject: headObject,
  8237. listObjectVersions: listObjectVersions,
  8238. putObject: putObject,
  8239. postObject: postObject,
  8240. deleteObject: deleteObject,
  8241. getObjectAcl: getObjectAcl,
  8242. putObjectAcl: putObjectAcl,
  8243. optionsObject: optionsObject,
  8244. putObjectCopy: putObjectCopy,
  8245. deleteMultipleObject: deleteMultipleObject,
  8246. restoreObject: restoreObject,
  8247. putObjectTagging: putObjectTagging,
  8248. getObjectTagging: getObjectTagging,
  8249. deleteObjectTagging: deleteObjectTagging,
  8250. appendObject: appendObject,
  8251. // 分块上传相关方法
  8252. uploadPartCopy: uploadPartCopy,
  8253. multipartInit: multipartInit,
  8254. multipartUpload: multipartUpload,
  8255. multipartComplete: multipartComplete,
  8256. multipartList: multipartList,
  8257. multipartListPart: multipartListPart,
  8258. multipartAbort: multipartAbort,
  8259. // 工具方法
  8260. request: request,
  8261. getObjectUrl: getObjectUrl,
  8262. getAuth: getAuth
  8263. };
  8264. module.exports.init = function (COS, task) {
  8265. task.transferToTaskMethod(API_MAP, 'postObject');
  8266. task.transferToTaskMethod(API_MAP, 'putObject');
  8267. util.each(API_MAP, function (fn, apiName) {
  8268. COS.prototype[apiName] = util.apiWrapper(apiName, fn);
  8269. });
  8270. };
  8271. /***/ }),
  8272. /* 19 */
  8273. /***/ (function(module, exports, __webpack_require__) {
  8274. "use strict";
  8275. function camSafeUrlEncode(str) {
  8276. return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
  8277. }
  8278. function getObjectKeys(obj, forKey) {
  8279. var list = [];
  8280. for (var key in obj) {
  8281. if (obj.hasOwnProperty(key)) {
  8282. list.push(forKey ? camSafeUrlEncode(key).toLowerCase() : key);
  8283. }
  8284. }
  8285. return list.sort(function (a, b) {
  8286. a = a.toLowerCase();
  8287. b = b.toLowerCase();
  8288. return a === b ? 0 : a > b ? 1 : -1;
  8289. });
  8290. };
  8291. var obj2str = function obj2str(obj, lowerCaseKey) {
  8292. var i, key, val;
  8293. var list = [];
  8294. var keyList = getObjectKeys(obj);
  8295. for (i = 0; i < keyList.length; i++) {
  8296. key = keyList[i];
  8297. val = obj[key] === undefined || obj[key] === null ? '' : '' + obj[key];
  8298. key = lowerCaseKey ? camSafeUrlEncode(key).toLowerCase() : camSafeUrlEncode(key);
  8299. val = camSafeUrlEncode(val) || '';
  8300. list.push(key + '=' + val);
  8301. }
  8302. return list.join('&');
  8303. };
  8304. var request = function request(params, callback) {
  8305. var filePath = params.filePath;
  8306. var headers = params.headers || {};
  8307. var url = params.url || params.Url;
  8308. var method = params.method;
  8309. var onProgress = params.onProgress;
  8310. var requestTask;
  8311. var cb = function cb(err, response) {
  8312. var H = response.header;
  8313. var headers = {};
  8314. if (H) for (var key in H) {
  8315. if (H.hasOwnProperty(key)) headers[key.toLowerCase()] = H[key];
  8316. }
  8317. callback(err, { statusCode: response.statusCode, headers: headers }, response.data);
  8318. };
  8319. if (filePath) {
  8320. var fileKey;
  8321. var m = url.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/);
  8322. if (params.pathStyle) {
  8323. fileKey = decodeURIComponent(m[3] || '');
  8324. url = m[1] + m[2];
  8325. } else {
  8326. fileKey = decodeURIComponent(m[2] + m[3] || '');
  8327. url = m[1];
  8328. }
  8329. // 整理 postObject 参数
  8330. var formData = {
  8331. 'key': fileKey,
  8332. 'success_action_status': 200,
  8333. 'Signature': headers.Authorization
  8334. };
  8335. var headerKeys = ['Cache-Control', 'Content-Type', 'Content-Disposition', 'Content-Encoding', 'Expires', 'x-cos-storage-class', 'x-cos-security-token', 'x-ci-security-token'];
  8336. for (var i in params.headers) {
  8337. if (params.headers.hasOwnProperty(i) && (i.indexOf('x-cos-meta-') > -1 || headerKeys.indexOf(i) > -1)) {
  8338. formData[i] = params.headers[i];
  8339. }
  8340. }
  8341. headers['x-cos-acl'] && (formData.acl = headers['x-cos-acl']);
  8342. !formData['Content-Type'] && (formData['Content-Type'] = '');
  8343. requestTask = wx.uploadFile({
  8344. url: url,
  8345. method: method,
  8346. name: 'file',
  8347. header: headers,
  8348. filePath: filePath,
  8349. formData: formData,
  8350. timeout: params.timeout,
  8351. success: function success(response) {
  8352. cb(null, response);
  8353. },
  8354. fail: function fail(response) {
  8355. cb(response.errMsg, response);
  8356. }
  8357. });
  8358. requestTask.onProgressUpdate(function (res) {
  8359. onProgress && onProgress({
  8360. loaded: res.totalBytesSent,
  8361. total: res.totalBytesExpectedToSend,
  8362. progress: res.progress / 100
  8363. });
  8364. });
  8365. } else {
  8366. var qsStr = params.qs && obj2str(params.qs) || '';
  8367. if (qsStr) {
  8368. url += (url.indexOf('?') > -1 ? '&' : '?') + qsStr;
  8369. }
  8370. headers['Content-Length'] && delete headers['Content-Length'];
  8371. requestTask = wx.request({
  8372. url: url,
  8373. method: method,
  8374. header: headers,
  8375. dataType: 'text',
  8376. data: params.body,
  8377. timeout: params.timeout,
  8378. success: function success(response) {
  8379. cb(null, response);
  8380. },
  8381. fail: function fail(response) {
  8382. cb(response.errMsg, response);
  8383. }
  8384. });
  8385. }
  8386. return requestTask;
  8387. };
  8388. module.exports = request;
  8389. /***/ }),
  8390. /* 20 */
  8391. /***/ (function(module, exports, __webpack_require__) {
  8392. "use strict";
  8393. var Mime = __webpack_require__(21);
  8394. module.exports = new Mime(__webpack_require__(22), __webpack_require__(23));
  8395. /***/ }),
  8396. /* 21 */
  8397. /***/ (function(module, exports, __webpack_require__) {
  8398. "use strict";
  8399. /**
  8400. * @param typeMap [Object] Map of MIME type -> Array[extensions]
  8401. * @param ...
  8402. */
  8403. function Mime() {
  8404. this._types = Object.create(null);
  8405. this._extensions = Object.create(null);
  8406. for (var i = 0; i < arguments.length; i++) {
  8407. this.define(arguments[i]);
  8408. }
  8409. this.define = this.define.bind(this);
  8410. this.getType = this.getType.bind(this);
  8411. this.getExtension = this.getExtension.bind(this);
  8412. }
  8413. /**
  8414. * Define mimetype -> extension mappings. Each key is a mime-type that maps
  8415. * to an array of extensions associated with the type. The first extension is
  8416. * used as the default extension for the type.
  8417. *
  8418. * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});
  8419. *
  8420. * If a type declares an extension that has already been defined, an error will
  8421. * be thrown. To suppress this error and force the extension to be associated
  8422. * with the new type, pass `force`=true. Alternatively, you may prefix the
  8423. * extension with "*" to map the type to extension, without mapping the
  8424. * extension to the type.
  8425. *
  8426. * e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']});
  8427. *
  8428. *
  8429. * @param map (Object) type definitions
  8430. * @param force (Boolean) if true, force overriding of existing definitions
  8431. */
  8432. Mime.prototype.define = function (typeMap, force) {
  8433. for (var type in typeMap) {
  8434. var extensions = typeMap[type].map(function (t) {
  8435. return t.toLowerCase();
  8436. });
  8437. type = type.toLowerCase();
  8438. for (var i = 0; i < extensions.length; i++) {
  8439. var ext = extensions[i];
  8440. // '*' prefix = not the preferred type for this extension. So fixup the
  8441. // extension, and skip it.
  8442. if (ext[0] === '*') {
  8443. continue;
  8444. }
  8445. if (!force && ext in this._types) {
  8446. 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 + '".');
  8447. }
  8448. this._types[ext] = type;
  8449. }
  8450. // Use first extension as default
  8451. if (force || !this._extensions[type]) {
  8452. var _ext = extensions[0];
  8453. this._extensions[type] = _ext[0] !== '*' ? _ext : _ext.substr(1);
  8454. }
  8455. }
  8456. };
  8457. /**
  8458. * Lookup a mime type based on extension
  8459. */
  8460. Mime.prototype.getType = function (path) {
  8461. path = String(path);
  8462. var last = path.replace(/^.*[/\\]/, '').toLowerCase();
  8463. var ext = last.replace(/^.*\./, '').toLowerCase();
  8464. var hasPath = last.length < path.length;
  8465. var hasDot = ext.length < last.length - 1;
  8466. return (hasDot || !hasPath) && this._types[ext] || null;
  8467. };
  8468. /**
  8469. * Return file extension associated with a mime type
  8470. */
  8471. Mime.prototype.getExtension = function (type) {
  8472. type = /^\s*([^;\s]*)/.test(type) && RegExp.$1;
  8473. return type && this._extensions[type.toLowerCase()] || null;
  8474. };
  8475. module.exports = Mime;
  8476. /***/ }),
  8477. /* 22 */
  8478. /***/ (function(module, exports, __webpack_require__) {
  8479. "use strict";
  8480. 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"] };
  8481. /***/ }),
  8482. /* 23 */
  8483. /***/ (function(module, exports, __webpack_require__) {
  8484. "use strict";
  8485. 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"] };
  8486. /***/ }),
  8487. /* 24 */
  8488. /***/ (function(module, exports, __webpack_require__) {
  8489. "use strict";
  8490. 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; };
  8491. var session = __webpack_require__(5);
  8492. var Async = __webpack_require__(25);
  8493. var EventProxy = __webpack_require__(4).EventProxy;
  8494. var util = __webpack_require__(0);
  8495. // 文件分块上传全过程,暴露的分块上传接口
  8496. function sliceUploadFile(params, callback) {
  8497. var self = this;
  8498. // 如果小程序版本不支持获取文件分片内容,统一转到 postObject 接口上传
  8499. if (!util.canFileSlice()) {
  8500. params.SkipTask = true;
  8501. self.postObject(params, callback);
  8502. return;
  8503. }
  8504. var ep = new EventProxy();
  8505. var TaskId = params.TaskId;
  8506. var Bucket = params.Bucket;
  8507. var Region = params.Region;
  8508. var Key = params.Key;
  8509. var FilePath = params.FilePath;
  8510. var ChunkSize = params.ChunkSize || params.SliceSize || self.options.ChunkSize;
  8511. var AsyncLimit = params.AsyncLimit;
  8512. var StorageClass = params.StorageClass;
  8513. var ServerSideEncryption = params.ServerSideEncryption;
  8514. var FileSize;
  8515. var onProgress;
  8516. var onHashProgress = params.onHashProgress;
  8517. // 上传过程中出现错误,返回错误
  8518. ep.on('error', function (err) {
  8519. if (!self._isRunningTask(TaskId)) return;
  8520. var _err = {
  8521. UploadId: params.UploadData.UploadId || '',
  8522. err: err
  8523. };
  8524. return callback(_err);
  8525. });
  8526. // 上传分块完成,开始 uploadSliceComplete 操作
  8527. ep.on('upload_complete', function (UploadCompleteData) {
  8528. var _UploadCompleteData = util.extend({
  8529. UploadId: params.UploadData.UploadId || ''
  8530. }, UploadCompleteData);
  8531. callback(null, _UploadCompleteData);
  8532. });
  8533. // 上传分块完成,开始 uploadSliceComplete 操作
  8534. ep.on('upload_slice_complete', function (UploadData) {
  8535. uploadSliceComplete.call(self, {
  8536. Bucket: Bucket,
  8537. Region: Region,
  8538. Key: Key,
  8539. UploadId: UploadData.UploadId,
  8540. SliceList: UploadData.SliceList
  8541. }, function (err, data) {
  8542. if (!self._isRunningTask(TaskId)) return;
  8543. session.removeUsing(UploadData.UploadId);
  8544. if (err) {
  8545. onProgress(null, true);
  8546. return ep.emit('error', err);
  8547. }
  8548. session.removeUploadId(UploadData.UploadId);
  8549. onProgress({ loaded: FileSize, total: FileSize }, true);
  8550. ep.emit('upload_complete', data);
  8551. });
  8552. });
  8553. // 获取 UploadId 完成,开始上传每个分片
  8554. ep.on('get_upload_data_finish', function (UploadData) {
  8555. // 处理 UploadId 缓存
  8556. var uuid = session.getFileId(params.FileStat, params.ChunkSize, Bucket, Key);
  8557. uuid && session.saveUploadId(uuid, UploadData.UploadId, self.options.UploadIdCacheLimit); // 缓存 UploadId
  8558. session.setUsing(UploadData.UploadId); // 标记 UploadId 为正在使用
  8559. // 获取 UploadId
  8560. onProgress(null, true); // 任务状态开始 uploading
  8561. uploadSliceList.call(self, {
  8562. TaskId: TaskId,
  8563. Bucket: Bucket,
  8564. Region: Region,
  8565. Key: Key,
  8566. FilePath: FilePath,
  8567. FileSize: FileSize,
  8568. SliceSize: ChunkSize,
  8569. AsyncLimit: AsyncLimit,
  8570. ServerSideEncryption: ServerSideEncryption,
  8571. UploadData: UploadData,
  8572. onProgress: onProgress
  8573. }, function (err, data) {
  8574. if (!self._isRunningTask(TaskId)) return;
  8575. if (err) {
  8576. onProgress(null, true);
  8577. return ep.emit('error', err);
  8578. }
  8579. ep.emit('upload_slice_complete', data);
  8580. });
  8581. });
  8582. // 开始获取文件 UploadId,里面会视情况计算 ETag,并比对,保证文件一致性,也优化上传
  8583. ep.on('get_file_size_finish', function () {
  8584. onProgress = util.throttleOnProgress.call(self, FileSize, params.onProgress);
  8585. if (params.UploadData.UploadId) {
  8586. ep.emit('get_upload_data_finish', params.UploadData);
  8587. } else {
  8588. var _params = util.extend({
  8589. TaskId: TaskId,
  8590. Bucket: Bucket,
  8591. Region: Region,
  8592. Key: Key,
  8593. Headers: params.Headers,
  8594. StorageClass: StorageClass,
  8595. FilePath: FilePath,
  8596. FileSize: FileSize,
  8597. SliceSize: ChunkSize,
  8598. onHashProgress: onHashProgress
  8599. }, params);
  8600. getUploadIdAndPartList.call(self, _params, function (err, UploadData) {
  8601. if (!self._isRunningTask(TaskId)) return;
  8602. if (err) return ep.emit('error', err);
  8603. params.UploadData.UploadId = UploadData.UploadId;
  8604. params.UploadData.PartList = UploadData.PartList;
  8605. ep.emit('get_upload_data_finish', params.UploadData);
  8606. });
  8607. }
  8608. });
  8609. // 获取上传文件大小
  8610. FileSize = params.ContentLength;
  8611. delete params.ContentLength;
  8612. !params.Headers && (params.Headers = {});
  8613. util.each(params.Headers, function (item, key) {
  8614. if (key.toLowerCase() === 'content-length') {
  8615. delete params.Headers[key];
  8616. }
  8617. });
  8618. // 控制分片大小
  8619. (function () {
  8620. var SIZE = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 1024 * 2, 1024 * 4, 1024 * 5];
  8621. var AutoChunkSize = 1024 * 1024;
  8622. for (var i = 0; i < SIZE.length; i++) {
  8623. AutoChunkSize = SIZE[i] * 1024 * 1024;
  8624. if (FileSize / AutoChunkSize <= self.options.MaxPartNumber) break;
  8625. }
  8626. params.ChunkSize = params.SliceSize = ChunkSize = Math.max(ChunkSize, AutoChunkSize);
  8627. })();
  8628. // 开始上传
  8629. if (FileSize === 0) {
  8630. params.Body = '';
  8631. params.ContentLength = 0;
  8632. params.SkipTask = true;
  8633. self.putObject(params, function (err, data) {
  8634. if (err) {
  8635. return callback(err);
  8636. }
  8637. callback(null, data);
  8638. });
  8639. } else {
  8640. ep.emit('get_file_size_finish');
  8641. }
  8642. }
  8643. // 获取上传任务的 UploadId
  8644. function getUploadIdAndPartList(params, callback) {
  8645. var TaskId = params.TaskId;
  8646. var Bucket = params.Bucket;
  8647. var Region = params.Region;
  8648. var Key = params.Key;
  8649. var StorageClass = params.StorageClass;
  8650. var self = this;
  8651. // 计算 ETag
  8652. var ETagMap = {};
  8653. var FileSize = params.FileSize;
  8654. var SliceSize = params.SliceSize;
  8655. var SliceCount = Math.ceil(FileSize / SliceSize);
  8656. var FinishSliceCount = 0;
  8657. var FinishSize = 0;
  8658. var onHashProgress = util.throttleOnProgress.call(self, FileSize, params.onHashProgress);
  8659. var getChunkETag = function getChunkETag(PartNumber, callback) {
  8660. var start = SliceSize * (PartNumber - 1);
  8661. var end = Math.min(start + SliceSize, FileSize);
  8662. var ChunkSize = end - start;
  8663. if (ETagMap[PartNumber]) {
  8664. callback(null, {
  8665. PartNumber: PartNumber,
  8666. ETag: ETagMap[PartNumber],
  8667. Size: ChunkSize
  8668. });
  8669. } else {
  8670. util.fileSlice(params.FilePath, start, end, function (chunkItem) {
  8671. try {
  8672. var md5 = util.getFileMd5(chunkItem);
  8673. } catch (err) {
  8674. return callback(err);
  8675. }
  8676. var ETag = '"' + md5 + '"';
  8677. ETagMap[PartNumber] = ETag;
  8678. FinishSliceCount += 1;
  8679. FinishSize += ChunkSize;
  8680. callback(null, {
  8681. PartNumber: PartNumber,
  8682. ETag: ETag,
  8683. Size: ChunkSize
  8684. });
  8685. onHashProgress({ loaded: FinishSize, total: FileSize });
  8686. });
  8687. }
  8688. };
  8689. // 通过和文件的 md5 对比,判断 UploadId 是否可用
  8690. var isAvailableUploadList = function isAvailableUploadList(PartList, callback) {
  8691. var PartCount = PartList.length;
  8692. // 如果没有分片,通过
  8693. if (PartCount === 0) {
  8694. return callback(null, true);
  8695. }
  8696. // 检查分片数量
  8697. if (PartCount > SliceCount) {
  8698. return callback(null, false);
  8699. }
  8700. // 检查分片大小
  8701. if (PartCount > 1) {
  8702. var PartSliceSize = Math.max(PartList[0].Size, PartList[1].Size);
  8703. if (PartSliceSize !== SliceSize) {
  8704. return callback(null, false);
  8705. }
  8706. }
  8707. // 逐个分片计算并检查 ETag 是否一致
  8708. var next = function next(index) {
  8709. if (index < PartCount) {
  8710. var Part = PartList[index];
  8711. getChunkETag(Part.PartNumber, function (err, chunk) {
  8712. if (chunk && chunk.ETag === Part.ETag && chunk.Size === Part.Size) {
  8713. next(index + 1);
  8714. } else {
  8715. callback(null, false);
  8716. }
  8717. });
  8718. } else {
  8719. callback(null, true);
  8720. }
  8721. };
  8722. next(0);
  8723. };
  8724. var ep = new EventProxy();
  8725. ep.on('error', function (errData) {
  8726. if (!self._isRunningTask(TaskId)) return;
  8727. return callback(errData);
  8728. });
  8729. // 存在 UploadId
  8730. ep.on('upload_id_available', function (UploadData) {
  8731. // 转换成 map
  8732. var map = {};
  8733. var list = [];
  8734. util.each(UploadData.PartList, function (item) {
  8735. map[item.PartNumber] = item;
  8736. });
  8737. for (var PartNumber = 1; PartNumber <= SliceCount; PartNumber++) {
  8738. var item = map[PartNumber];
  8739. if (item) {
  8740. item.PartNumber = PartNumber;
  8741. item.Uploaded = true;
  8742. } else {
  8743. item = {
  8744. PartNumber: PartNumber,
  8745. ETag: null,
  8746. Uploaded: false
  8747. };
  8748. }
  8749. list.push(item);
  8750. }
  8751. UploadData.PartList = list;
  8752. callback(null, UploadData);
  8753. });
  8754. // 不存在 UploadId, 初始化生成 UploadId
  8755. ep.on('no_available_upload_id', function () {
  8756. if (!self._isRunningTask(TaskId)) return;
  8757. var _params = util.extend({
  8758. Bucket: Bucket,
  8759. Region: Region,
  8760. Key: Key,
  8761. Headers: util.clone(params.Headers),
  8762. Query: util.clone(params.Query),
  8763. StorageClass: StorageClass
  8764. }, params);
  8765. self.multipartInit(_params, function (err, data) {
  8766. if (!self._isRunningTask(TaskId)) return;
  8767. if (err) return ep.emit('error', err);
  8768. var UploadId = data.UploadId;
  8769. if (!UploadId) {
  8770. return callback({ Message: 'no upload id' });
  8771. }
  8772. ep.emit('upload_id_available', { UploadId: UploadId, PartList: [] });
  8773. });
  8774. });
  8775. // 如果已存在 UploadId,找一个可以用的 UploadId
  8776. ep.on('has_and_check_upload_id', function (UploadIdList) {
  8777. // 串行地,找一个内容一致的 UploadId
  8778. UploadIdList = UploadIdList.reverse();
  8779. Async.eachLimit(UploadIdList, 1, function (UploadId, asyncCallback) {
  8780. if (!self._isRunningTask(TaskId)) return;
  8781. // 如果正在上传,跳过
  8782. if (session.using[UploadId]) {
  8783. asyncCallback(); // 检查下一个 UploadId
  8784. return;
  8785. }
  8786. // 判断 UploadId 是否可用
  8787. wholeMultipartListPart.call(self, {
  8788. Bucket: Bucket,
  8789. Region: Region,
  8790. Key: Key,
  8791. UploadId: UploadId
  8792. }, function (err, PartListData) {
  8793. if (!self._isRunningTask(TaskId)) return;
  8794. if (err) {
  8795. session.removeUsing(UploadId);
  8796. return ep.emit('error', err);
  8797. }
  8798. var PartList = PartListData.PartList;
  8799. PartList.forEach(function (item) {
  8800. item.PartNumber *= 1;
  8801. item.Size *= 1;
  8802. item.ETag = item.ETag || '';
  8803. });
  8804. isAvailableUploadList(PartList, function (err, isAvailable) {
  8805. if (!self._isRunningTask(TaskId)) return;
  8806. if (err) return ep.emit('error', err);
  8807. if (isAvailable) {
  8808. asyncCallback({
  8809. UploadId: UploadId,
  8810. PartList: PartList
  8811. }); // 马上结束
  8812. } else {
  8813. asyncCallback(); // 检查下一个 UploadId
  8814. }
  8815. });
  8816. });
  8817. }, function (AvailableUploadData) {
  8818. if (!self._isRunningTask(TaskId)) return;
  8819. onHashProgress(null, true);
  8820. if (AvailableUploadData && AvailableUploadData.UploadId) {
  8821. ep.emit('upload_id_available', AvailableUploadData);
  8822. } else {
  8823. ep.emit('no_available_upload_id');
  8824. }
  8825. });
  8826. });
  8827. // 在本地缓存找可用的 UploadId
  8828. ep.on('seek_local_avail_upload_id', function (RemoteUploadIdList) {
  8829. // 在本地找可用的 UploadId
  8830. var uuid = session.getFileId(params.FileStat, params.ChunkSize, Bucket, Key);
  8831. var LocalUploadIdList = session.getUploadIdList(uuid);
  8832. if (!uuid || !LocalUploadIdList) {
  8833. ep.emit('has_and_check_upload_id', RemoteUploadIdList);
  8834. return;
  8835. }
  8836. var next = function next(index) {
  8837. // 如果本地找不到可用 UploadId,再一个个遍历校验远端
  8838. if (index >= LocalUploadIdList.length) {
  8839. ep.emit('has_and_check_upload_id', RemoteUploadIdList);
  8840. return;
  8841. }
  8842. var UploadId = LocalUploadIdList[index];
  8843. // 如果不在远端 UploadId 列表里,跳过并删除
  8844. if (!util.isInArray(RemoteUploadIdList, UploadId)) {
  8845. session.removeUploadId(UploadId);
  8846. next(index + 1);
  8847. return;
  8848. }
  8849. // 如果正在上传,跳过
  8850. if (session.using[UploadId]) {
  8851. next(index + 1);
  8852. return;
  8853. }
  8854. // 判断 UploadId 是否存在线上
  8855. wholeMultipartListPart.call(self, {
  8856. Bucket: Bucket,
  8857. Region: Region,
  8858. Key: Key,
  8859. UploadId: UploadId
  8860. }, function (err, PartListData) {
  8861. if (!self._isRunningTask(TaskId)) return;
  8862. if (err) {
  8863. // 如果 UploadId 获取会出错,跳过并删除
  8864. session.removeUploadId(UploadId);
  8865. next(index + 1);
  8866. } else {
  8867. // 找到可用 UploadId
  8868. ep.emit('upload_id_available', {
  8869. UploadId: UploadId,
  8870. PartList: PartListData.PartList
  8871. });
  8872. }
  8873. });
  8874. };
  8875. next(0);
  8876. });
  8877. // 获取线上 UploadId 列表
  8878. ep.on('get_remote_upload_id_list', function () {
  8879. // 获取符合条件的 UploadId 列表,因为同一个文件可以有多个上传任务。
  8880. wholeMultipartList.call(self, {
  8881. Bucket: Bucket,
  8882. Region: Region,
  8883. Key: Key
  8884. }, function (err, data) {
  8885. if (!self._isRunningTask(TaskId)) return;
  8886. if (err) {
  8887. return ep.emit('error', err);
  8888. }
  8889. // 整理远端 UploadId 列表
  8890. var RemoteUploadIdList = util.filter(data.UploadList, function (item) {
  8891. return item.Key === Key && (!StorageClass || item.StorageClass.toUpperCase() === StorageClass.toUpperCase());
  8892. }).reverse().map(function (item) {
  8893. return item.UploadId || item.UploadID;
  8894. });
  8895. if (RemoteUploadIdList.length) {
  8896. ep.emit('seek_local_avail_upload_id', RemoteUploadIdList);
  8897. } else {
  8898. // 远端没有 UploadId,清理缓存的 UploadId
  8899. var uuid = session.getFileId(params.FileStat, params.ChunkSize, Bucket, Key),
  8900. LocalUploadIdList;
  8901. if (uuid && (LocalUploadIdList = session.getUploadIdList(uuid))) {
  8902. util.each(LocalUploadIdList, function (UploadId) {
  8903. session.removeUploadId(UploadId);
  8904. });
  8905. }
  8906. ep.emit('no_available_upload_id');
  8907. }
  8908. });
  8909. });
  8910. // 开始找可用 UploadId
  8911. ep.emit('get_remote_upload_id_list');
  8912. }
  8913. // 获取符合条件的全部上传任务 (条件包括 Bucket, Region, Prefix)
  8914. function wholeMultipartList(params, callback) {
  8915. var self = this;
  8916. var UploadList = [];
  8917. var sendParams = {
  8918. Bucket: params.Bucket,
  8919. Region: params.Region,
  8920. Prefix: params.Key
  8921. };
  8922. var next = function next() {
  8923. self.multipartList(sendParams, function (err, data) {
  8924. if (err) return callback(err);
  8925. UploadList.push.apply(UploadList, data.Upload || []);
  8926. if (data.IsTruncated === 'true') {
  8927. // 列表不完整
  8928. sendParams.KeyMarker = data.NextKeyMarker;
  8929. sendParams.UploadIdMarker = data.NextUploadIdMarker;
  8930. next();
  8931. } else {
  8932. callback(null, { UploadList: UploadList });
  8933. }
  8934. });
  8935. };
  8936. next();
  8937. }
  8938. // 获取指定上传任务的分块列表
  8939. function wholeMultipartListPart(params, callback) {
  8940. var self = this;
  8941. var PartList = [];
  8942. var sendParams = {
  8943. Bucket: params.Bucket,
  8944. Region: params.Region,
  8945. Key: params.Key,
  8946. UploadId: params.UploadId
  8947. };
  8948. var next = function next() {
  8949. self.multipartListPart(sendParams, function (err, data) {
  8950. if (err) return callback(err);
  8951. PartList.push.apply(PartList, data.Part || []);
  8952. if (data.IsTruncated === 'true') {
  8953. // 列表不完整
  8954. sendParams.PartNumberMarker = data.NextPartNumberMarker;
  8955. next();
  8956. } else {
  8957. callback(null, { PartList: PartList });
  8958. }
  8959. });
  8960. };
  8961. next();
  8962. }
  8963. // 上传文件分块,包括
  8964. /*
  8965. UploadId (上传任务编号)
  8966. AsyncLimit (并发量),
  8967. SliceList (上传的分块数组),
  8968. FilePath (本地文件的位置),
  8969. SliceSize (文件分块大小)
  8970. FileSize (文件大小)
  8971. onProgress (上传成功之后的回调函数)
  8972. */
  8973. function uploadSliceList(params, cb) {
  8974. var self = this;
  8975. var TaskId = params.TaskId;
  8976. var Bucket = params.Bucket;
  8977. var Region = params.Region;
  8978. var Key = params.Key;
  8979. var UploadData = params.UploadData;
  8980. var FileSize = params.FileSize;
  8981. var SliceSize = params.SliceSize;
  8982. var ChunkParallel = Math.min(params.AsyncLimit || self.options.ChunkParallelLimit || 1, 256);
  8983. var FilePath = params.FilePath;
  8984. var SliceCount = Math.ceil(FileSize / SliceSize);
  8985. var FinishSize = 0;
  8986. var ServerSideEncryption = params.ServerSideEncryption;
  8987. var needUploadSlices = util.filter(UploadData.PartList, function (SliceItem) {
  8988. if (SliceItem['Uploaded']) {
  8989. FinishSize += SliceItem['PartNumber'] >= SliceCount ? FileSize % SliceSize || SliceSize : SliceSize;
  8990. }
  8991. return !SliceItem['Uploaded'];
  8992. });
  8993. var _onProgress2 = params.onProgress;
  8994. Async.eachLimit(needUploadSlices, ChunkParallel, function (SliceItem, asyncCallback) {
  8995. if (!self._isRunningTask(TaskId)) return;
  8996. var PartNumber = SliceItem['PartNumber'];
  8997. var currentSize = Math.min(FileSize, SliceItem['PartNumber'] * SliceSize) - (SliceItem['PartNumber'] - 1) * SliceSize;
  8998. var preAddSize = 0;
  8999. uploadSliceItem.call(self, {
  9000. TaskId: TaskId,
  9001. Bucket: Bucket,
  9002. Region: Region,
  9003. Key: Key,
  9004. SliceSize: SliceSize,
  9005. FileSize: FileSize,
  9006. PartNumber: PartNumber,
  9007. ServerSideEncryption: ServerSideEncryption,
  9008. FilePath: FilePath,
  9009. UploadData: UploadData,
  9010. onProgress: function onProgress(data) {
  9011. FinishSize += data.loaded - preAddSize;
  9012. preAddSize = data.loaded;
  9013. _onProgress2({ loaded: FinishSize, total: FileSize });
  9014. }
  9015. }, function (err, data) {
  9016. if (!self._isRunningTask(TaskId)) return;
  9017. if (err) {
  9018. FinishSize -= preAddSize;
  9019. } else {
  9020. FinishSize += currentSize - preAddSize;
  9021. SliceItem.ETag = data.ETag;
  9022. }
  9023. _onProgress2({ loaded: FinishSize, total: FileSize });
  9024. asyncCallback(err || null, data);
  9025. });
  9026. }, function (err) {
  9027. if (!self._isRunningTask(TaskId)) return;
  9028. if (err) return cb(err);
  9029. cb(null, {
  9030. UploadId: UploadData.UploadId,
  9031. SliceList: UploadData.PartList
  9032. });
  9033. });
  9034. }
  9035. // 上传指定分片
  9036. function uploadSliceItem(params, callback) {
  9037. var self = this;
  9038. var TaskId = params.TaskId;
  9039. var Bucket = params.Bucket;
  9040. var Region = params.Region;
  9041. var Key = params.Key;
  9042. var FileSize = params.FileSize;
  9043. var FilePath = params.FilePath;
  9044. var PartNumber = params.PartNumber * 1;
  9045. var SliceSize = params.SliceSize;
  9046. var ServerSideEncryption = params.ServerSideEncryption;
  9047. var UploadData = params.UploadData;
  9048. var ChunkRetryTimes = self.options.ChunkRetryTimes + 1;
  9049. var Headers = params.Headers || {};
  9050. var start = SliceSize * (PartNumber - 1);
  9051. var ContentLength = SliceSize;
  9052. var end = start + SliceSize;
  9053. if (end > FileSize) {
  9054. end = FileSize;
  9055. ContentLength = end - start;
  9056. }
  9057. var headersWhiteList = ['x-cos-traffic-limit', 'x-cos-mime-limit'];
  9058. var headers = {};
  9059. util.each(Headers, function (v, k) {
  9060. if (headersWhiteList.indexOf(k) > -1) {
  9061. headers[k] = v;
  9062. }
  9063. });
  9064. util.fileSlice(FilePath, start, end, function (Body) {
  9065. var md5 = util.getFileMd5(Body);
  9066. var contentMd5 = md5 ? util.binaryBase64(md5) : null;
  9067. var PartItem = UploadData.PartList[PartNumber - 1];
  9068. Async.retry(ChunkRetryTimes, function (tryCallback) {
  9069. if (!self._isRunningTask(TaskId)) return;
  9070. self.multipartUpload({
  9071. TaskId: TaskId,
  9072. Bucket: Bucket,
  9073. Region: Region,
  9074. Key: Key,
  9075. ContentLength: ContentLength,
  9076. PartNumber: PartNumber,
  9077. UploadId: UploadData.UploadId,
  9078. ServerSideEncryption: ServerSideEncryption,
  9079. Body: Body,
  9080. Headers: headers,
  9081. onProgress: params.onProgress,
  9082. ContentMD5: contentMd5
  9083. }, function (err, data) {
  9084. if (!self._isRunningTask(TaskId)) return;
  9085. if (err) {
  9086. return tryCallback(err);
  9087. } else {
  9088. PartItem.Uploaded = true;
  9089. return tryCallback(null, data);
  9090. }
  9091. });
  9092. }, function (err, data) {
  9093. if (!self._isRunningTask(TaskId)) return;
  9094. return callback(err, data);
  9095. });
  9096. });
  9097. }
  9098. // 完成分块上传
  9099. function uploadSliceComplete(params, callback) {
  9100. var Bucket = params.Bucket;
  9101. var Region = params.Region;
  9102. var Key = params.Key;
  9103. var UploadId = params.UploadId;
  9104. var SliceList = params.SliceList;
  9105. var self = this;
  9106. var ChunkRetryTimes = this.options.ChunkRetryTimes + 1;
  9107. var Parts = SliceList.map(function (item) {
  9108. return {
  9109. PartNumber: item.PartNumber,
  9110. ETag: item.ETag
  9111. };
  9112. });
  9113. // 完成上传的请求也做重试
  9114. Async.retry(ChunkRetryTimes, function (tryCallback) {
  9115. self.multipartComplete({
  9116. Bucket: Bucket,
  9117. Region: Region,
  9118. Key: Key,
  9119. UploadId: UploadId,
  9120. Parts: Parts
  9121. }, tryCallback);
  9122. }, function (err, data) {
  9123. callback(err, data);
  9124. });
  9125. }
  9126. // 抛弃分块上传任务
  9127. /*
  9128. AsyncLimit (抛弃上传任务的并发量),
  9129. UploadId (上传任务的编号,当 Level 为 task 时候需要)
  9130. Level (抛弃分块上传任务的级别,task : 抛弃指定的上传任务,file : 抛弃指定的文件对应的上传任务,其他值 :抛弃指定Bucket 的全部上传任务)
  9131. */
  9132. function abortUploadTask(params, callback) {
  9133. var Bucket = params.Bucket;
  9134. var Region = params.Region;
  9135. var Key = params.Key;
  9136. var UploadId = params.UploadId;
  9137. var Level = params.Level || 'task';
  9138. var AsyncLimit = params.AsyncLimit;
  9139. var self = this;
  9140. var ep = new EventProxy();
  9141. ep.on('error', function (errData) {
  9142. return callback(errData);
  9143. });
  9144. // 已经获取到需要抛弃的任务列表
  9145. ep.on('get_abort_array', function (AbortArray) {
  9146. abortUploadTaskArray.call(self, {
  9147. Bucket: Bucket,
  9148. Region: Region,
  9149. Key: Key,
  9150. Headers: params.Headers,
  9151. AsyncLimit: AsyncLimit,
  9152. AbortArray: AbortArray
  9153. }, function (err, data) {
  9154. if (err) {
  9155. return callback(err);
  9156. }
  9157. callback(null, data);
  9158. });
  9159. });
  9160. if (Level === 'bucket') {
  9161. // Bucket 级别的任务抛弃,抛弃该 Bucket 下的全部上传任务
  9162. wholeMultipartList.call(self, {
  9163. Bucket: Bucket,
  9164. Region: Region
  9165. }, function (err, data) {
  9166. if (err) {
  9167. return callback(err);
  9168. }
  9169. ep.emit('get_abort_array', data.UploadList || []);
  9170. });
  9171. } else if (Level === 'file') {
  9172. // 文件级别的任务抛弃,抛弃该文件的全部上传任务
  9173. if (!Key) return callback({ error: 'abort_upload_task_no_key' });
  9174. wholeMultipartList.call(self, {
  9175. Bucket: Bucket,
  9176. Region: Region,
  9177. Key: Key
  9178. }, function (err, data) {
  9179. if (err) {
  9180. return callback(err);
  9181. }
  9182. ep.emit('get_abort_array', data.UploadList || []);
  9183. });
  9184. } else if (Level === 'task') {
  9185. // 单个任务级别的任务抛弃,抛弃指定 UploadId 的上传任务
  9186. if (!UploadId) return callback({ error: 'abort_upload_task_no_id' });
  9187. if (!Key) return callback({ error: 'abort_upload_task_no_key' });
  9188. ep.emit('get_abort_array', [{
  9189. Key: Key,
  9190. UploadId: UploadId
  9191. }]);
  9192. } else {
  9193. return callback({ error: 'abort_unknown_level' });
  9194. }
  9195. }
  9196. // 批量抛弃分块上传任务
  9197. function abortUploadTaskArray(params, callback) {
  9198. var Bucket = params.Bucket;
  9199. var Region = params.Region;
  9200. var Key = params.Key;
  9201. var AbortArray = params.AbortArray;
  9202. var AsyncLimit = params.AsyncLimit || 1;
  9203. var self = this;
  9204. var index = 0;
  9205. var resultList = new Array(AbortArray.length);
  9206. Async.eachLimit(AbortArray, AsyncLimit, function (AbortItem, callback) {
  9207. var eachIndex = index;
  9208. if (Key && Key !== AbortItem.Key) {
  9209. resultList[eachIndex] = { error: { KeyNotMatch: true } };
  9210. callback(null);
  9211. return;
  9212. }
  9213. var UploadId = AbortItem.UploadId || AbortItem.UploadID;
  9214. self.multipartAbort({
  9215. Bucket: Bucket,
  9216. Region: Region,
  9217. Key: AbortItem.Key,
  9218. Headers: params.Headers,
  9219. UploadId: UploadId
  9220. }, function (err) {
  9221. var task = {
  9222. Bucket: Bucket,
  9223. Region: Region,
  9224. Key: AbortItem.Key,
  9225. UploadId: UploadId
  9226. };
  9227. resultList[eachIndex] = { error: err, task: task };
  9228. callback(null);
  9229. });
  9230. index++;
  9231. }, function (err) {
  9232. if (err) {
  9233. return callback(err);
  9234. }
  9235. var successList = [];
  9236. var errorList = [];
  9237. for (var i = 0, len = resultList.length; i < len; i++) {
  9238. var item = resultList[i];
  9239. if (item['task']) {
  9240. if (item['error']) {
  9241. errorList.push(item['task']);
  9242. } else {
  9243. successList.push(item['task']);
  9244. }
  9245. }
  9246. }
  9247. return callback(null, {
  9248. successList: successList,
  9249. errorList: errorList
  9250. });
  9251. });
  9252. }
  9253. // 高级上传
  9254. function uploadFile(params, callback) {
  9255. var self = this;
  9256. // 判断多大的文件使用分片上传
  9257. var SliceSize = params.SliceSize === undefined ? self.options.SliceSize : params.SliceSize;
  9258. var taskList = [];
  9259. var FileSize = params.FileSize;
  9260. var fileInfo = { TaskId: '' };
  9261. // 整理 option,用于返回给回调
  9262. util.each(params, function (v, k) {
  9263. if ((typeof v === 'undefined' ? 'undefined' : _typeof(v)) !== 'object' && typeof v !== 'function') {
  9264. fileInfo[k] = v;
  9265. }
  9266. });
  9267. // 处理文件 TaskReady
  9268. var _onTaskReady = params.onTaskReady;
  9269. params.onTaskReady = function (tid) {
  9270. fileInfo.TaskId = tid;
  9271. _onTaskReady && _onTaskReady(tid);
  9272. };
  9273. // 处理文件完成
  9274. var _onFileFinish = params.onFileFinish;
  9275. var onFileFinish = function onFileFinish(err, data) {
  9276. _onFileFinish && _onFileFinish(err, data, fileInfo);
  9277. callback && callback(err, data);
  9278. };
  9279. // 添加上传任务
  9280. var api = FileSize > SliceSize ? 'sliceUploadFile' : 'postObject';
  9281. taskList.push({
  9282. api: api,
  9283. params: params,
  9284. callback: onFileFinish
  9285. });
  9286. self._addTasks(taskList);
  9287. }
  9288. // 批量上传文件
  9289. function uploadFiles(params, callback) {
  9290. var self = this;
  9291. // 判断多大的文件使用分片上传
  9292. var SliceSize = params.SliceSize === undefined ? self.options.SliceSize : params.SliceSize;
  9293. // 汇总返回进度
  9294. var TotalSize = 0;
  9295. var TotalFinish = 0;
  9296. var onTotalProgress = util.throttleOnProgress.call(self, TotalFinish, params.onProgress);
  9297. // 汇总返回回调
  9298. var unFinishCount = params.files.length;
  9299. var _onTotalFileFinish = params.onFileFinish;
  9300. var resultList = Array(unFinishCount);
  9301. var onTotalFileFinish = function onTotalFileFinish(err, data, options) {
  9302. onTotalProgress(null, true);
  9303. _onTotalFileFinish && _onTotalFileFinish(err, data, options);
  9304. resultList[options.Index] = {
  9305. options: options,
  9306. error: err,
  9307. data: data
  9308. };
  9309. if (--unFinishCount <= 0 && callback) {
  9310. callback(null, {
  9311. files: resultList
  9312. });
  9313. }
  9314. };
  9315. // 开始处理每个文件
  9316. var taskList = [];
  9317. util.each(params.files, function (fileParams, index) {
  9318. var FileSize = fileParams.FileSize;
  9319. var fileInfo = { Index: index, TaskId: '' };
  9320. // 更新文件总大小
  9321. TotalSize += FileSize;
  9322. // 整理 option,用于返回给回调
  9323. util.each(fileParams, function (v, k) {
  9324. if ((typeof v === 'undefined' ? 'undefined' : _typeof(v)) !== 'object' && typeof v !== 'function') {
  9325. fileInfo[k] = v;
  9326. }
  9327. });
  9328. // 处理单个文件 TaskReady
  9329. var _onTaskReady = fileParams.onTaskReady;
  9330. fileParams.onTaskReady = function (tid) {
  9331. fileInfo.TaskId = tid;
  9332. _onTaskReady && _onTaskReady(tid);
  9333. };
  9334. // 处理单个文件进度
  9335. var PreAddSize = 0;
  9336. var _onProgress = fileParams.onProgress;
  9337. fileParams.onProgress = function (info) {
  9338. TotalFinish = TotalFinish - PreAddSize + info.loaded;
  9339. PreAddSize = info.loaded;
  9340. _onProgress && _onProgress(info);
  9341. onTotalProgress({ loaded: TotalFinish, total: TotalSize });
  9342. };
  9343. // 处理单个文件完成
  9344. var _onFileFinish = fileParams.onFileFinish;
  9345. var onFileFinish = function onFileFinish(err, data) {
  9346. _onFileFinish && _onFileFinish(err, data);
  9347. onTotalFileFinish && onTotalFileFinish(err, data, fileInfo);
  9348. };
  9349. // 添加上传任务
  9350. var api = FileSize > SliceSize ? 'sliceUploadFile' : 'postObject';
  9351. taskList.push({
  9352. api: api,
  9353. params: fileParams,
  9354. callback: onFileFinish
  9355. });
  9356. });
  9357. self._addTasks(taskList);
  9358. }
  9359. // 分片复制文件
  9360. function sliceCopyFile(params, callback) {
  9361. var ep = new EventProxy();
  9362. var self = this;
  9363. var Bucket = params.Bucket;
  9364. var Region = params.Region;
  9365. var Key = params.Key;
  9366. var CopySource = params.CopySource;
  9367. var m = CopySource.match(/^([^.]+-\d+)\.cos(v6)?\.([^.]+)\.[^/]+\/(.+)$/);
  9368. if (!m) {
  9369. callback({ error: 'CopySource format error' });
  9370. return;
  9371. }
  9372. var SourceBucket = m[1];
  9373. var SourceRegion = m[3];
  9374. var SourceKey = decodeURIComponent(m[4]);
  9375. var CopySliceSize = params.CopySliceSize === undefined ? self.options.CopySliceSize : params.CopySliceSize;
  9376. CopySliceSize = Math.max(0, CopySliceSize);
  9377. var ChunkSize = params.CopyChunkSize || this.options.CopyChunkSize;
  9378. var ChunkParallel = this.options.CopyChunkParallelLimit;
  9379. var FinishSize = 0;
  9380. var FileSize;
  9381. var _onProgress3;
  9382. // 分片复制完成,开始 multipartComplete 操作
  9383. ep.on('copy_slice_complete', function (UploadData) {
  9384. self.multipartComplete({
  9385. Bucket: Bucket,
  9386. Region: Region,
  9387. Key: Key,
  9388. UploadId: UploadData.UploadId,
  9389. Parts: UploadData.PartList
  9390. }, function (err, data) {
  9391. if (err) {
  9392. _onProgress3(null, true);
  9393. return callback(err);
  9394. }
  9395. _onProgress3({ loaded: FileSize, total: FileSize }, true);
  9396. callback(null, data);
  9397. });
  9398. });
  9399. ep.on('get_copy_data_finish', function (UploadData) {
  9400. Async.eachLimit(UploadData.PartList, ChunkParallel, function (SliceItem, asyncCallback) {
  9401. var PartNumber = SliceItem.PartNumber;
  9402. var CopySourceRange = SliceItem.CopySourceRange;
  9403. var currentSize = SliceItem.end - SliceItem.start;
  9404. var preAddSize = 0;
  9405. copySliceItem.call(self, {
  9406. Bucket: Bucket,
  9407. Region: Region,
  9408. Key: Key,
  9409. CopySource: CopySource,
  9410. UploadId: UploadData.UploadId,
  9411. PartNumber: PartNumber,
  9412. CopySourceRange: CopySourceRange,
  9413. onProgress: function onProgress(data) {
  9414. FinishSize += data.loaded - preAddSize;
  9415. preAddSize = data.loaded;
  9416. _onProgress3({ loaded: FinishSize, total: FileSize });
  9417. }
  9418. }, function (err, data) {
  9419. if (err) {
  9420. return asyncCallback(err);
  9421. }
  9422. _onProgress3({ loaded: FinishSize, total: FileSize });
  9423. FinishSize += currentSize - preAddSize;
  9424. SliceItem.ETag = data.ETag;
  9425. asyncCallback(err || null, data);
  9426. });
  9427. }, function (err) {
  9428. if (err) {
  9429. _onProgress3(null, true);
  9430. return callback(err);
  9431. }
  9432. ep.emit('copy_slice_complete', UploadData);
  9433. });
  9434. });
  9435. ep.on('get_file_size_finish', function (SourceHeaders) {
  9436. // 控制分片大小
  9437. (function () {
  9438. var SIZE = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 1024 * 2, 1024 * 4, 1024 * 5];
  9439. var AutoChunkSize = 1024 * 1024;
  9440. for (var i = 0; i < SIZE.length; i++) {
  9441. AutoChunkSize = SIZE[i] * 1024 * 1024;
  9442. if (FileSize / AutoChunkSize <= self.options.MaxPartNumber) break;
  9443. }
  9444. params.ChunkSize = ChunkSize = Math.max(ChunkSize, AutoChunkSize);
  9445. var ChunkCount = Math.ceil(FileSize / ChunkSize);
  9446. var list = [];
  9447. for (var partNumber = 1; partNumber <= ChunkCount; partNumber++) {
  9448. var start = (partNumber - 1) * ChunkSize;
  9449. var end = partNumber * ChunkSize < FileSize ? partNumber * ChunkSize - 1 : FileSize - 1;
  9450. var item = {
  9451. PartNumber: partNumber,
  9452. start: start,
  9453. end: end,
  9454. CopySourceRange: "bytes=" + start + "-" + end
  9455. };
  9456. list.push(item);
  9457. }
  9458. params.PartList = list;
  9459. })();
  9460. var TargetHeader;
  9461. if (params.Headers['x-cos-metadata-directive'] === 'Replaced') {
  9462. TargetHeader = params.Headers;
  9463. } else {
  9464. TargetHeader = SourceHeaders;
  9465. }
  9466. TargetHeader['x-cos-storage-class'] = params.Headers['x-cos-storage-class'] || SourceHeaders['x-cos-storage-class'];
  9467. TargetHeader = util.clearKey(TargetHeader);
  9468. /**
  9469. * 对于归档存储的对象,如果未恢复副本,则不允许 Copy
  9470. */
  9471. if (SourceHeaders['x-cos-storage-class'] === 'ARCHIVE' || SourceHeaders['x-cos-storage-class'] === 'DEEP_ARCHIVE') {
  9472. var restoreHeader = SourceHeaders['x-cos-restore'];
  9473. if (!restoreHeader || restoreHeader === 'ongoing-request="true"') {
  9474. callback({ error: 'Unrestored archive object is not allowed to be copied' });
  9475. return;
  9476. }
  9477. }
  9478. /**
  9479. * 去除一些无用的头部,规避 multipartInit 出错
  9480. * 这些头部通常是在 putObjectCopy 时才使用
  9481. */
  9482. delete TargetHeader['x-cos-copy-source'];
  9483. delete TargetHeader['x-cos-metadata-directive'];
  9484. delete TargetHeader['x-cos-copy-source-If-Modified-Since'];
  9485. delete TargetHeader['x-cos-copy-source-If-Unmodified-Since'];
  9486. delete TargetHeader['x-cos-copy-source-If-Match'];
  9487. delete TargetHeader['x-cos-copy-source-If-None-Match'];
  9488. self.multipartInit({
  9489. Bucket: Bucket,
  9490. Region: Region,
  9491. Key: Key,
  9492. Headers: TargetHeader
  9493. }, function (err, data) {
  9494. if (err) {
  9495. return callback(err);
  9496. }
  9497. params.UploadId = data.UploadId;
  9498. ep.emit('get_copy_data_finish', params);
  9499. });
  9500. });
  9501. // 获取远端复制源文件的大小
  9502. self.headObject({
  9503. Bucket: SourceBucket,
  9504. Region: SourceRegion,
  9505. Key: SourceKey
  9506. }, function (err, data) {
  9507. if (err) {
  9508. if (err.statusCode && err.statusCode === 404) {
  9509. callback({ ErrorStatus: SourceKey + ' Not Exist' });
  9510. } else {
  9511. callback(err);
  9512. }
  9513. return;
  9514. }
  9515. FileSize = params.FileSize = data.headers['content-length'];
  9516. if (FileSize === undefined || !FileSize) {
  9517. callback({ error: 'get Content-Length error, please add "Content-Length" to CORS ExposeHeader setting.' });
  9518. return;
  9519. }
  9520. _onProgress3 = util.throttleOnProgress.call(self, FileSize, params.onProgress);
  9521. // 开始上传
  9522. if (FileSize <= CopySliceSize) {
  9523. if (!params.Headers['x-cos-metadata-directive']) {
  9524. params.Headers['x-cos-metadata-directive'] = 'Copy';
  9525. }
  9526. self.putObjectCopy(params, function (err, data) {
  9527. if (err) {
  9528. _onProgress3(null, true);
  9529. return callback(err);
  9530. }
  9531. _onProgress3({ loaded: FileSize, total: FileSize }, true);
  9532. callback(err, data);
  9533. });
  9534. } else {
  9535. var resHeaders = data.headers;
  9536. var SourceHeaders = {
  9537. 'Cache-Control': resHeaders['cache-control'],
  9538. 'Content-Disposition': resHeaders['content-disposition'],
  9539. 'Content-Encoding': resHeaders['content-encoding'],
  9540. 'Content-Type': resHeaders['content-type'],
  9541. 'Expires': resHeaders['expires'],
  9542. 'x-cos-storage-class': resHeaders['x-cos-storage-class']
  9543. };
  9544. util.each(resHeaders, function (v, k) {
  9545. var metaPrefix = 'x-cos-meta-';
  9546. if (k.indexOf(metaPrefix) === 0 && k.length > metaPrefix.length) {
  9547. SourceHeaders[k] = v;
  9548. }
  9549. });
  9550. ep.emit('get_file_size_finish', SourceHeaders);
  9551. }
  9552. });
  9553. }
  9554. // 复制指定分片
  9555. function copySliceItem(params, callback) {
  9556. var TaskId = params.TaskId;
  9557. var Bucket = params.Bucket;
  9558. var Region = params.Region;
  9559. var Key = params.Key;
  9560. var CopySource = params.CopySource;
  9561. var UploadId = params.UploadId;
  9562. var PartNumber = params.PartNumber * 1;
  9563. var CopySourceRange = params.CopySourceRange;
  9564. var ChunkRetryTimes = this.options.ChunkRetryTimes + 1;
  9565. var self = this;
  9566. Async.retry(ChunkRetryTimes, function (tryCallback) {
  9567. self.uploadPartCopy({
  9568. TaskId: TaskId,
  9569. Bucket: Bucket,
  9570. Region: Region,
  9571. Key: Key,
  9572. CopySource: CopySource,
  9573. UploadId: UploadId,
  9574. PartNumber: PartNumber,
  9575. CopySourceRange: CopySourceRange,
  9576. onProgress: params.onProgress
  9577. }, function (err, data) {
  9578. tryCallback(err || null, data);
  9579. });
  9580. }, function (err, data) {
  9581. return callback(err, data);
  9582. });
  9583. }
  9584. var API_MAP = {
  9585. sliceUploadFile: sliceUploadFile,
  9586. abortUploadTask: abortUploadTask,
  9587. uploadFile: uploadFile,
  9588. uploadFiles: uploadFiles,
  9589. sliceCopyFile: sliceCopyFile
  9590. };
  9591. module.exports.init = function (COS, task) {
  9592. task.transferToTaskMethod(API_MAP, 'sliceUploadFile');
  9593. util.each(API_MAP, function (fn, apiName) {
  9594. COS.prototype[apiName] = util.apiWrapper(apiName, fn);
  9595. });
  9596. };
  9597. /***/ }),
  9598. /* 25 */
  9599. /***/ (function(module, exports, __webpack_require__) {
  9600. "use strict";
  9601. var eachLimit = function eachLimit(arr, limit, iterator, callback) {
  9602. callback = callback || function () {};
  9603. if (!arr.length || limit <= 0) {
  9604. return callback();
  9605. }
  9606. var completed = 0;
  9607. var started = 0;
  9608. var running = 0;
  9609. (function replenish() {
  9610. if (completed >= arr.length) {
  9611. return callback();
  9612. }
  9613. while (running < limit && started < arr.length) {
  9614. started += 1;
  9615. running += 1;
  9616. iterator(arr[started - 1], function (err) {
  9617. if (err) {
  9618. callback(err);
  9619. callback = function callback() {};
  9620. } else {
  9621. completed += 1;
  9622. running -= 1;
  9623. if (completed >= arr.length) {
  9624. callback();
  9625. } else {
  9626. replenish();
  9627. }
  9628. }
  9629. });
  9630. }
  9631. })();
  9632. };
  9633. var retry = function retry(times, iterator, callback) {
  9634. var next = function next(index) {
  9635. iterator(function (err, data) {
  9636. if (err && index < times) {
  9637. next(index + 1);
  9638. } else {
  9639. callback(err, data);
  9640. }
  9641. });
  9642. };
  9643. if (times < 1) {
  9644. callback();
  9645. } else {
  9646. next(1);
  9647. }
  9648. };
  9649. var async = {
  9650. eachLimit: eachLimit,
  9651. retry: retry
  9652. };
  9653. module.exports = async;
  9654. /***/ })
  9655. /******/ ]);
  9656. });