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

lib-jitsi-meet.js 417KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055
  1. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.JitsiMeetJS=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. var room = null;
  3. /**
  4. * Creates a JitsiConference object with the given name and properties.
  5. * Note: this constructor is not a part of the public API (objects should be
  6. * created using JitsiConnection.createConference).
  7. * @param options.config properties / settings related to the conference that will be created.
  8. * @param options.name the name of the conference
  9. * @param options.connection the JitsiConnection object for this JitsiConference.
  10. * @constructor
  11. */
  12. function JitsiConference(options) {
  13. this.options = options;
  14. this.connection = this.options.connection;
  15. this.xmpp = this.connection.xmpp;
  16. }
  17. /**
  18. * Joins the conference.
  19. */
  20. JitsiConference.prototype.join = function () {
  21. room = this.xmpp.joinRoom(this.options.name, null, null);
  22. }
  23. /**
  24. * Leaves the conference.
  25. */
  26. JitsiConference.prototype.leave = function () {
  27. this.xmpp.leaveRoom(room.roomjid);
  28. room = null;
  29. }
  30. /**
  31. * Creates the media tracks and returns them via the callback.
  32. * @param options Object with properties / settings specifying the tracks which should be created.
  33. * should be created or some additional configurations about resolution for example.
  34. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>} A promise that returns an array of created JitsiTracks if resolved,
  35. * or a JitsiConferenceError if rejected.
  36. */
  37. JitsiConference.prototype.createLocalTracks = function (options) {
  38. }
  39. /**
  40. * Returns the local tracks.
  41. */
  42. JitsiConference.prototype.getLocalTracks = function () {
  43. };
  44. /**
  45. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  46. * in JitsiConferenceEvents.
  47. * @param eventId the event ID.
  48. * @param handler handler for the event.
  49. *
  50. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  51. */
  52. JitsiConference.prototype.on = function (eventId, handler) {
  53. this.xmpp.addListener(eventId, handler);
  54. }
  55. /**
  56. * Removes event listener
  57. * @param eventId the event ID.
  58. * @param [handler] optional, the specific handler to unbind
  59. *
  60. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  61. */
  62. JitsiConference.prototype.off = function (eventId, handler) {
  63. this.xmpp.removeListener(event, listener);
  64. }
  65. // Common aliases for event emitter
  66. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on
  67. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off
  68. /**
  69. * Receives notifications from another participants for commands / custom events(send by sendPresenceCommand method).
  70. * @param command {String} the name of the command
  71. * @param handler {Function} handler for the command
  72. */
  73. JitsiConference.prototype.addCommandListener = function (command, handler) {
  74. }
  75. /**
  76. * Removes command listener
  77. * @param command {String} the name of the command
  78. */
  79. JitsiConference.prototype.removeCommandListener = function (command) {
  80. }
  81. /**
  82. * Sends text message to the other participants in the conference
  83. * @param message the text message.
  84. */
  85. JitsiConference.prototype.sendTextMessage = function (message) {
  86. this.xmpp.sendChatMessage(message);
  87. }
  88. /**
  89. * Send presence command.
  90. * @param name the name of the command.
  91. * @param values Object with keys and values that will be send.
  92. * @param persistent if false the command will be sent only one time
  93. * @param successCallback will be called when the command is successfully send.
  94. * @param errorCallback will be called when the command is not sent successfully.
  95. * @returns {Promise.<{void}, JitsiConferenceError>} A promise that returns an array of created streams if resolved,
  96. * or an JitsiConferenceError if rejected.
  97. */
  98. JitsiConference.prototype.sendCommand = function (name, values, persistent) {
  99. }
  100. /**
  101. * Sets the display name for this conference.
  102. * @param name the display name to set
  103. */
  104. JitsiConference.prototype.setDisplayName = function(name) {
  105. room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  106. }
  107. /**
  108. * Elects the participant with the given id to be the selected participant or the speaker.
  109. * @param id the identifier of the participant
  110. */
  111. JitsiConference.prototype.selectParticipant = function(participantId) {
  112. }
  113. /**
  114. * Returns the list of participants for this conference.
  115. * @return Object a list of participant identifiers containing all conference participants.
  116. */
  117. JitsiConference.prototype.getParticipants = function() {
  118. }
  119. module.exports = JitsiConference;
  120. },{}],2:[function(require,module,exports){
  121. /**
  122. * Enumeration with the errors for the conference.
  123. * @type {{string: string}}
  124. */
  125. var JitsiConferenceErrors = {
  126. /**
  127. * Indicates that a password is required in order to join the conference.
  128. */
  129. PASSWORD_REQUIRED: "conference.passwordRequired",
  130. /**
  131. * Indicates that a connection error occurred when trying to join a conference.
  132. */
  133. CONNECTION_ERROR: "conference.connectionError",
  134. /**
  135. * Indicates that there is no available videobridge.
  136. */
  137. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  138. /**
  139. * Many more errors TBD here.
  140. */
  141. };
  142. module.exports = JitsiConferenceErrors;
  143. },{}],3:[function(require,module,exports){
  144. /**
  145. * Enumeration with the events for the conference.
  146. * @type {{string: string}}
  147. */
  148. var JitsiConferenceEvents = {
  149. /**
  150. * A new media track was added to the conference.
  151. */
  152. TRACK_ADDED: "conference.trackAdded",
  153. /**
  154. * The media track was removed to the conference.
  155. */
  156. TRACK_REMOVED: "conference.trackRemoved",
  157. /**
  158. * The active speaker was changed.
  159. */
  160. ACTIVE_SPEAKER_CHANGED: "conference.activeSpeaker",
  161. /**
  162. * A new user joinned the conference.
  163. */
  164. USER_JOINED: "conference.userJoined",
  165. /**
  166. * A user has left the conference.
  167. */
  168. USER_LEFT: "conference.userLeft",
  169. /**
  170. * New text message was received.
  171. */
  172. MESSAGE_RECEIVED: "conference.messageReceived",
  173. /**
  174. * A user has changed it display name
  175. */
  176. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  177. /**
  178. * A participant avatar has changed.
  179. */
  180. AVATAR_CHANGED: "conference.avatarChanged",
  181. /**
  182. * New connection statistics are received.
  183. */
  184. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  185. /**
  186. * The Last N set is changed.
  187. */
  188. LAST_N_CHANGED: "conference.lastNChanged",
  189. /**
  190. * A media track was muted.
  191. */
  192. TRACK_MUTED: "conference.trackMuted",
  193. /**
  194. * A media track was unmuted.
  195. */
  196. TRACK_UNMUTED: "conference.trackUnmuted",
  197. /**
  198. * Audio levels of a media track was changed.
  199. */
  200. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  201. /**
  202. * Indicates that the connection to the conference has been interrupted for some reason.
  203. */
  204. CONNECTION_INTERRUPTED: "conference.connecionInterrupted",
  205. /**
  206. * Indicates that the connection to the conference has been restored.
  207. */
  208. CONNECTION_ESTABLISHED: "conference.connecionEstablished"
  209. };
  210. module.exports = JitsiConferenceEvents;
  211. },{}],4:[function(require,module,exports){
  212. var JitsiConference = require("./JitsiConference");
  213. var XMPP = require("./modules/xmpp/xmpp");
  214. function wrapper()
  215. {
  216. var jitsiconnectioninstance = new JitsiConnection();
  217. this.a = jitsiconnectioninstance.a();
  218. }
  219. /**
  220. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  221. * JitsiConference interface.
  222. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  223. * @param token secret generated by the provider of Jitsi Meet video conferencing services.
  224. * The token will be send to the provider from the Jitsi Meet server deployment for authorization of the current client.
  225. * @param options Object with properties / settings related to connection with the server.
  226. * @constructor
  227. */
  228. function JitsiConnection(appID, token, options) {
  229. this.appID = appID;
  230. this.token = token;
  231. this.options = options;
  232. this.xmpp = new XMPP(options);
  233. }
  234. /**
  235. * Connect the client with the server.
  236. * @param options {object} connecting options (for example authentications parameters).
  237. */
  238. JitsiConnection.prototype.connect = function (options) {
  239. if(!options)
  240. options = {};
  241. this.xmpp.connect(options.id, options.password);
  242. }
  243. /**
  244. * Disconnect the client from the server.
  245. */
  246. JitsiConnection.prototype.disconnect = function () {
  247. this.xmpp.disconnect();
  248. }
  249. /**
  250. * This method allows renewal of the tokens if they are expiring.
  251. * @param token the new token.
  252. */
  253. JitsiConnection.prototype.setToken = function (token) {
  254. this.token = token;
  255. }
  256. /**
  257. * Creates and joins new conference.
  258. * @param name the name of the conference; if null - a generated name will be provided from the api
  259. * @param options Object with properties / settings related to the conference that will be created.
  260. * @returns {JitsiConference} returns the new conference object.
  261. */
  262. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  263. return new JitsiConference({name: name, config: options, connection: this});
  264. }
  265. /**
  266. * Subscribes the passed listener to the event.
  267. * @param event {JitsiConnectionEvents} the connection event.
  268. * @param listener {Function} the function that will receive the event
  269. */
  270. JitsiConnection.prototype.addEventListener = function (event, listener) {
  271. this.xmpp.addListener(event, listener);
  272. }
  273. /**
  274. * Unsubscribes the passed handler.
  275. * @param event {JitsiConnectionEvents} the connection event.
  276. * @param listener {Function} the function that will receive the event
  277. */
  278. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  279. this.xmpp.removeListener(event, listener);
  280. }
  281. module.exports = JitsiConnection;
  282. },{"./JitsiConference":1,"./modules/xmpp/xmpp":22}],5:[function(require,module,exports){
  283. /**
  284. * Enumeration with the errors for the connection.
  285. * @type {{string: string}}
  286. */
  287. var JitsiConnectionErrors = {
  288. /**
  289. * Indicates that a password is required in order to join the conference.
  290. */
  291. PASSWORD_REQUIRED: "connection.passwordRequired",
  292. /**
  293. * Indicates that a connection error occurred when trying to join a conference.
  294. */
  295. CONNECTION_ERROR: "connection.connectionError",
  296. /**
  297. * Not specified errors.
  298. */
  299. OTHER_ERROR: "connection.otherError"
  300. };
  301. module.exports = JitsiConnectionErrors;
  302. },{}],6:[function(require,module,exports){
  303. /**
  304. * Enumeration with the events for the connection.
  305. * @type {{string: string}}
  306. */
  307. var JitsiConnnectionEvents = {
  308. /**
  309. * Indicates that the connection has been failed for some reason.
  310. */
  311. CONNECTION_FAILED: "connection.connecionFailed",
  312. /**
  313. * Indicates that the connection has been established.
  314. */
  315. CONNECTION_ESTABLISHED: "connection.connecionEstablished",
  316. /**
  317. * Indicates that the connection has been disconnected.
  318. */
  319. CONNECTION_DISCONNECTED: "connection.connecionDisconnected",
  320. /**
  321. * Indicates that the perfomed action cannot be executed because the
  322. * connection is not in the correct state(connected, disconnected, etc.)
  323. */
  324. WRONG_STATE: "connection.wrongState"
  325. };
  326. module.exports = JitsiConnnectionEvents;
  327. },{}],7:[function(require,module,exports){
  328. var JitsiConnection = require("./JitsiConnection");
  329. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  330. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  331. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  332. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  333. /**
  334. * Namespace for the interface of Jitsi Meet Library.
  335. */
  336. var LibJitsiMeet = {
  337. JitsiConnection: JitsiConnection,
  338. events: {
  339. conference: JitsiConferenceEvents,
  340. connection: JitsiConnectionEvents
  341. },
  342. errors: {
  343. conference: JitsiConferenceErrors,
  344. connection: JitsiConnectionErrors
  345. }
  346. }
  347. //Setups the promise object.
  348. require("es6-promise").polyfill();
  349. module.exports = LibJitsiMeet;
  350. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"es6-promise":23}],8:[function(require,module,exports){
  351. /* global config, APP, Strophe */
  352. // cache datachannels to avoid garbage collection
  353. // https://code.google.com/p/chromium/issues/detail?id=405545
  354. var RTCEvents = require("../../service/RTC/RTCEvents");
  355. var _dataChannels = [];
  356. var eventEmitter = null;
  357. var DataChannels = {
  358. /**
  359. * Callback triggered by PeerConnection when new data channel is opened
  360. * on the bridge.
  361. * @param event the event info object.
  362. */
  363. onDataChannel: function (event) {
  364. var dataChannel = event.channel;
  365. dataChannel.onopen = function () {
  366. console.info("Data channel opened by the Videobridge!", dataChannel);
  367. // Code sample for sending string and/or binary data
  368. // Sends String message to the bridge
  369. //dataChannel.send("Hello bridge!");
  370. // Sends 12 bytes binary message to the bridge
  371. //dataChannel.send(new ArrayBuffer(12));
  372. eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  373. };
  374. dataChannel.onerror = function (error) {
  375. console.error("Data Channel Error:", error, dataChannel);
  376. };
  377. dataChannel.onmessage = function (event) {
  378. var data = event.data;
  379. // JSON
  380. var obj;
  381. try {
  382. obj = JSON.parse(data);
  383. }
  384. catch (e) {
  385. console.error(
  386. "Failed to parse data channel message as JSON: ",
  387. data,
  388. dataChannel);
  389. }
  390. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  391. var colibriClass = obj.colibriClass;
  392. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  393. // Endpoint ID from the Videobridge.
  394. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  395. console.info(
  396. "Data channel new dominant speaker event: ",
  397. dominantSpeakerEndpoint);
  398. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  399. }
  400. else if ("InLastNChangeEvent" === colibriClass) {
  401. var oldValue = obj.oldValue;
  402. var newValue = obj.newValue;
  403. // Make sure that oldValue and newValue are of type boolean.
  404. var type;
  405. if ((type = typeof oldValue) !== 'boolean') {
  406. if (type === 'string') {
  407. oldValue = (oldValue == "true");
  408. } else {
  409. oldValue = new Boolean(oldValue).valueOf();
  410. }
  411. }
  412. if ((type = typeof newValue) !== 'boolean') {
  413. if (type === 'string') {
  414. newValue = (newValue == "true");
  415. } else {
  416. newValue = new Boolean(newValue).valueOf();
  417. }
  418. }
  419. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  420. }
  421. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  422. // The new/latest list of last-n endpoint IDs.
  423. var lastNEndpoints = obj.lastNEndpoints;
  424. // The list of endpoint IDs which are entering the list of
  425. // last-n at this time i.e. were not in the old list of last-n
  426. // endpoint IDs.
  427. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  428. console.log(
  429. "Data channel new last-n event: ",
  430. lastNEndpoints, endpointsEnteringLastN, obj);
  431. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  432. lastNEndpoints, endpointsEnteringLastN, obj);
  433. }
  434. else {
  435. console.debug("Data channel JSON-formatted message: ", obj);
  436. }
  437. }
  438. };
  439. dataChannel.onclose = function () {
  440. console.info("The Data Channel closed", dataChannel);
  441. var idx = _dataChannels.indexOf(dataChannel);
  442. if (idx > -1)
  443. _dataChannels = _dataChannels.splice(idx, 1);
  444. };
  445. _dataChannels.push(dataChannel);
  446. },
  447. /**
  448. * Binds "ondatachannel" event listener to given PeerConnection instance.
  449. * @param peerConnection WebRTC peer connection instance.
  450. */
  451. init: function (peerConnection, emitter) {
  452. if(!config.openSctp)
  453. return;
  454. peerConnection.ondatachannel = this.onDataChannel;
  455. eventEmitter = emitter;
  456. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  457. // Although it's not a requirement to open separate channels from both bridge
  458. // and peer as single channel can be used for sending and receiving data.
  459. // So either channel opened by the bridge or the one opened here is enough
  460. // for communication with the bridge.
  461. /*var dataChannelOptions =
  462. {
  463. reliable: true
  464. };
  465. var dataChannel
  466. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  467. // Can be used only when is in open state
  468. dataChannel.onopen = function ()
  469. {
  470. dataChannel.send("My channel !!!");
  471. };
  472. dataChannel.onmessage = function (event)
  473. {
  474. var msgData = event.data;
  475. console.info("Got My Data Channel Message:", msgData, dataChannel);
  476. };*/
  477. },
  478. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  479. handlePinnedEndpointEvent: onPinnedEndpointChanged
  480. };
  481. function onSelectedEndpointChanged(userResource) {
  482. console.log('selected endpoint changed: ', userResource);
  483. if (_dataChannels && _dataChannels.length != 0) {
  484. _dataChannels.some(function (dataChannel) {
  485. if (dataChannel.readyState == 'open') {
  486. console.log('sending selected endpoint changed ' +
  487. 'notification to the bridge: ', userResource);
  488. dataChannel.send(JSON.stringify({
  489. 'colibriClass': 'SelectedEndpointChangedEvent',
  490. 'selectedEndpoint':
  491. (!userResource || userResource === null)?
  492. null : userResource
  493. }));
  494. return true;
  495. }
  496. });
  497. }
  498. }
  499. function onPinnedEndpointChanged(userResource) {
  500. console.log('pinned endpoint changed: ', userResource);
  501. if (_dataChannels && _dataChannels.length != 0) {
  502. _dataChannels.some(function (dataChannel) {
  503. if (dataChannel.readyState == 'open') {
  504. dataChannel.send(JSON.stringify({
  505. 'colibriClass': 'PinnedEndpointChangedEvent',
  506. 'pinnedEndpoint':
  507. (!userResource || userResource == null)?
  508. null : userResource
  509. }));
  510. return true;
  511. }
  512. });
  513. }
  514. }
  515. module.exports = DataChannels;
  516. },{"../../service/RTC/RTCEvents":41}],9:[function(require,module,exports){
  517. /* global APP */
  518. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  519. var RTCEvents = require("../../service/RTC/RTCEvents");
  520. var RTCBrowserType = require("./RTCBrowserType");
  521. /**
  522. * This implements 'onended' callback normally fired by WebRTC after the stream
  523. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  524. * @param stream original WebRTC stream object to which 'onended' handling
  525. * will be added.
  526. */
  527. function implementOnEndedHandling(stream) {
  528. var originalStop = stream.stop;
  529. stream.stop = function () {
  530. originalStop.apply(stream);
  531. if (!stream.ended) {
  532. stream.ended = true;
  533. stream.onended();
  534. }
  535. };
  536. }
  537. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream) {
  538. this.stream = stream;
  539. this.eventEmitter = eventEmitter;
  540. this.type = type;
  541. this.videoType = videoType;
  542. this.isGUMStream = true;
  543. if(isGUMStream === false)
  544. this.isGUMStream = isGUMStream;
  545. var self = this;
  546. if(type == "audio") {
  547. this.getTracks = function () {
  548. return self.stream.getAudioTracks();
  549. };
  550. } else {
  551. this.getTracks = function () {
  552. return self.stream.getVideoTracks();
  553. };
  554. }
  555. this.stream.onended = function () {
  556. self.streamEnded();
  557. };
  558. if (RTCBrowserType.isFirefox()) {
  559. implementOnEndedHandling(this.stream);
  560. }
  561. }
  562. LocalStream.prototype.streamEnded = function () {
  563. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  564. };
  565. LocalStream.prototype.getOriginalStream = function()
  566. {
  567. return this.stream;
  568. };
  569. LocalStream.prototype.isAudioStream = function () {
  570. return this.type === "audio";
  571. };
  572. LocalStream.prototype.setMute = function (mute)
  573. {
  574. var isAudio = this.isAudioStream();
  575. var eventType = isAudio ? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE;
  576. if ((window.location.protocol != "https:" && this.isGUMStream) ||
  577. (isAudio && this.isGUMStream) || this.videoType === "screen" ||
  578. // FIXME FF does not support 'removeStream' method used to mute
  579. RTCBrowserType.isFirefox()) {
  580. var tracks = this.getTracks();
  581. for (var idx = 0; idx < tracks.length; idx++) {
  582. tracks[idx].enabled = !mute;
  583. }
  584. this.eventEmitter.emit(eventType, mute);
  585. } else {
  586. if (mute) {
  587. APP.xmpp.removeStream(this.stream);
  588. this.stream.stop();
  589. this.eventEmitter.emit(eventType, true);
  590. } else {
  591. var self = this;
  592. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  593. (this.isAudioStream() ? ["audio"] : ["video"]),
  594. function (stream) {
  595. if (isAudio) {
  596. APP.RTC.changeLocalAudio(stream,
  597. function () {
  598. self.eventEmitter.emit(eventType, false);
  599. });
  600. } else {
  601. APP.RTC.changeLocalVideo(stream, false,
  602. function () {
  603. self.eventEmitter.emit(eventType, false);
  604. });
  605. }
  606. });
  607. }
  608. }
  609. };
  610. LocalStream.prototype.isMuted = function () {
  611. var tracks = [];
  612. if (this.isAudioStream()) {
  613. tracks = this.stream.getAudioTracks();
  614. } else {
  615. if (this.stream.ended)
  616. return true;
  617. tracks = this.stream.getVideoTracks();
  618. }
  619. for (var idx = 0; idx < tracks.length; idx++) {
  620. if(tracks[idx].enabled)
  621. return false;
  622. }
  623. return true;
  624. };
  625. LocalStream.prototype.getId = function () {
  626. return this.stream.getTracks()[0].id;
  627. };
  628. module.exports = LocalStream;
  629. },{"../../service/RTC/RTCEvents":41,"../../service/RTC/StreamEventTypes.js":43,"./RTCBrowserType":12}],10:[function(require,module,exports){
  630. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  631. /**
  632. * Creates a MediaStream object for the given data, session id and ssrc.
  633. * It is a wrapper class for the MediaStream.
  634. *
  635. * @param data the data object from which we obtain the stream,
  636. * the peerjid, etc.
  637. * @param sid the session id
  638. * @param ssrc the ssrc corresponding to this MediaStream
  639. *
  640. * @constructor
  641. */
  642. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  643. // XXX(gp) to minimize headaches in the future, we should build our
  644. // abstractions around tracks and not streams. ORTC is track based API.
  645. // Mozilla expects m-lines to represent media tracks.
  646. //
  647. // Practically, what I'm saying is that we should have a MediaTrack class
  648. // and not a MediaStream class.
  649. //
  650. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  651. // a track might have an associated RTX and FEC sources.
  652. this.sid = sid;
  653. this.stream = data.stream;
  654. this.peerjid = data.peerjid;
  655. this.videoType = data.videoType;
  656. this.ssrc = ssrc;
  657. this.type = (this.stream.getVideoTracks().length > 0)?
  658. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  659. this.muted = false;
  660. this.eventEmitter = eventEmitter;
  661. }
  662. MediaStream.prototype.getOriginalStream = function() {
  663. return this.stream;
  664. };
  665. MediaStream.prototype.setMute = function (value) {
  666. this.stream.muted = value;
  667. this.muted = value;
  668. };
  669. module.exports = MediaStream;
  670. },{"../../service/RTC/MediaStreamTypes":40}],11:[function(require,module,exports){
  671. /* global APP */
  672. var EventEmitter = require("events");
  673. var RTCBrowserType = require("./RTCBrowserType");
  674. var RTCUtils = require("./RTCUtils.js");
  675. var LocalStream = require("./LocalStream.js");
  676. var DataChannels = require("./DataChannels");
  677. var MediaStream = require("./MediaStream.js");
  678. var DesktopSharingEventTypes
  679. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  680. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  681. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  682. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  683. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  684. var UIEvents = require("../../service/UI/UIEvents");
  685. var eventEmitter = new EventEmitter();
  686. function getMediaStreamUsage()
  687. {
  688. var result = {
  689. audio: true,
  690. video: true
  691. };
  692. /** There are some issues with the desktop sharing
  693. * when this property is enabled.
  694. * WARNING: We must change the implementation to start video/audio if we
  695. * receive from the focus that the peer is not muted.
  696. var isSecureConnection = window.location.protocol == "https:";
  697. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  698. {
  699. result = {
  700. audio: false,
  701. video: false
  702. };
  703. }
  704. **/
  705. return result;
  706. }
  707. var RTC = {
  708. rtcUtils: null,
  709. devices: {
  710. audio: true,
  711. video: true
  712. },
  713. localStreams: [],
  714. remoteStreams: {},
  715. localAudio: null,
  716. localVideo: null,
  717. addStreamListener: function (listener, eventType) {
  718. eventEmitter.on(eventType, listener);
  719. },
  720. addListener: function (type, listener) {
  721. eventEmitter.on(type, listener);
  722. },
  723. removeStreamListener: function (listener, eventType) {
  724. if(!(eventType instanceof StreamEventTypes))
  725. throw "Illegal argument";
  726. eventEmitter.removeListener(eventType, listener);
  727. },
  728. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  729. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  730. //in firefox we have only one stream object
  731. if(this.localStreams.length == 0 ||
  732. this.localStreams[0].getOriginalStream() != stream)
  733. this.localStreams.push(localStream);
  734. if(isMuted === true)
  735. localStream.setMute(true);
  736. if(type == "audio") {
  737. this.localAudio = localStream;
  738. } else {
  739. this.localVideo = localStream;
  740. }
  741. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  742. if(change)
  743. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  744. eventEmitter.emit(eventType, localStream, isMuted);
  745. return localStream;
  746. },
  747. removeLocalStream: function (stream) {
  748. for(var i = 0; i < this.localStreams.length; i++) {
  749. if(this.localStreams[i].getOriginalStream() === stream) {
  750. delete this.localStreams[i];
  751. return;
  752. }
  753. }
  754. },
  755. createRemoteStream: function (data, sid, thessrc) {
  756. var remoteStream = new MediaStream(data, sid, thessrc,
  757. RTCBrowserType.getBrowserType(), eventEmitter);
  758. var jid = data.peerjid || APP.xmpp.myJid();
  759. if(!this.remoteStreams[jid]) {
  760. this.remoteStreams[jid] = {};
  761. }
  762. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  763. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  764. return remoteStream;
  765. },
  766. getPCConstraints: function () {
  767. return this.rtcUtils.pc_constraints;
  768. },
  769. getUserMediaWithConstraints:function(um, success_callback,
  770. failure_callback, resolution,
  771. bandwidth, fps, desktopStream)
  772. {
  773. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  774. failure_callback, resolution, bandwidth, fps, desktopStream);
  775. },
  776. attachMediaStream: function (elSelector, stream) {
  777. this.rtcUtils.attachMediaStream(elSelector, stream);
  778. },
  779. getStreamID: function (stream) {
  780. return this.rtcUtils.getStreamID(stream);
  781. },
  782. getVideoSrc: function (element) {
  783. return this.rtcUtils.getVideoSrc(element);
  784. },
  785. setVideoSrc: function (element, src) {
  786. this.rtcUtils.setVideoSrc(element, src);
  787. },
  788. getVideoElementName: function () {
  789. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  790. },
  791. dispose: function() {
  792. if (this.rtcUtils) {
  793. this.rtcUtils = null;
  794. }
  795. },
  796. stop: function () {
  797. this.dispose();
  798. },
  799. start: function () {
  800. var self = this;
  801. APP.desktopsharing.addListener(
  802. function (stream, isUsingScreenStream, callback) {
  803. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  804. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  805. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  806. DataChannels.init(event.peerconnection, eventEmitter);
  807. });
  808. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  809. DataChannels.handleSelectedEndpointEvent);
  810. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  811. DataChannels.handlePinnedEndpointEvent);
  812. // In case of IE we continue from 'onReady' callback
  813. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  814. // once it is initialized.
  815. var onReady = function () {
  816. eventEmitter.emit(RTCEvents.RTC_READY, true);
  817. self.rtcUtils.obtainAudioAndVideoPermissions(
  818. null, null, getMediaStreamUsage());
  819. };
  820. this.rtcUtils = new RTCUtils(this, onReady);
  821. // Call onReady() if Temasys plugin is not used
  822. if (!RTCBrowserType.isTemasysPluginUsed()) {
  823. onReady();
  824. }
  825. },
  826. muteRemoteVideoStream: function (jid, value) {
  827. var stream;
  828. if(this.remoteStreams[jid] &&
  829. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  830. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  831. }
  832. if(!stream)
  833. return true;
  834. if (value != stream.muted) {
  835. stream.setMute(value);
  836. return true;
  837. }
  838. return false;
  839. },
  840. switchVideoStreams: function (new_stream) {
  841. this.localVideo.stream = new_stream;
  842. this.localStreams = [];
  843. //in firefox we have only one stream object
  844. if (this.localAudio.getOriginalStream() != new_stream)
  845. this.localStreams.push(this.localAudio);
  846. this.localStreams.push(this.localVideo);
  847. },
  848. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  849. var oldStream = this.localVideo.getOriginalStream();
  850. var type = (isUsingScreenStream ? "screen" : "camera");
  851. var localCallback = callback;
  852. if(this.localVideo.isMuted() && this.localVideo.videoType !== type) {
  853. localCallback = function() {
  854. APP.xmpp.setVideoMute(false, function(mute) {
  855. eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);
  856. });
  857. callback();
  858. };
  859. }
  860. // FIXME: Workaround for FF/IE/Safari
  861. if (stream && stream.videoStream) {
  862. stream = stream.videoStream;
  863. }
  864. var videoStream = this.rtcUtils.createStream(stream, true);
  865. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  866. // Stop the stream to trigger onended event for old stream
  867. oldStream.stop();
  868. this.switchVideoStreams(videoStream, oldStream);
  869. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  870. },
  871. changeLocalAudio: function (stream, callback) {
  872. var oldStream = this.localAudio.getOriginalStream();
  873. var newStream = this.rtcUtils.createStream(stream);
  874. this.localAudio = this.createLocalStream(newStream, "audio", true);
  875. // Stop the stream to trigger onended event for old stream
  876. oldStream.stop();
  877. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  878. },
  879. isVideoMuted: function (jid) {
  880. if (jid === APP.xmpp.myJid()) {
  881. var localVideo = APP.RTC.localVideo;
  882. return (!localVideo || localVideo.isMuted());
  883. } else {
  884. if (!APP.RTC.remoteStreams[jid] ||
  885. !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  886. return null;
  887. }
  888. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  889. }
  890. },
  891. setVideoMute: function (mute, callback, options) {
  892. if (!this.localVideo)
  893. return;
  894. if (mute == APP.RTC.localVideo.isMuted())
  895. {
  896. APP.xmpp.sendVideoInfoPresence(mute);
  897. if (callback)
  898. callback(mute);
  899. }
  900. else
  901. {
  902. APP.RTC.localVideo.setMute(mute);
  903. APP.xmpp.setVideoMute(
  904. mute,
  905. callback,
  906. options);
  907. }
  908. },
  909. setDeviceAvailability: function (devices) {
  910. if(!devices)
  911. return;
  912. if(devices.audio === true || devices.audio === false)
  913. this.devices.audio = devices.audio;
  914. if(devices.video === true || devices.video === false)
  915. this.devices.video = devices.video;
  916. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  917. }
  918. };
  919. module.exports = RTC;
  920. },{"../../service/RTC/MediaStreamTypes":40,"../../service/RTC/RTCEvents.js":41,"../../service/RTC/StreamEventTypes.js":43,"../../service/UI/UIEvents":44,"../../service/desktopsharing/DesktopSharingEventTypes":46,"../../service/xmpp/XMPPEvents":47,"./DataChannels":8,"./LocalStream.js":9,"./MediaStream.js":10,"./RTCBrowserType":12,"./RTCUtils.js":13,"events":48}],12:[function(require,module,exports){
  921. var currentBrowser;
  922. var browserVersion;
  923. var RTCBrowserType = {
  924. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  925. RTC_BROWSER_OPERA: "rtc_browser.opera",
  926. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  927. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  928. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  929. getBrowserType: function () {
  930. return currentBrowser;
  931. },
  932. isChrome: function () {
  933. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  934. },
  935. isOpera: function () {
  936. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  937. },
  938. isFirefox: function () {
  939. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  940. },
  941. isIExplorer: function () {
  942. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  943. },
  944. isSafari: function () {
  945. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  946. },
  947. isTemasysPluginUsed: function () {
  948. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  949. },
  950. getFirefoxVersion: function () {
  951. return RTCBrowserType.isFirefox() ? browserVersion : null;
  952. },
  953. getChromeVersion: function () {
  954. return RTCBrowserType.isChrome() ? browserVersion : null;
  955. },
  956. usesPlanB: function() {
  957. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  958. RTCBrowserType.isTemasysPluginUsed();
  959. },
  960. usesUnifiedPlan: function() {
  961. return RTCBrowserType.isFirefox();
  962. }
  963. // Add version getters for other browsers when needed
  964. };
  965. // detectOpera() must be called before detectChrome() !!!
  966. // otherwise Opera wil be detected as Chrome
  967. function detectChrome() {
  968. if (navigator.webkitGetUserMedia) {
  969. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  970. var userAgent = navigator.userAgent.toLowerCase();
  971. // We can assume that user agent is chrome, because it's
  972. // enforced when 'ext' streaming method is set
  973. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  974. console.log("This appears to be Chrome, ver: " + ver);
  975. return ver;
  976. }
  977. return null;
  978. }
  979. function detectOpera() {
  980. var userAgent = navigator.userAgent;
  981. if (userAgent.match(/Opera|OPR/)) {
  982. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  983. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  984. console.info("This appears to be Opera, ver: " + version);
  985. return version;
  986. }
  987. return null;
  988. }
  989. function detectFirefox() {
  990. if (navigator.mozGetUserMedia) {
  991. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  992. var version = parseInt(
  993. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  994. console.log('This appears to be Firefox, ver: ' + version);
  995. return version;
  996. }
  997. return null;
  998. }
  999. function detectSafari() {
  1000. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1001. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1002. console.info("This appears to be Safari");
  1003. // FIXME detect Safari version when needed
  1004. return 1;
  1005. }
  1006. return null;
  1007. }
  1008. function detectIE() {
  1009. var version;
  1010. var ua = window.navigator.userAgent;
  1011. var msie = ua.indexOf('MSIE ');
  1012. if (msie > 0) {
  1013. // IE 10 or older => return version number
  1014. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1015. }
  1016. var trident = ua.indexOf('Trident/');
  1017. if (!version && trident > 0) {
  1018. // IE 11 => return version number
  1019. var rv = ua.indexOf('rv:');
  1020. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1021. }
  1022. var edge = ua.indexOf('Edge/');
  1023. if (!version && edge > 0) {
  1024. // IE 12 => return version number
  1025. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1026. }
  1027. if (version) {
  1028. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1029. console.info("This appears to be IExplorer, ver: " + version);
  1030. }
  1031. return version;
  1032. }
  1033. function detectBrowser() {
  1034. var version;
  1035. var detectors = [
  1036. detectOpera,
  1037. detectChrome,
  1038. detectFirefox,
  1039. detectIE,
  1040. detectSafari
  1041. ];
  1042. // Try all browser detectors
  1043. for (var i = 0; i < detectors.length; i++) {
  1044. version = detectors[i]();
  1045. if (version)
  1046. return version;
  1047. }
  1048. console.error("Failed to detect browser type");
  1049. return undefined;
  1050. }
  1051. browserVersion = detectBrowser();
  1052. module.exports = RTCBrowserType;
  1053. },{}],13:[function(require,module,exports){
  1054. /* global config, require, attachMediaStream, getUserMedia */
  1055. var RTCBrowserType = require("./RTCBrowserType");
  1056. var Resolutions = require("../../service/RTC/Resolutions");
  1057. var AdapterJS = require("./adapter.screenshare");
  1058. var SDPUtil = require("../xmpp/SDPUtil");
  1059. var currentResolution = null;
  1060. function getPreviousResolution(resolution) {
  1061. if(!Resolutions[resolution])
  1062. return null;
  1063. var order = Resolutions[resolution].order;
  1064. var res = null;
  1065. var resName = null;
  1066. for(var i in Resolutions) {
  1067. var tmp = Resolutions[i];
  1068. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  1069. resName = i;
  1070. res = tmp;
  1071. }
  1072. }
  1073. return resName;
  1074. }
  1075. function setResolutionConstraints(constraints, resolution, isAndroid) {
  1076. if (Resolutions[resolution]) {
  1077. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1078. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1079. }
  1080. else if (isAndroid) {
  1081. // FIXME can't remember if the purpose of this was to always request
  1082. // low resolution on Android ? if yes it should be moved up front
  1083. constraints.video.mandatory.minWidth = 320;
  1084. constraints.video.mandatory.minHeight = 240;
  1085. constraints.video.mandatory.maxFrameRate = 15;
  1086. }
  1087. if (constraints.video.mandatory.minWidth)
  1088. constraints.video.mandatory.maxWidth =
  1089. constraints.video.mandatory.minWidth;
  1090. if (constraints.video.mandatory.minHeight)
  1091. constraints.video.mandatory.maxHeight =
  1092. constraints.video.mandatory.minHeight;
  1093. }
  1094. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1095. {
  1096. var constraints = {audio: false, video: false};
  1097. if (um.indexOf('video') >= 0) {
  1098. // same behaviour as true
  1099. constraints.video = { mandatory: {}, optional: [] };
  1100. constraints.video.optional.push({ googLeakyBucket: true });
  1101. setResolutionConstraints(constraints, resolution, isAndroid);
  1102. }
  1103. if (um.indexOf('audio') >= 0) {
  1104. if (!RTCBrowserType.isFirefox()) {
  1105. // same behaviour as true
  1106. constraints.audio = { mandatory: {}, optional: []};
  1107. // if it is good enough for hangouts...
  1108. constraints.audio.optional.push(
  1109. {googEchoCancellation: true},
  1110. {googAutoGainControl: true},
  1111. {googNoiseSupression: true},
  1112. {googHighpassFilter: true},
  1113. {googNoisesuppression2: true},
  1114. {googEchoCancellation2: true},
  1115. {googAutoGainControl2: true}
  1116. );
  1117. } else {
  1118. constraints.audio = true;
  1119. }
  1120. }
  1121. if (um.indexOf('screen') >= 0) {
  1122. if (RTCBrowserType.isChrome()) {
  1123. constraints.video = {
  1124. mandatory: {
  1125. chromeMediaSource: "screen",
  1126. googLeakyBucket: true,
  1127. maxWidth: window.screen.width,
  1128. maxHeight: window.screen.height,
  1129. maxFrameRate: 3
  1130. },
  1131. optional: []
  1132. };
  1133. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1134. constraints.video = {
  1135. optional: [
  1136. {
  1137. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1138. }
  1139. ]
  1140. };
  1141. } else {
  1142. console.error(
  1143. "'screen' WebRTC media source is supported only in Chrome" +
  1144. " and with Temasys plugin");
  1145. }
  1146. }
  1147. if (um.indexOf('desktop') >= 0) {
  1148. constraints.video = {
  1149. mandatory: {
  1150. chromeMediaSource: "desktop",
  1151. chromeMediaSourceId: desktopStream,
  1152. googLeakyBucket: true,
  1153. maxWidth: window.screen.width,
  1154. maxHeight: window.screen.height,
  1155. maxFrameRate: 3
  1156. },
  1157. optional: []
  1158. };
  1159. }
  1160. if (bandwidth) {
  1161. if (!constraints.video) {
  1162. //same behaviour as true
  1163. constraints.video = {mandatory: {}, optional: []};
  1164. }
  1165. constraints.video.optional.push({bandwidth: bandwidth});
  1166. }
  1167. if (fps) {
  1168. // for some cameras it might be necessary to request 30fps
  1169. // so they choose 30fps mjpg over 10fps yuy2
  1170. if (!constraints.video) {
  1171. // same behaviour as true;
  1172. constraints.video = {mandatory: {}, optional: []};
  1173. }
  1174. constraints.video.mandatory.minFrameRate = fps;
  1175. }
  1176. return constraints;
  1177. }
  1178. //Options parameter is to pass config options. Currently uses only "useIPv6".
  1179. function RTCUtils(RTCService, onTemasysPluginReady, options)
  1180. {
  1181. var self = this;
  1182. this.service = RTCService;
  1183. if (RTCBrowserType.isFirefox()) {
  1184. var FFversion = RTCBrowserType.getFirefoxVersion();
  1185. if (FFversion >= 40) {
  1186. this.peerconnection = mozRTCPeerConnection;
  1187. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1188. this.pc_constraints = {};
  1189. this.attachMediaStream = function (element, stream) {
  1190. // srcObject is being standardized and FF will eventually
  1191. // support that unprefixed. FF also supports the
  1192. // "element.src = URL.createObjectURL(...)" combo, but that
  1193. // will be deprecated in favour of srcObject.
  1194. //
  1195. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1196. // https://github.com/webrtc/samples/issues/302
  1197. if(!element[0])
  1198. return;
  1199. element[0].mozSrcObject = stream;
  1200. element[0].play();
  1201. };
  1202. this.getStreamID = function (stream) {
  1203. var id = stream.id;
  1204. if (!id) {
  1205. var tracks = stream.getVideoTracks();
  1206. if (!tracks || tracks.length === 0) {
  1207. tracks = stream.getAudioTracks();
  1208. }
  1209. id = tracks[0].id;
  1210. }
  1211. return SDPUtil.filter_special_chars(id);
  1212. };
  1213. this.getVideoSrc = function (element) {
  1214. if(!element)
  1215. return null;
  1216. return element.mozSrcObject;
  1217. };
  1218. this.setVideoSrc = function (element, src) {
  1219. if(element)
  1220. element.mozSrcObject = src;
  1221. };
  1222. RTCSessionDescription = mozRTCSessionDescription;
  1223. RTCIceCandidate = mozRTCIceCandidate;
  1224. } else {
  1225. console.error(
  1226. "Firefox version too old: " + FFversion + ". Required >= 40.");
  1227. window.location.href = 'unsupported_browser.html';
  1228. return;
  1229. }
  1230. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1231. this.peerconnection = webkitRTCPeerConnection;
  1232. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1233. this.attachMediaStream = function (element, stream) {
  1234. element.attr('src', webkitURL.createObjectURL(stream));
  1235. };
  1236. this.getStreamID = function (stream) {
  1237. // streams from FF endpoints have the characters '{' and '}'
  1238. // that make jQuery choke.
  1239. return SDPUtil.filter_special_chars(stream.id);
  1240. };
  1241. this.getVideoSrc = function (element) {
  1242. if(!element)
  1243. return null;
  1244. return element.getAttribute("src");
  1245. };
  1246. this.setVideoSrc = function (element, src) {
  1247. if(element)
  1248. element.setAttribute("src", src);
  1249. };
  1250. // DTLS should now be enabled by default but..
  1251. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1252. if (options.useIPv6) {
  1253. // https://code.google.com/p/webrtc/issues/detail?id=2828
  1254. this.pc_constraints.optional.push({googIPv6: true});
  1255. }
  1256. if (navigator.userAgent.indexOf('Android') != -1) {
  1257. this.pc_constraints = {}; // disable DTLS on Android
  1258. }
  1259. if (!webkitMediaStream.prototype.getVideoTracks) {
  1260. webkitMediaStream.prototype.getVideoTracks = function () {
  1261. return this.videoTracks;
  1262. };
  1263. }
  1264. if (!webkitMediaStream.prototype.getAudioTracks) {
  1265. webkitMediaStream.prototype.getAudioTracks = function () {
  1266. return this.audioTracks;
  1267. };
  1268. }
  1269. }
  1270. // Detect IE/Safari
  1271. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1272. //AdapterJS.WebRTCPlugin.setLogLevel(
  1273. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1274. AdapterJS.webRTCReady(function (isPlugin) {
  1275. self.peerconnection = RTCPeerConnection;
  1276. self.getUserMedia = getUserMedia;
  1277. self.attachMediaStream = function (elSel, stream) {
  1278. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1279. return;
  1280. }
  1281. attachMediaStream(elSel[0], stream);
  1282. };
  1283. self.getStreamID = function (stream) {
  1284. var id = SDPUtil.filter_special_chars(stream.label);
  1285. return id;
  1286. };
  1287. self.getVideoSrc = function (element) {
  1288. if (!element) {
  1289. console.warn("Attempt to get video SRC of null element");
  1290. return null;
  1291. }
  1292. var children = element.children;
  1293. for (var i = 0; i !== children.length; ++i) {
  1294. if (children[i].name === 'streamId') {
  1295. return children[i].value;
  1296. }
  1297. }
  1298. //console.info(element.id + " SRC: " + src);
  1299. return null;
  1300. };
  1301. self.setVideoSrc = function (element, src) {
  1302. //console.info("Set video src: ", element, src);
  1303. if (!src) {
  1304. console.warn("Not attaching video stream, 'src' is null");
  1305. return;
  1306. }
  1307. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1308. var stream = AdapterJS.WebRTCPlugin.plugin
  1309. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1310. attachMediaStream(element, stream);
  1311. };
  1312. onTemasysPluginReady(isPlugin);
  1313. });
  1314. } else {
  1315. try {
  1316. console.log('Browser does not appear to be WebRTC-capable');
  1317. } catch (e) { }
  1318. window.location.href = 'unsupported_browser.html';
  1319. }
  1320. }
  1321. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1322. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1323. desktopStream) {
  1324. currentResolution = resolution;
  1325. // Check if we are running on Android device
  1326. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1327. var constraints = getConstraints(
  1328. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1329. console.info("Get media constraints", constraints);
  1330. var self = this;
  1331. try {
  1332. this.getUserMedia(constraints,
  1333. function (stream) {
  1334. console.log('onUserMediaSuccess');
  1335. self.setAvailableDevices(um, true);
  1336. success_callback(stream);
  1337. },
  1338. function (error) {
  1339. self.setAvailableDevices(um, false);
  1340. console.warn('Failed to get access to local media. Error ',
  1341. error, constraints);
  1342. if (failure_callback) {
  1343. failure_callback(error);
  1344. }
  1345. });
  1346. } catch (e) {
  1347. console.error('GUM failed: ', e);
  1348. if(failure_callback) {
  1349. failure_callback(e);
  1350. }
  1351. }
  1352. };
  1353. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1354. var devices = {};
  1355. if(um.indexOf("video") != -1) {
  1356. devices.video = available;
  1357. }
  1358. if(um.indexOf("audio") != -1) {
  1359. devices.audio = available;
  1360. }
  1361. this.service.setDeviceAvailability(devices);
  1362. };
  1363. /**
  1364. * We ask for audio and video combined stream in order to get permissions and
  1365. * not to ask twice.
  1366. */
  1367. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1368. function(devices, callback, usageOptions)
  1369. {
  1370. var self = this;
  1371. // Get AV
  1372. var successCallback = function (stream) {
  1373. if(callback)
  1374. callback(stream, usageOptions);
  1375. else
  1376. self.successCallback(stream, usageOptions);
  1377. };
  1378. if(!devices)
  1379. devices = ['audio', 'video'];
  1380. var newDevices = [];
  1381. if(usageOptions)
  1382. for(var i = 0; i < devices.length; i++) {
  1383. var device = devices[i];
  1384. if(usageOptions[device] === true)
  1385. newDevices.push(device);
  1386. }
  1387. else
  1388. newDevices = devices;
  1389. if(newDevices.length === 0) {
  1390. successCallback();
  1391. return;
  1392. }
  1393. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1394. // With FF/IE we can't split the stream into audio and video because FF
  1395. // doesn't support media stream constructors. So, we need to get the
  1396. // audio stream separately from the video stream using two distinct GUM
  1397. // calls. Not very user friendly :-( but we don't have many other
  1398. // options neither.
  1399. //
  1400. // Note that we pack those 2 streams in a single object and pass it to
  1401. // the successCallback method.
  1402. var obtainVideo = function (audioStream) {
  1403. self.getUserMediaWithConstraints(
  1404. ['video'],
  1405. function (videoStream) {
  1406. return successCallback({
  1407. audioStream: audioStream,
  1408. videoStream: videoStream
  1409. });
  1410. },
  1411. function (error) {
  1412. console.error(
  1413. 'failed to obtain video stream - stop', error);
  1414. self.errorCallback(error);
  1415. },
  1416. config.resolution || '360');
  1417. };
  1418. var obtainAudio = function () {
  1419. self.getUserMediaWithConstraints(
  1420. ['audio'],
  1421. function (audioStream) {
  1422. if (newDevices.indexOf('video') !== -1)
  1423. obtainVideo(audioStream);
  1424. },
  1425. function (error) {
  1426. console.error(
  1427. 'failed to obtain audio stream - stop', error);
  1428. self.errorCallback(error);
  1429. }
  1430. );
  1431. };
  1432. if (newDevices.indexOf('audio') !== -1) {
  1433. obtainAudio();
  1434. } else {
  1435. obtainVideo(null);
  1436. }
  1437. } else {
  1438. this.getUserMediaWithConstraints(
  1439. newDevices,
  1440. function (stream) {
  1441. successCallback(stream);
  1442. },
  1443. function (error) {
  1444. self.errorCallback(error);
  1445. },
  1446. config.resolution || '360');
  1447. }
  1448. };
  1449. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1450. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1451. // it's an object with two properties: audioStream, videoStream.
  1452. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1453. console.log('got', stream, stream.getAudioTracks().length,
  1454. stream.getVideoTracks().length);
  1455. this.handleLocalStream(stream, usageOptions);
  1456. };
  1457. RTCUtils.prototype.errorCallback = function (error) {
  1458. var self = this;
  1459. console.error('failed to obtain audio/video stream - trying audio only', error);
  1460. var resolution = getPreviousResolution(currentResolution);
  1461. if(typeof error == "object" && error.constraintName && error.name
  1462. && (error.name == "ConstraintNotSatisfiedError" ||
  1463. error.name == "OverconstrainedError") &&
  1464. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1465. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1466. && resolution != null)
  1467. {
  1468. self.getUserMediaWithConstraints(['audio', 'video'],
  1469. function (stream) {
  1470. return self.successCallback(stream);
  1471. }, function (error) {
  1472. return self.errorCallback(error);
  1473. }, resolution);
  1474. }
  1475. else {
  1476. self.getUserMediaWithConstraints(
  1477. ['audio'],
  1478. function (stream) {
  1479. return self.successCallback(stream);
  1480. },
  1481. function (error) {
  1482. console.error('failed to obtain audio/video stream - stop',
  1483. error);
  1484. return self.successCallback(null);
  1485. }
  1486. );
  1487. }
  1488. };
  1489. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions) {
  1490. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1491. // an object with two properties: audioStream, videoStream.
  1492. var audioStream, videoStream;
  1493. if(window.webkitMediaStream)
  1494. {
  1495. audioStream = new webkitMediaStream();
  1496. videoStream = new webkitMediaStream();
  1497. if(stream) {
  1498. var audioTracks = stream.getAudioTracks();
  1499. for (var i = 0; i < audioTracks.length; i++) {
  1500. audioStream.addTrack(audioTracks[i]);
  1501. }
  1502. var videoTracks = stream.getVideoTracks();
  1503. for (i = 0; i < videoTracks.length; i++) {
  1504. videoStream.addTrack(videoTracks[i]);
  1505. }
  1506. }
  1507. }
  1508. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())
  1509. { // Firefox and Temasys plugin
  1510. if (stream && stream.audioStream)
  1511. audioStream = stream.audioStream;
  1512. else
  1513. audioStream = new DummyMediaStream("dummyAudio");
  1514. if (stream && stream.videoStream)
  1515. videoStream = stream.videoStream;
  1516. else
  1517. videoStream = new DummyMediaStream("dummyVideo");
  1518. }
  1519. var audioMuted = (usageOptions && usageOptions.audio === false),
  1520. videoMuted = (usageOptions && usageOptions.video === false);
  1521. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1522. videoGUM = (!usageOptions || usageOptions.video !== false);
  1523. this.service.createLocalStream(audioStream, "audio", null, null,
  1524. audioMuted, audioGUM);
  1525. this.service.createLocalStream(videoStream, "video", null, 'camera',
  1526. videoMuted, videoGUM);
  1527. };
  1528. function DummyMediaStream(id) {
  1529. this.id = id;
  1530. this.label = id;
  1531. this.stop = function() { };
  1532. this.getAudioTracks = function() { return []; };
  1533. this.getVideoTracks = function() { return []; };
  1534. }
  1535. RTCUtils.prototype.createStream = function(stream, isVideo) {
  1536. var newStream = null;
  1537. if (window.webkitMediaStream) {
  1538. newStream = new webkitMediaStream();
  1539. if (newStream) {
  1540. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  1541. for (var i = 0; i < tracks.length; i++) {
  1542. newStream.addTrack(tracks[i]);
  1543. }
  1544. }
  1545. }
  1546. else {
  1547. // FIXME: this is duplicated with 'handleLocalStream' !!!
  1548. if (stream) {
  1549. newStream = stream;
  1550. } else {
  1551. newStream =
  1552. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  1553. }
  1554. }
  1555. return newStream;
  1556. };
  1557. module.exports = RTCUtils;
  1558. },{"../../service/RTC/Resolutions":42,"../xmpp/SDPUtil":16,"./RTCBrowserType":12,"./adapter.screenshare":14}],14:[function(require,module,exports){
  1559. /*! adapterjs - custom version from - 2015-08-12 */
  1560. // Adapter's interface.
  1561. var AdapterJS = AdapterJS || {};
  1562. // Browserify compatibility
  1563. if(typeof exports !== 'undefined') {
  1564. module.exports = AdapterJS;
  1565. }
  1566. AdapterJS.options = AdapterJS.options || {};
  1567. // uncomment to get virtual webcams
  1568. // AdapterJS.options.getAllCams = true;
  1569. // uncomment to prevent the install prompt when the plugin in not yet installed
  1570. // AdapterJS.options.hidePluginInstallPrompt = true;
  1571. // AdapterJS version
  1572. AdapterJS.VERSION = '0.11.1';
  1573. // This function will be called when the WebRTC API is ready to be used
  1574. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  1575. // the plugin
  1576. // You may Override this function to synchronise the start of your application
  1577. // with the WebRTC API being ready.
  1578. // If you decide not to override use this synchronisation, it may result in
  1579. // an extensive CPU usage on the plugin start (once per tab loaded)
  1580. // Params:
  1581. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  1582. //
  1583. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  1584. // The WebRTC API is ready.
  1585. // Override me and do whatever you want here
  1586. };
  1587. // Sets a callback function to be called when the WebRTC interface is ready.
  1588. // The first argument is the function to callback.\
  1589. // Throws an error if the first argument is not a function
  1590. AdapterJS.webRTCReady = function (callback) {
  1591. if (typeof callback !== 'function') {
  1592. throw new Error('Callback provided is not a function');
  1593. }
  1594. if (true === AdapterJS.onwebrtcreadyDone) {
  1595. // All WebRTC interfaces are ready, just call the callback
  1596. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  1597. } else {
  1598. // will be triggered automatically when your browser/plugin is ready.
  1599. AdapterJS.onwebrtcready = callback;
  1600. }
  1601. };
  1602. // Plugin namespace
  1603. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  1604. // The object to store plugin information
  1605. AdapterJS.WebRTCPlugin.pluginInfo = {
  1606. prefix : 'Tem',
  1607. plugName : 'TemWebRTCPlugin',
  1608. pluginId : 'plugin0',
  1609. type : 'application/x-temwebrtcplugin',
  1610. onload : '__TemWebRTCReady0',
  1611. portalLink : 'http://skylink.io/plugin/',
  1612. downloadLink : null, //set below
  1613. companyName: 'Temasys'
  1614. };
  1615. if(!!navigator.platform.match(/^Mac/i)) {
  1616. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  1617. }
  1618. else if(!!navigator.platform.match(/^Win/i)) {
  1619. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  1620. }
  1621. // Unique identifier of each opened page
  1622. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  1623. // Use this whenever you want to call the plugin.
  1624. AdapterJS.WebRTCPlugin.plugin = null;
  1625. // Set log level for the plugin once it is ready.
  1626. // The different values are
  1627. // This is an asynchronous function that will run when the plugin is ready
  1628. AdapterJS.WebRTCPlugin.setLogLevel = null;
  1629. // Defines webrtc's JS interface according to the plugin's implementation.
  1630. // Define plugin Browsers as WebRTC Interface.
  1631. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  1632. // This function detects whether or not a plugin is installed.
  1633. // Checks if Not IE (firefox, for example), else if it's IE,
  1634. // we're running IE and do something. If not it is not supported.
  1635. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  1636. // Lets adapter.js wait until the the document is ready before injecting the plugin
  1637. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  1638. // Inject the HTML DOM object element into the page.
  1639. AdapterJS.WebRTCPlugin.injectPlugin = null;
  1640. // States of readiness that the plugin goes through when
  1641. // being injected and stated
  1642. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  1643. NONE : 0, // no plugin use
  1644. INITIALIZING : 1, // Detected need for plugin
  1645. INJECTING : 2, // Injecting plugin
  1646. INJECTED: 3, // Plugin element injected but not usable yet
  1647. READY: 4 // Plugin ready to be used
  1648. };
  1649. // Current state of the plugin. You cannot use the plugin before this is
  1650. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  1651. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  1652. // True is AdapterJS.onwebrtcready was already called, false otherwise
  1653. // Used to make sure AdapterJS.onwebrtcready is only called once
  1654. AdapterJS.onwebrtcreadyDone = false;
  1655. // Log levels for the plugin.
  1656. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  1657. /*
  1658. Log outputs are prefixed in some cases.
  1659. INFO: Information reported by the plugin.
  1660. ERROR: Errors originating from within the plugin.
  1661. WEBRTC: Error originating from within the libWebRTC library
  1662. */
  1663. // From the least verbose to the most verbose
  1664. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  1665. NONE : 'NONE',
  1666. ERROR : 'ERROR',
  1667. WARNING : 'WARNING',
  1668. INFO: 'INFO',
  1669. VERBOSE: 'VERBOSE',
  1670. SENSITIVE: 'SENSITIVE'
  1671. };
  1672. // Does a waiting check before proceeding to load the plugin.
  1673. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  1674. // This methid will use an interval to wait for the plugin to be ready.
  1675. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  1676. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  1677. // This function will be called when plugin is ready. It sends necessary
  1678. // details to the plugin.
  1679. // The function will wait for the document to be ready and the set the
  1680. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  1681. // indicating that it can start being requested.
  1682. // This function is not in the IE/Safari condition brackets so that
  1683. // TemPluginLoaded function might be called on Chrome/Firefox.
  1684. // This function is the only private function that is not encapsulated to
  1685. // allow the plugin method to be called.
  1686. __TemWebRTCReady0 = function () {
  1687. if (document.readyState === 'complete') {
  1688. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1689. AdapterJS.maybeThroughWebRTCReady();
  1690. } else {
  1691. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  1692. if (document.readyState === 'complete') {
  1693. // TODO: update comments, we wait for the document to be ready
  1694. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  1695. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1696. AdapterJS.maybeThroughWebRTCReady();
  1697. }
  1698. }, 100);
  1699. }
  1700. };
  1701. AdapterJS.maybeThroughWebRTCReady = function() {
  1702. if (!AdapterJS.onwebrtcreadyDone) {
  1703. AdapterJS.onwebrtcreadyDone = true;
  1704. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  1705. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  1706. }
  1707. }
  1708. };
  1709. // Text namespace
  1710. AdapterJS.TEXT = {
  1711. PLUGIN: {
  1712. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  1713. 'to work on this browser.',
  1714. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  1715. BUTTON: 'Install Now'
  1716. },
  1717. REFRESH: {
  1718. REQUIRE_REFRESH: 'Please refresh page',
  1719. BUTTON: 'Refresh Page'
  1720. }
  1721. };
  1722. // The result of ice connection states.
  1723. // - starting: Ice connection is starting.
  1724. // - checking: Ice connection is checking.
  1725. // - connected Ice connection is connected.
  1726. // - completed Ice connection is connected.
  1727. // - done Ice connection has been completed.
  1728. // - disconnected Ice connection has been disconnected.
  1729. // - failed Ice connection has failed.
  1730. // - closed Ice connection is closed.
  1731. AdapterJS._iceConnectionStates = {
  1732. starting : 'starting',
  1733. checking : 'checking',
  1734. connected : 'connected',
  1735. completed : 'connected',
  1736. done : 'completed',
  1737. disconnected : 'disconnected',
  1738. failed : 'failed',
  1739. closed : 'closed'
  1740. };
  1741. //The IceConnection states that has been fired for each peer.
  1742. AdapterJS._iceConnectionFiredStates = [];
  1743. // Check if WebRTC Interface is defined.
  1744. AdapterJS.isDefined = null;
  1745. // This function helps to retrieve the webrtc detected browser information.
  1746. // This sets:
  1747. // - webrtcDetectedBrowser: The browser agent name.
  1748. // - webrtcDetectedVersion: The browser version.
  1749. // - webrtcDetectedType: The types of webRTC support.
  1750. // - 'moz': Mozilla implementation of webRTC.
  1751. // - 'webkit': WebKit implementation of webRTC.
  1752. // - 'plugin': Using the plugin implementation.
  1753. AdapterJS.parseWebrtcDetectedBrowser = function () {
  1754. var hasMatch, checkMatch = navigator.userAgent.match(
  1755. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  1756. if (/trident/i.test(checkMatch[1])) {
  1757. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  1758. webrtcDetectedBrowser = 'IE';
  1759. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  1760. } else if (checkMatch[1] === 'Chrome') {
  1761. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  1762. if (hasMatch !== null) {
  1763. webrtcDetectedBrowser = 'opera';
  1764. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  1765. }
  1766. }
  1767. if (navigator.userAgent.indexOf('Safari')) {
  1768. if (typeof InstallTrigger !== 'undefined') {
  1769. webrtcDetectedBrowser = 'firefox';
  1770. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  1771. webrtcDetectedBrowser = 'IE';
  1772. } else if (
  1773. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  1774. webrtcDetectedBrowser = 'safari';
  1775. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  1776. webrtcDetectedBrowser = 'opera';
  1777. } else if (!!window.chrome) {
  1778. webrtcDetectedBrowser = 'chrome';
  1779. }
  1780. }
  1781. if (!webrtcDetectedBrowser) {
  1782. webrtcDetectedVersion = checkMatch[1];
  1783. }
  1784. if (!webrtcDetectedVersion) {
  1785. try {
  1786. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  1787. [navigator.appName, navigator.appVersion, '-?'];
  1788. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  1789. checkMatch.splice(1, 1, hasMatch[1]);
  1790. }
  1791. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  1792. } catch (error) { }
  1793. }
  1794. };
  1795. // To fix configuration as some browsers does not support
  1796. // the 'urls' attribute.
  1797. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  1798. if (pcConfig === null) {
  1799. return;
  1800. }
  1801. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  1802. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  1803. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  1804. delete pcConfig.iceServers[i].urls;
  1805. }
  1806. }
  1807. };
  1808. AdapterJS.addEvent = function(elem, evnt, func) {
  1809. if (elem.addEventListener) { // W3C DOM
  1810. elem.addEventListener(evnt, func, false);
  1811. } else if (elem.attachEvent) {// OLD IE DOM
  1812. elem.attachEvent('on'+evnt, func);
  1813. } else { // No much to do
  1814. elem[evnt] = func;
  1815. }
  1816. };
  1817. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  1818. // only inject once the page is ready
  1819. if (document.readyState !== 'complete') {
  1820. return;
  1821. }
  1822. var w = window;
  1823. var i = document.createElement('iframe');
  1824. i.style.position = 'fixed';
  1825. i.style.top = '-41px';
  1826. i.style.left = 0;
  1827. i.style.right = 0;
  1828. i.style.width = '100%';
  1829. i.style.height = '40px';
  1830. i.style.backgroundColor = '#ffffe1';
  1831. i.style.border = 'none';
  1832. i.style.borderBottom = '1px solid #888888';
  1833. i.style.zIndex = '9999999';
  1834. if(typeof i.style.webkitTransition === 'string') {
  1835. i.style.webkitTransition = 'all .5s ease-out';
  1836. } else if(typeof i.style.transition === 'string') {
  1837. i.style.transition = 'all .5s ease-out';
  1838. }
  1839. document.body.appendChild(i);
  1840. c = (i.contentWindow) ? i.contentWindow :
  1841. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  1842. c.document.open();
  1843. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  1844. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  1845. 'middle; cursor: default;">' + text + '</span>');
  1846. if(buttonText && buttonLink) {
  1847. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  1848. c.document.close();
  1849. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  1850. if (!!displayRefreshBar) {
  1851. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  1852. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  1853. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  1854. }
  1855. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  1856. e.preventDefault();
  1857. try {
  1858. event.cancelBubble = true;
  1859. } catch(error) { }
  1860. var pluginInstallInterval = setInterval(function(){
  1861. if(! isIE) {
  1862. navigator.plugins.refresh(false);
  1863. }
  1864. AdapterJS.WebRTCPlugin.isPluginInstalled(
  1865. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  1866. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  1867. function() {
  1868. clearInterval(pluginInstallInterval);
  1869. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  1870. },
  1871. function() { //Does nothing because not used here
  1872. });
  1873. } , 500);
  1874. });
  1875. }else {
  1876. c.document.close();
  1877. }
  1878. AdapterJS.addEvent(c.document, 'click', function() {
  1879. w.document.body.removeChild(i);
  1880. });
  1881. setTimeout(function() {
  1882. if(typeof i.style.webkitTransform === 'string') {
  1883. i.style.webkitTransform = 'translateY(40px)';
  1884. } else if(typeof i.style.transform === 'string') {
  1885. i.style.transform = 'translateY(40px)';
  1886. } else {
  1887. i.style.top = '0px';
  1888. }
  1889. }, 300);
  1890. };
  1891. // -----------------------------------------------------------
  1892. // Detected webrtc implementation. Types are:
  1893. // - 'moz': Mozilla implementation of webRTC.
  1894. // - 'webkit': WebKit implementation of webRTC.
  1895. // - 'plugin': Using the plugin implementation.
  1896. webrtcDetectedType = null;
  1897. // Detected webrtc datachannel support. Types are:
  1898. // - 'SCTP': SCTP datachannel support.
  1899. // - 'RTP': RTP datachannel support.
  1900. webrtcDetectedDCSupport = null;
  1901. // Set the settings for creating DataChannels, MediaStream for
  1902. // Cross-browser compability.
  1903. // - This is only for SCTP based support browsers.
  1904. // the 'urls' attribute.
  1905. checkMediaDataChannelSettings =
  1906. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  1907. if (typeof callback !== 'function') {
  1908. return;
  1909. }
  1910. var beOfferer = true;
  1911. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  1912. // Nightly version does not require MozDontOfferDataChannel for interop
  1913. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  1914. var isPeerFirefox = peerBrowserAgent === 'firefox';
  1915. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  1916. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  1917. // Resends an updated version of constraints for MozDataChannel to work
  1918. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  1919. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  1920. try {
  1921. delete constraints.mandatory.MozDontOfferDataChannel;
  1922. } catch (error) {
  1923. console.error('Failed deleting MozDontOfferDataChannel');
  1924. console.error(error);
  1925. }
  1926. } else if ((isLocalFirefox && !isPeerFirefox)) {
  1927. constraints.mandatory.MozDontOfferDataChannel = true;
  1928. }
  1929. if (!isLocalFirefox) {
  1930. // temporary measure to remove Moz* constraints in non Firefox browsers
  1931. for (var prop in constraints.mandatory) {
  1932. if (constraints.mandatory.hasOwnProperty(prop)) {
  1933. if (prop.indexOf('Moz') !== -1) {
  1934. delete constraints.mandatory[prop];
  1935. }
  1936. }
  1937. }
  1938. }
  1939. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  1940. // interopability of the media stream
  1941. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  1942. beOfferer = false;
  1943. }
  1944. callback(beOfferer, constraints);
  1945. };
  1946. // Handles the differences for all browsers ice connection state output.
  1947. // - Tested outcomes are:
  1948. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  1949. // - Chrome (answerer) : 'checking' > 'connected'
  1950. // - Firefox (offerer) : 'checking' > 'connected'
  1951. // - Firefox (answerer): 'checking' > 'connected'
  1952. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  1953. if (typeof callback !== 'function') {
  1954. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  1955. return;
  1956. }
  1957. peerId = (peerId) ? peerId : 'peer';
  1958. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  1959. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  1960. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  1961. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  1962. AdapterJS._iceConnectionFiredStates[peerId] = [];
  1963. }
  1964. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  1965. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  1966. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  1967. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  1968. setTimeout(function () {
  1969. AdapterJS._iceConnectionFiredStates[peerId]
  1970. .push(AdapterJS._iceConnectionStates.done);
  1971. callback(AdapterJS._iceConnectionStates.done);
  1972. }, 1000);
  1973. }
  1974. callback(iceConnectionState);
  1975. }
  1976. return;
  1977. };
  1978. // Firefox:
  1979. // - Creates iceServer from the url for Firefox.
  1980. // - Create iceServer with stun url.
  1981. // - Create iceServer with turn url.
  1982. // - Ignore the transport parameter from TURN url for FF version <=27.
  1983. // - Return null for createIceServer if transport=tcp.
  1984. // - FF 27 and above supports transport parameters in TURN url,
  1985. // - So passing in the full url to create iceServer.
  1986. // Chrome:
  1987. // - Creates iceServer from the url for Chrome M33 and earlier.
  1988. // - Create iceServer with stun url.
  1989. // - Chrome M28 & above uses below TURN format.
  1990. // Plugin:
  1991. // - Creates Ice Server for Plugin Browsers
  1992. // - If Stun - Create iceServer with stun url.
  1993. // - Else - Create iceServer with turn url
  1994. // - This is a WebRTC Function
  1995. createIceServer = null;
  1996. // Firefox:
  1997. // - Creates IceServers for Firefox
  1998. // - Use .url for FireFox.
  1999. // - Multiple Urls support
  2000. // Chrome:
  2001. // - Creates iceServers from the urls for Chrome M34 and above.
  2002. // - .urls is supported since Chrome M34.
  2003. // - Multiple Urls support
  2004. // Plugin:
  2005. // - Creates Ice Servers for Plugin Browsers
  2006. // - Multiple Urls support
  2007. // - This is a WebRTC Function
  2008. createIceServers = null;
  2009. //------------------------------------------------------------
  2010. //The RTCPeerConnection object.
  2011. RTCPeerConnection = null;
  2012. // Creates RTCSessionDescription object for Plugin Browsers
  2013. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  2014. RTCSessionDescription : null;
  2015. // Creates RTCIceCandidate object for Plugin Browsers
  2016. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  2017. RTCIceCandidate : null;
  2018. // Get UserMedia (only difference is the prefix).
  2019. // Code from Adam Barth.
  2020. getUserMedia = null;
  2021. // Attach a media stream to an element.
  2022. attachMediaStream = null;
  2023. // Re-attach a media stream to an element.
  2024. reattachMediaStream = null;
  2025. // Detected browser agent name. Types are:
  2026. // - 'firefox': Firefox browser.
  2027. // - 'chrome': Chrome browser.
  2028. // - 'opera': Opera browser.
  2029. // - 'safari': Safari browser.
  2030. // - 'IE' - Internet Explorer browser.
  2031. webrtcDetectedBrowser = null;
  2032. // Detected browser version.
  2033. webrtcDetectedVersion = null;
  2034. // Check for browser types and react accordingly
  2035. if (navigator.mozGetUserMedia) {
  2036. webrtcDetectedBrowser = 'firefox';
  2037. webrtcDetectedVersion = parseInt(navigator
  2038. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2039. webrtcDetectedType = 'moz';
  2040. webrtcDetectedDCSupport = 'SCTP';
  2041. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2042. AdapterJS.maybeFixConfiguration(pcConfig);
  2043. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  2044. };
  2045. // The RTCSessionDescription object.
  2046. RTCSessionDescription = mozRTCSessionDescription;
  2047. window.RTCSessionDescription = RTCSessionDescription;
  2048. // The RTCIceCandidate object.
  2049. RTCIceCandidate = mozRTCIceCandidate;
  2050. window.RTCIceCandidate = RTCIceCandidate;
  2051. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2052. navigator.getUserMedia = window.getUserMedia;
  2053. // Shim for MediaStreamTrack.getSources.
  2054. MediaStreamTrack.getSources = function(successCb) {
  2055. setTimeout(function() {
  2056. var infos = [
  2057. { kind: 'audio', id: 'default', label:'', facing:'' },
  2058. { kind: 'video', id: 'default', label:'', facing:'' }
  2059. ];
  2060. successCb(infos);
  2061. }, 0);
  2062. };
  2063. createIceServer = function (url, username, password) {
  2064. var iceServer = null;
  2065. var url_parts = url.split(':');
  2066. if (url_parts[0].indexOf('stun') === 0) {
  2067. iceServer = { url : url };
  2068. } else if (url_parts[0].indexOf('turn') === 0) {
  2069. if (webrtcDetectedVersion < 27) {
  2070. var turn_url_parts = url.split('?');
  2071. if (turn_url_parts.length === 1 ||
  2072. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2073. iceServer = {
  2074. url : turn_url_parts[0],
  2075. credential : password,
  2076. username : username
  2077. };
  2078. }
  2079. } else {
  2080. iceServer = {
  2081. url : url,
  2082. credential : password,
  2083. username : username
  2084. };
  2085. }
  2086. }
  2087. return iceServer;
  2088. };
  2089. createIceServers = function (urls, username, password) {
  2090. var iceServers = [];
  2091. for (i = 0; i < urls.length; i++) {
  2092. var iceServer = createIceServer(urls[i], username, password);
  2093. if (iceServer !== null) {
  2094. iceServers.push(iceServer);
  2095. }
  2096. }
  2097. return iceServers;
  2098. };
  2099. attachMediaStream = function (element, stream) {
  2100. element.mozSrcObject = stream;
  2101. if (stream !== null)
  2102. element.play();
  2103. return element;
  2104. };
  2105. reattachMediaStream = function (to, from) {
  2106. to.mozSrcObject = from.mozSrcObject;
  2107. to.play();
  2108. return to;
  2109. };
  2110. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2111. if (!callback) {
  2112. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2113. ': 1 argument required, but only 0 present.');
  2114. }
  2115. return callback([]);
  2116. };
  2117. // Fake get{Video,Audio}Tracks
  2118. if (!MediaStream.prototype.getVideoTracks) {
  2119. MediaStream.prototype.getVideoTracks = function () {
  2120. return [];
  2121. };
  2122. }
  2123. if (!MediaStream.prototype.getAudioTracks) {
  2124. MediaStream.prototype.getAudioTracks = function () {
  2125. return [];
  2126. };
  2127. }
  2128. AdapterJS.maybeThroughWebRTCReady();
  2129. } else if (navigator.webkitGetUserMedia) {
  2130. webrtcDetectedBrowser = 'chrome';
  2131. webrtcDetectedType = 'webkit';
  2132. webrtcDetectedVersion = parseInt(navigator
  2133. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2134. // check if browser is opera 20+
  2135. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2136. if (checkIfOpera !== null) {
  2137. webrtcDetectedBrowser = 'opera';
  2138. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2139. }
  2140. // check browser datachannel support
  2141. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2142. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2143. webrtcDetectedDCSupport = 'SCTP';
  2144. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2145. webrtcDetectedVersion > 24) {
  2146. webrtcDetectedDCSupport = 'RTP';
  2147. } else {
  2148. webrtcDetectedDCSupport = '';
  2149. }
  2150. createIceServer = function (url, username, password) {
  2151. var iceServer = null;
  2152. var url_parts = url.split(':');
  2153. if (url_parts[0].indexOf('stun') === 0) {
  2154. iceServer = { 'url' : url };
  2155. } else if (url_parts[0].indexOf('turn') === 0) {
  2156. iceServer = {
  2157. 'url' : url,
  2158. 'credential' : password,
  2159. 'username' : username
  2160. };
  2161. }
  2162. return iceServer;
  2163. };
  2164. createIceServers = function (urls, username, password) {
  2165. var iceServers = [];
  2166. if (webrtcDetectedVersion >= 34) {
  2167. iceServers = {
  2168. 'urls' : urls,
  2169. 'credential' : password,
  2170. 'username' : username
  2171. };
  2172. } else {
  2173. for (i = 0; i < urls.length; i++) {
  2174. var iceServer = createIceServer(urls[i], username, password);
  2175. if (iceServer !== null) {
  2176. iceServers.push(iceServer);
  2177. }
  2178. }
  2179. }
  2180. return iceServers;
  2181. };
  2182. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2183. if (webrtcDetectedVersion < 34) {
  2184. AdapterJS.maybeFixConfiguration(pcConfig);
  2185. }
  2186. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2187. };
  2188. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2189. navigator.getUserMedia = window.getUserMedia;
  2190. attachMediaStream = function (element, stream) {
  2191. if (typeof element.srcObject !== 'undefined') {
  2192. element.srcObject = stream;
  2193. } else if (typeof element.mozSrcObject !== 'undefined') {
  2194. element.mozSrcObject = stream;
  2195. } else if (typeof element.src !== 'undefined') {
  2196. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2197. } else {
  2198. console.log('Error attaching stream to element.');
  2199. }
  2200. return element;
  2201. };
  2202. reattachMediaStream = function (to, from) {
  2203. to.src = from.src;
  2204. return to;
  2205. };
  2206. AdapterJS.maybeThroughWebRTCReady();
  2207. } else { // TRY TO USE PLUGIN
  2208. // IE 9 is not offering an implementation of console.log until you open a console
  2209. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2210. /* jshint -W020 */
  2211. console = {} || console;
  2212. // Implemented based on console specs from MDN
  2213. // You may override these functions
  2214. console.log = function (arg) {};
  2215. console.info = function (arg) {};
  2216. console.error = function (arg) {};
  2217. console.dir = function (arg) {};
  2218. console.exception = function (arg) {};
  2219. console.trace = function (arg) {};
  2220. console.warn = function (arg) {};
  2221. console.count = function (arg) {};
  2222. console.debug = function (arg) {};
  2223. console.count = function (arg) {};
  2224. console.time = function (arg) {};
  2225. console.timeEnd = function (arg) {};
  2226. console.group = function (arg) {};
  2227. console.groupCollapsed = function (arg) {};
  2228. console.groupEnd = function (arg) {};
  2229. /* jshint +W020 */
  2230. }
  2231. webrtcDetectedType = 'plugin';
  2232. webrtcDetectedDCSupport = 'plugin';
  2233. AdapterJS.parseWebrtcDetectedBrowser();
  2234. isIE = webrtcDetectedBrowser === 'IE';
  2235. /* jshint -W035 */
  2236. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2237. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2238. /* empty because it needs to prevent the function from running. */
  2239. }
  2240. };
  2241. /* jshint +W035 */
  2242. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2243. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2244. // Call immediately if possible
  2245. // Once the plugin is set, the code will always take this path
  2246. callback();
  2247. } else {
  2248. // otherwise start a 100ms interval
  2249. var checkPluginReadyState = setInterval(function () {
  2250. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2251. clearInterval(checkPluginReadyState);
  2252. callback();
  2253. }
  2254. }, 100);
  2255. }
  2256. };
  2257. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2258. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2259. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2260. });
  2261. };
  2262. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2263. // only inject once the page is ready
  2264. if (document.readyState !== 'complete') {
  2265. return;
  2266. }
  2267. // Prevent multiple injections
  2268. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2269. return;
  2270. }
  2271. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2272. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2273. var frag = document.createDocumentFragment();
  2274. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2275. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2276. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2277. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2278. '<param name="pluginId" value="' +
  2279. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2280. '<param name="windowless" value="false" /> ' +
  2281. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2282. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload +
  2283. '" />' +
  2284. // uncomment to be able to use virtual cams
  2285. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2286. '</object>';
  2287. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2288. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2289. }
  2290. document.body.appendChild(frag);
  2291. // Need to re-fetch the plugin
  2292. AdapterJS.WebRTCPlugin.plugin =
  2293. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2294. } else {
  2295. // Load Plugin
  2296. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2297. AdapterJS.WebRTCPlugin.plugin.id =
  2298. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2299. // IE will only start the plugin if it's ACTUALLY visible
  2300. if (isIE) {
  2301. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2302. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2303. } else { // The size of the plugin on Safari should be 0x0px
  2304. // so that the autorisation prompt is at the top
  2305. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2306. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2307. }
  2308. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2309. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2310. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2311. '<param name="pluginId" value="' +
  2312. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2313. '<param name="windowless" value="false" /> ' +
  2314. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2315. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">';
  2316. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2317. }
  2318. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2319. };
  2320. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2321. function (comName, plugName, installedCb, notInstalledCb) {
  2322. if (!isIE) {
  2323. var pluginArray = navigator.plugins;
  2324. for (var i = 0; i < pluginArray.length; i++) {
  2325. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2326. installedCb();
  2327. return;
  2328. }
  2329. }
  2330. notInstalledCb();
  2331. } else {
  2332. try {
  2333. var axo = new ActiveXObject(comName + '.' + plugName);
  2334. } catch (e) {
  2335. notInstalledCb();
  2336. return;
  2337. }
  2338. installedCb();
  2339. }
  2340. };
  2341. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2342. if (AdapterJS.WebRTCPlugin.pluginState ===
  2343. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2344. console.error("WebRTC interface has been defined already");
  2345. return;
  2346. }
  2347. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2348. AdapterJS.isDefined = function (variable) {
  2349. return variable !== null && variable !== undefined;
  2350. };
  2351. createIceServer = function (url, username, password) {
  2352. var iceServer = null;
  2353. var url_parts = url.split(':');
  2354. if (url_parts[0].indexOf('stun') === 0) {
  2355. iceServer = {
  2356. 'url' : url,
  2357. 'hasCredentials' : false
  2358. };
  2359. } else if (url_parts[0].indexOf('turn') === 0) {
  2360. iceServer = {
  2361. 'url' : url,
  2362. 'hasCredentials' : true,
  2363. 'credential' : password,
  2364. 'username' : username
  2365. };
  2366. }
  2367. return iceServer;
  2368. };
  2369. createIceServers = function (urls, username, password) {
  2370. var iceServers = [];
  2371. for (var i = 0; i < urls.length; ++i) {
  2372. iceServers.push(createIceServer(urls[i], username, password));
  2373. }
  2374. return iceServers;
  2375. };
  2376. RTCSessionDescription = function (info) {
  2377. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2378. return AdapterJS.WebRTCPlugin.plugin.
  2379. ConstructSessionDescription(info.type, info.sdp);
  2380. };
  2381. RTCPeerConnection = function (servers, constraints) {
  2382. var iceServers = null;
  2383. if (servers) {
  2384. iceServers = servers.iceServers;
  2385. for (var i = 0; i < iceServers.length; i++) {
  2386. if (iceServers[i].urls && !iceServers[i].url) {
  2387. iceServers[i].url = iceServers[i].urls;
  2388. }
  2389. iceServers[i].hasCredentials = AdapterJS.
  2390. isDefined(iceServers[i].username) &&
  2391. AdapterJS.isDefined(iceServers[i].credential);
  2392. }
  2393. }
  2394. var mandatory = (constraints && constraints.mandatory) ?
  2395. constraints.mandatory : null;
  2396. var optional = (constraints && constraints.optional) ?
  2397. constraints.optional : null;
  2398. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2399. return AdapterJS.WebRTCPlugin.plugin.
  2400. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2401. iceServers, mandatory, optional);
  2402. };
  2403. MediaStreamTrack = {};
  2404. MediaStreamTrack.getSources = function (callback) {
  2405. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2406. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2407. });
  2408. };
  2409. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2410. constraints.audio = constraints.audio || false;
  2411. constraints.video = constraints.video || false;
  2412. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2413. AdapterJS.WebRTCPlugin.plugin.
  2414. getUserMedia(constraints, successCallback, failureCallback);
  2415. });
  2416. };
  2417. window.navigator.getUserMedia = window.getUserMedia;
  2418. attachMediaStream = function (element, stream) {
  2419. if (!element || !element.parentNode) {
  2420. return;
  2421. }
  2422. var streamId
  2423. if (stream === null) {
  2424. streamId = '';
  2425. }
  2426. else {
  2427. stream.enableSoundTracks(true);
  2428. streamId = stream.id;
  2429. }
  2430. if (element.nodeName.toLowerCase() !== 'audio') {
  2431. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2432. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2433. var frag = document.createDocumentFragment();
  2434. var temp = document.createElement('div');
  2435. var classHTML = '';
  2436. if (element.className) {
  2437. classHTML = 'class="' + element.className + '" ';
  2438. } else if (element.attributes && element.attributes['class']) {
  2439. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2440. }
  2441. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2442. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2443. '<param name="pluginId" value="' + elementId + '" /> ' +
  2444. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2445. '<param name="windowless" value="true" /> ' +
  2446. '<param name="streamId" value="' + streamId + '" /> ' +
  2447. '</object>';
  2448. while (temp.firstChild) {
  2449. frag.appendChild(temp.firstChild);
  2450. }
  2451. var height = '';
  2452. var width = '';
  2453. if (element.getBoundingClientRect) {
  2454. var rectObject = element.getBoundingClientRect();
  2455. width = rectObject.width + 'px';
  2456. height = rectObject.height + 'px';
  2457. }
  2458. else if (element.width) {
  2459. width = element.width;
  2460. height = element.height;
  2461. } else {
  2462. // TODO: What scenario could bring us here?
  2463. }
  2464. element.parentNode.insertBefore(frag, element);
  2465. frag = document.getElementById(elementId);
  2466. frag.width = width;
  2467. frag.height = height;
  2468. element.parentNode.removeChild(element);
  2469. } else {
  2470. var children = element.children;
  2471. for (var i = 0; i !== children.length; ++i) {
  2472. if (children[i].name === 'streamId') {
  2473. children[i].value = streamId;
  2474. break;
  2475. }
  2476. }
  2477. element.setStreamId(streamId);
  2478. }
  2479. var newElement = document.getElementById(elementId);
  2480. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2481. if (isIE) { // on IE the event needs to be plugged manually
  2482. newElement.attachEvent('onplaying', newElement.onplaying);
  2483. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2484. newElement._TemOnClick = function (id) {
  2485. var arg = {
  2486. srcElement : document.getElementById(id)
  2487. };
  2488. newElement.onclick(arg);
  2489. };
  2490. }
  2491. return newElement;
  2492. } else {
  2493. return element;
  2494. }
  2495. };
  2496. reattachMediaStream = function (to, from) {
  2497. var stream = null;
  2498. var children = from.children;
  2499. for (var i = 0; i !== children.length; ++i) {
  2500. if (children[i].name === 'streamId') {
  2501. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2502. stream = AdapterJS.WebRTCPlugin.plugin
  2503. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2504. break;
  2505. }
  2506. }
  2507. if (stream !== null) {
  2508. return attachMediaStream(to, stream);
  2509. } else {
  2510. console.log('Could not find the stream associated with this element');
  2511. }
  2512. };
  2513. RTCIceCandidate = function (candidate) {
  2514. if (!candidate.sdpMid) {
  2515. candidate.sdpMid = '';
  2516. }
  2517. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2518. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2519. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2520. );
  2521. };
  2522. // inject plugin
  2523. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2524. AdapterJS.WebRTCPlugin.injectPlugin();
  2525. };
  2526. // This function will be called if the plugin is needed (browser different
  2527. // from Chrome or Firefox), but the plugin is not installed.
  2528. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2529. function() {
  2530. AdapterJS.addEvent(document,
  2531. 'readystatechange',
  2532. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2533. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2534. };
  2535. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2536. if (AdapterJS.options.hidePluginInstallPrompt) {
  2537. return;
  2538. }
  2539. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  2540. if(downloadLink) { // if download link
  2541. var popupString;
  2542. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  2543. popupString = 'This website requires you to install the ' +
  2544. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  2545. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  2546. ' WebRTC Plugin</a>' +
  2547. ' to work on this browser.';
  2548. } else { // no portal link, just print a generic explanation
  2549. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  2550. }
  2551. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  2552. } else { // no download link, just print a generic explanation
  2553. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  2554. }
  2555. };
  2556. // Try to detect the plugin and act accordingly
  2557. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2558. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2559. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2560. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  2561. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  2562. }
  2563. (function () {
  2564. 'use strict';
  2565. var baseGetUserMedia = null;
  2566. AdapterJS.TEXT.EXTENSION = {
  2567. REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
  2568. REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
  2569. REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
  2570. BUTTON_FF: 'Install Now',
  2571. BUTTON_CHROME: 'Go to Chrome Web Store'
  2572. };
  2573. var clone = function(obj) {
  2574. if (null == obj || "object" != typeof obj) return obj;
  2575. var copy = obj.constructor();
  2576. for (var attr in obj) {
  2577. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  2578. }
  2579. return copy;
  2580. };
  2581. if (window.navigator.mozGetUserMedia) {
  2582. baseGetUserMedia = window.navigator.getUserMedia;
  2583. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2584. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2585. // intercepting screensharing requests
  2586. if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
  2587. throw new Error('Only "screen" and "window" option is available as mediaSource');
  2588. }
  2589. var updatedConstraints = clone(constraints);
  2590. //constraints.video.mediaSource = constraints.video.mediaSource;
  2591. updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
  2592. // so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
  2593. // strange but this works anyway
  2594. var checkIfReady = setInterval(function () {
  2595. if (document.readyState === 'complete') {
  2596. clearInterval(checkIfReady);
  2597. baseGetUserMedia(updatedConstraints, successCb, function (error) {
  2598. if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
  2599. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
  2600. AdapterJS.TEXT.EXTENSION.BUTTON_FF,
  2601. 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
  2602. //window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
  2603. } else {
  2604. failureCb(error);
  2605. }
  2606. });
  2607. }
  2608. }, 1);
  2609. } else { // regular GetUserMediaRequest
  2610. baseGetUserMedia(constraints, successCb, failureCb);
  2611. }
  2612. };
  2613. getUserMedia = navigator.getUserMedia;
  2614. } else if (window.navigator.webkitGetUserMedia) {
  2615. baseGetUserMedia = window.navigator.getUserMedia;
  2616. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2617. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2618. if (window.webrtcDetectedBrowser !== 'chrome') {
  2619. throw new Error('Current browser does not support screensharing');
  2620. }
  2621. // would be fine since no methods
  2622. var updatedConstraints = clone(constraints);
  2623. var chromeCallback = function(error, sourceId) {
  2624. if(!error) {
  2625. updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
  2626. updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
  2627. updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
  2628. updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
  2629. if (sourceId) {
  2630. updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
  2631. }
  2632. delete updatedConstraints.video.mediaSource;
  2633. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2634. } else {
  2635. if (error === 'permission-denied') {
  2636. throw new Error('Permission denied for screen retrieval');
  2637. } else {
  2638. throw new Error('Failed retrieving selected screen');
  2639. }
  2640. }
  2641. };
  2642. var onIFrameCallback = function (event) {
  2643. if (!event.data) {
  2644. return;
  2645. }
  2646. if (event.data.chromeMediaSourceId) {
  2647. if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
  2648. chromeCallback('permission-denied');
  2649. } else {
  2650. chromeCallback(null, event.data.chromeMediaSourceId);
  2651. }
  2652. }
  2653. if (event.data.chromeExtensionStatus) {
  2654. if (event.data.chromeExtensionStatus === 'not-installed') {
  2655. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
  2656. AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
  2657. event.data.data, true, true);
  2658. } else {
  2659. chromeCallback(event.data.chromeExtensionStatus, null);
  2660. }
  2661. }
  2662. // this event listener is no more needed
  2663. window.removeEventListener('message', onIFrameCallback);
  2664. };
  2665. window.addEventListener('message', onIFrameCallback);
  2666. postFrameMessage({
  2667. captureSourceId: true
  2668. });
  2669. } else {
  2670. baseGetUserMedia(constraints, successCb, failureCb);
  2671. }
  2672. };
  2673. getUserMedia = navigator.getUserMedia;
  2674. } else {
  2675. baseGetUserMedia = window.navigator.getUserMedia;
  2676. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2677. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2678. // would be fine since no methods
  2679. var updatedConstraints = clone(constraints);
  2680. // wait for plugin to be ready
  2681. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2682. // check if screensharing feature is available
  2683. if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
  2684. !!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2685. // set the constraints
  2686. updatedConstraints.video.optional = updatedConstraints.video.optional || [];
  2687. updatedConstraints.video.optional.push({
  2688. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
  2689. });
  2690. delete updatedConstraints.video.mediaSource;
  2691. } else {
  2692. throw new Error('Your WebRTC plugin does not support screensharing');
  2693. }
  2694. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2695. });
  2696. } else {
  2697. baseGetUserMedia(constraints, successCb, failureCb);
  2698. }
  2699. };
  2700. getUserMedia = window.navigator.getUserMedia;
  2701. }
  2702. if (window.webrtcDetectedBrowser === 'chrome') {
  2703. var iframe = document.createElement('iframe');
  2704. iframe.onload = function() {
  2705. iframe.isLoaded = true;
  2706. };
  2707. iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
  2708. //'https://temasys-cdn.s3.amazonaws.com/skylink/extensions/detection-script-dev/detectRTC.html';
  2709. iframe.style.display = 'none';
  2710. (document.body || document.documentElement).appendChild(iframe);
  2711. var postFrameMessage = function (object) {
  2712. object = object || {};
  2713. if (!iframe.isLoaded) {
  2714. setTimeout(function () {
  2715. iframe.contentWindow.postMessage(object, '*');
  2716. }, 100);
  2717. return;
  2718. }
  2719. iframe.contentWindow.postMessage(object, '*');
  2720. };
  2721. }
  2722. })();
  2723. },{}],15:[function(require,module,exports){
  2724. function supportsLocalStorage() {
  2725. try {
  2726. return 'localStorage' in window && window.localStorage !== null;
  2727. } catch (e) {
  2728. console.log("localstorage is not supported");
  2729. return false;
  2730. }
  2731. }
  2732. function generateUniqueId() {
  2733. function _p8() {
  2734. return (Math.random().toString(16) + "000000000").substr(2, 8);
  2735. }
  2736. return _p8() + _p8() + _p8() + _p8();
  2737. }
  2738. function Settings(conferenceID) {
  2739. this.email = '';
  2740. this.displayName = '';
  2741. this.userId;
  2742. this.language = null;
  2743. this.confSettings = null;
  2744. if (supportsLocalStorage()) {
  2745. if(!window.localStorage.jitsiConferences)
  2746. window.localStorage.jitsiConferences = {}
  2747. if (!window.localStorage.jitsiConferences[conferenceID]) {
  2748. window.localStorage.jitsiConferences[conferenceID] = {}
  2749. }
  2750. this.confSettings = window.localStorage.jitsiConferences[conferenceID];
  2751. if(!this.confSettings.jitsiMeetId) {
  2752. this.confSettings.jitsiMeetId = generateUniqueId();
  2753. console.log("generated id",
  2754. this.confSettings.jitsiMeetId);
  2755. }
  2756. this.userId = this.confSettings.jitsiMeetId || '';
  2757. this.email = this.confSettings.email || '';
  2758. this.displayName = this.confSettings.displayname || '';
  2759. this.language = this.confSettings.language;
  2760. } else {
  2761. console.log("local storage is not supported");
  2762. this.userId = generateUniqueId();
  2763. }
  2764. }
  2765. Settings.prototype.setDisplayName = function (newDisplayName) {
  2766. this.displayName = newDisplayName;
  2767. if(this.confSettings != null)
  2768. this.confSettings.displayname = displayName;
  2769. return this.displayName;
  2770. },
  2771. Settings.prototype.setEmail = function (newEmail) {
  2772. this.email = newEmail;
  2773. if(this.confSettings != null)
  2774. this.confSettings.email = newEmail;
  2775. return this.email;
  2776. },
  2777. Settings.prototype.getSettings = function () {
  2778. return {
  2779. email: this.email,
  2780. displayName: this.displayName,
  2781. uid: this.userId,
  2782. language: this.language
  2783. };
  2784. },
  2785. Settings.prototype.setLanguage = function (lang) {
  2786. this.language = lang;
  2787. if(this.confSettings != null)
  2788. this.confSettings.language = lang;
  2789. }
  2790. module.exports = Settings;
  2791. },{}],16:[function(require,module,exports){
  2792. SDPUtil = {
  2793. filter_special_chars: function (text) {
  2794. return text.replace(/[\\\/\{,\}\+]/g, "");
  2795. },
  2796. iceparams: function (mediadesc, sessiondesc) {
  2797. var data = null;
  2798. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  2799. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  2800. data = {
  2801. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  2802. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  2803. };
  2804. }
  2805. return data;
  2806. },
  2807. parse_iceufrag: function (line) {
  2808. return line.substring(12);
  2809. },
  2810. build_iceufrag: function (frag) {
  2811. return 'a=ice-ufrag:' + frag;
  2812. },
  2813. parse_icepwd: function (line) {
  2814. return line.substring(10);
  2815. },
  2816. build_icepwd: function (pwd) {
  2817. return 'a=ice-pwd:' + pwd;
  2818. },
  2819. parse_mid: function (line) {
  2820. return line.substring(6);
  2821. },
  2822. parse_mline: function (line) {
  2823. var parts = line.substring(2).split(' '),
  2824. data = {};
  2825. data.media = parts.shift();
  2826. data.port = parts.shift();
  2827. data.proto = parts.shift();
  2828. if (parts[parts.length - 1] === '') { // trailing whitespace
  2829. parts.pop();
  2830. }
  2831. data.fmt = parts;
  2832. return data;
  2833. },
  2834. build_mline: function (mline) {
  2835. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  2836. },
  2837. parse_rtpmap: function (line) {
  2838. var parts = line.substring(9).split(' '),
  2839. data = {};
  2840. data.id = parts.shift();
  2841. parts = parts[0].split('/');
  2842. data.name = parts.shift();
  2843. data.clockrate = parts.shift();
  2844. data.channels = parts.length ? parts.shift() : '1';
  2845. return data;
  2846. },
  2847. /**
  2848. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  2849. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  2850. * @returns [SCTP port number, protocol, streams]
  2851. */
  2852. parse_sctpmap: function (line)
  2853. {
  2854. var parts = line.substring(10).split(' ');
  2855. var sctpPort = parts[0];
  2856. var protocol = parts[1];
  2857. // Stream count is optional
  2858. var streamCount = parts.length > 2 ? parts[2] : null;
  2859. return [sctpPort, protocol, streamCount];// SCTP port
  2860. },
  2861. build_rtpmap: function (el) {
  2862. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  2863. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  2864. line += '/' + el.getAttribute('channels');
  2865. }
  2866. return line;
  2867. },
  2868. parse_crypto: function (line) {
  2869. var parts = line.substring(9).split(' '),
  2870. data = {};
  2871. data.tag = parts.shift();
  2872. data['crypto-suite'] = parts.shift();
  2873. data['key-params'] = parts.shift();
  2874. if (parts.length) {
  2875. data['session-params'] = parts.join(' ');
  2876. }
  2877. return data;
  2878. },
  2879. parse_fingerprint: function (line) { // RFC 4572
  2880. var parts = line.substring(14).split(' '),
  2881. data = {};
  2882. data.hash = parts.shift();
  2883. data.fingerprint = parts.shift();
  2884. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  2885. return data;
  2886. },
  2887. parse_fmtp: function (line) {
  2888. var parts = line.split(' '),
  2889. i, key, value,
  2890. data = [];
  2891. parts.shift();
  2892. parts = parts.join(' ').split(';');
  2893. for (i = 0; i < parts.length; i++) {
  2894. key = parts[i].split('=')[0];
  2895. while (key.length && key[0] == ' ') {
  2896. key = key.substring(1);
  2897. }
  2898. value = parts[i].split('=')[1];
  2899. if (key && value) {
  2900. data.push({name: key, value: value});
  2901. } else if (key) {
  2902. // rfc 4733 (DTMF) style stuff
  2903. data.push({name: '', value: key});
  2904. }
  2905. }
  2906. return data;
  2907. },
  2908. parse_icecandidate: function (line) {
  2909. var candidate = {},
  2910. elems = line.split(' ');
  2911. candidate.foundation = elems[0].substring(12);
  2912. candidate.component = elems[1];
  2913. candidate.protocol = elems[2].toLowerCase();
  2914. candidate.priority = elems[3];
  2915. candidate.ip = elems[4];
  2916. candidate.port = elems[5];
  2917. // elems[6] => "typ"
  2918. candidate.type = elems[7];
  2919. candidate.generation = 0; // default value, may be overwritten below
  2920. for (var i = 8; i < elems.length; i += 2) {
  2921. switch (elems[i]) {
  2922. case 'raddr':
  2923. candidate['rel-addr'] = elems[i + 1];
  2924. break;
  2925. case 'rport':
  2926. candidate['rel-port'] = elems[i + 1];
  2927. break;
  2928. case 'generation':
  2929. candidate.generation = elems[i + 1];
  2930. break;
  2931. case 'tcptype':
  2932. candidate.tcptype = elems[i + 1];
  2933. break;
  2934. default: // TODO
  2935. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  2936. }
  2937. }
  2938. candidate.network = '1';
  2939. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  2940. return candidate;
  2941. },
  2942. build_icecandidate: function (cand) {
  2943. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  2944. line += ' ';
  2945. switch (cand.type) {
  2946. case 'srflx':
  2947. case 'prflx':
  2948. case 'relay':
  2949. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  2950. line += 'raddr';
  2951. line += ' ';
  2952. line += cand['rel-addr'];
  2953. line += ' ';
  2954. line += 'rport';
  2955. line += ' ';
  2956. line += cand['rel-port'];
  2957. line += ' ';
  2958. }
  2959. break;
  2960. }
  2961. if (cand.hasOwnAttribute('tcptype')) {
  2962. line += 'tcptype';
  2963. line += ' ';
  2964. line += cand.tcptype;
  2965. line += ' ';
  2966. }
  2967. line += 'generation';
  2968. line += ' ';
  2969. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  2970. return line;
  2971. },
  2972. parse_ssrc: function (desc) {
  2973. // proprietary mapping of a=ssrc lines
  2974. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  2975. // and parse according to that
  2976. var lines = desc.split('\r\n'),
  2977. data = {};
  2978. for (var i = 0; i < lines.length; i++) {
  2979. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  2980. var idx = lines[i].indexOf(' ');
  2981. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  2982. }
  2983. }
  2984. return data;
  2985. },
  2986. parse_rtcpfb: function (line) {
  2987. var parts = line.substr(10).split(' ');
  2988. var data = {};
  2989. data.pt = parts.shift();
  2990. data.type = parts.shift();
  2991. data.params = parts;
  2992. return data;
  2993. },
  2994. parse_extmap: function (line) {
  2995. var parts = line.substr(9).split(' ');
  2996. var data = {};
  2997. data.value = parts.shift();
  2998. if (data.value.indexOf('/') != -1) {
  2999. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  3000. data.value = data.value.substr(0, data.value.indexOf('/'));
  3001. } else {
  3002. data.direction = 'both';
  3003. }
  3004. data.uri = parts.shift();
  3005. data.params = parts;
  3006. return data;
  3007. },
  3008. find_line: function (haystack, needle, sessionpart) {
  3009. var lines = haystack.split('\r\n');
  3010. for (var i = 0; i < lines.length; i++) {
  3011. if (lines[i].substring(0, needle.length) == needle) {
  3012. return lines[i];
  3013. }
  3014. }
  3015. if (!sessionpart) {
  3016. return false;
  3017. }
  3018. // search session part
  3019. lines = sessionpart.split('\r\n');
  3020. for (var j = 0; j < lines.length; j++) {
  3021. if (lines[j].substring(0, needle.length) == needle) {
  3022. return lines[j];
  3023. }
  3024. }
  3025. return false;
  3026. },
  3027. find_lines: function (haystack, needle, sessionpart) {
  3028. var lines = haystack.split('\r\n'),
  3029. needles = [];
  3030. for (var i = 0; i < lines.length; i++) {
  3031. if (lines[i].substring(0, needle.length) == needle)
  3032. needles.push(lines[i]);
  3033. }
  3034. if (needles.length || !sessionpart) {
  3035. return needles;
  3036. }
  3037. // search session part
  3038. lines = sessionpart.split('\r\n');
  3039. for (var j = 0; j < lines.length; j++) {
  3040. if (lines[j].substring(0, needle.length) == needle) {
  3041. needles.push(lines[j]);
  3042. }
  3043. }
  3044. return needles;
  3045. },
  3046. candidateToJingle: function (line) {
  3047. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  3048. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  3049. if (line.indexOf('candidate:') === 0) {
  3050. line = 'a=' + line;
  3051. } else if (line.substring(0, 12) != 'a=candidate:') {
  3052. console.log('parseCandidate called with a line that is not a candidate line');
  3053. console.log(line);
  3054. return null;
  3055. }
  3056. if (line.substring(line.length - 2) == '\r\n') // chomp it
  3057. line = line.substring(0, line.length - 2);
  3058. var candidate = {},
  3059. elems = line.split(' '),
  3060. i;
  3061. if (elems[6] != 'typ') {
  3062. console.log('did not find typ in the right place');
  3063. console.log(line);
  3064. return null;
  3065. }
  3066. candidate.foundation = elems[0].substring(12);
  3067. candidate.component = elems[1];
  3068. candidate.protocol = elems[2].toLowerCase();
  3069. candidate.priority = elems[3];
  3070. candidate.ip = elems[4];
  3071. candidate.port = elems[5];
  3072. // elems[6] => "typ"
  3073. candidate.type = elems[7];
  3074. candidate.generation = '0'; // default, may be overwritten below
  3075. for (i = 8; i < elems.length; i += 2) {
  3076. switch (elems[i]) {
  3077. case 'raddr':
  3078. candidate['rel-addr'] = elems[i + 1];
  3079. break;
  3080. case 'rport':
  3081. candidate['rel-port'] = elems[i + 1];
  3082. break;
  3083. case 'generation':
  3084. candidate.generation = elems[i + 1];
  3085. break;
  3086. case 'tcptype':
  3087. candidate.tcptype = elems[i + 1];
  3088. break;
  3089. default: // TODO
  3090. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  3091. }
  3092. }
  3093. candidate.network = '1';
  3094. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  3095. return candidate;
  3096. },
  3097. candidateFromJingle: function (cand) {
  3098. var line = 'a=candidate:';
  3099. line += cand.getAttribute('foundation');
  3100. line += ' ';
  3101. line += cand.getAttribute('component');
  3102. line += ' ';
  3103. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  3104. line += ' ';
  3105. line += cand.getAttribute('priority');
  3106. line += ' ';
  3107. line += cand.getAttribute('ip');
  3108. line += ' ';
  3109. line += cand.getAttribute('port');
  3110. line += ' ';
  3111. line += 'typ';
  3112. line += ' ' + cand.getAttribute('type');
  3113. line += ' ';
  3114. switch (cand.getAttribute('type')) {
  3115. case 'srflx':
  3116. case 'prflx':
  3117. case 'relay':
  3118. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  3119. line += 'raddr';
  3120. line += ' ';
  3121. line += cand.getAttribute('rel-addr');
  3122. line += ' ';
  3123. line += 'rport';
  3124. line += ' ';
  3125. line += cand.getAttribute('rel-port');
  3126. line += ' ';
  3127. }
  3128. break;
  3129. }
  3130. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  3131. line += 'tcptype';
  3132. line += ' ';
  3133. line += cand.getAttribute('tcptype');
  3134. line += ' ';
  3135. }
  3136. line += 'generation';
  3137. line += ' ';
  3138. line += cand.getAttribute('generation') || '0';
  3139. return line + '\r\n';
  3140. }
  3141. };
  3142. module.exports = SDPUtil;
  3143. },{}],17:[function(require,module,exports){
  3144. /* global $, $iq, APP, config, messageHandler,
  3145. roomName, sessionTerminated, Strophe, Util */
  3146. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  3147. var Settings = require("../settings/Settings");
  3148. var AuthenticationEvents
  3149. = require("../../service/authentication/AuthenticationEvents");
  3150. /**
  3151. * Contains logic responsible for enabling/disabling functionality available
  3152. * only to moderator users.
  3153. */
  3154. var connection = null;
  3155. var focusUserJid;
  3156. function createExpBackoffTimer(step) {
  3157. var count = 1;
  3158. return function (reset) {
  3159. // Reset call
  3160. if (reset) {
  3161. count = 1;
  3162. return;
  3163. }
  3164. // Calculate next timeout
  3165. var timeout = Math.pow(2, count - 1);
  3166. count += 1;
  3167. return timeout * step;
  3168. };
  3169. }
  3170. var getNextTimeout = createExpBackoffTimer(1000);
  3171. var getNextErrorTimeout = createExpBackoffTimer(1000);
  3172. // External authentication stuff
  3173. var externalAuthEnabled = false;
  3174. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  3175. // it will be enabled automatically if focus detects the component through
  3176. // service discovery.
  3177. var sipGatewayEnabled = null;
  3178. var eventEmitter = null;
  3179. var Moderator = {
  3180. isModerator: function () {
  3181. return connection && connection.emuc.isModerator();
  3182. },
  3183. isPeerModerator: function (peerJid) {
  3184. return connection &&
  3185. connection.emuc.getMemberRole(peerJid) === 'moderator';
  3186. },
  3187. isExternalAuthEnabled: function () {
  3188. return externalAuthEnabled;
  3189. },
  3190. isSipGatewayEnabled: function () {
  3191. return sipGatewayEnabled;
  3192. },
  3193. setConnection: function (con) {
  3194. connection = con;
  3195. },
  3196. init: function (xmpp, emitter) {
  3197. this.xmppService = xmpp;
  3198. sipGatewayEnabled = this.xmppService.options.hosts.call_control !== undefined;
  3199. eventEmitter = emitter;
  3200. // Message listener that talks to POPUP window
  3201. function listener(event) {
  3202. if (event.data && event.data.sessionId) {
  3203. if (event.origin !== window.location.origin) {
  3204. console.warn("Ignoring sessionId from different origin: " +
  3205. event.origin);
  3206. return;
  3207. }
  3208. localStorage.setItem('sessionId', event.data.sessionId);
  3209. // After popup is closed we will authenticate
  3210. }
  3211. }
  3212. // Register
  3213. if (window.addEventListener) {
  3214. window.addEventListener("message", listener, false);
  3215. } else {
  3216. window.attachEvent("onmessage", listener);
  3217. }
  3218. },
  3219. onMucMemberLeft: function (jid) {
  3220. console.info("Someone left is it focus ? " + jid);
  3221. var resource = Strophe.getResourceFromJid(jid);
  3222. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  3223. console.info(
  3224. "Focus has left the room - leaving conference");
  3225. //hangUp();
  3226. // We'd rather reload to have everything re-initialized
  3227. // FIXME: show some message before reload
  3228. location.reload();
  3229. }
  3230. },
  3231. setFocusUserJid: function (focusJid) {
  3232. if (!focusUserJid) {
  3233. focusUserJid = focusJid;
  3234. console.info("Focus jid set to: " + focusUserJid);
  3235. }
  3236. },
  3237. getFocusUserJid: function () {
  3238. return focusUserJid;
  3239. },
  3240. getFocusComponent: function () {
  3241. // Get focus component address
  3242. var focusComponent = this.xmppService.options.hosts.focus;
  3243. // If not specified use default: 'focus.domain'
  3244. if (!focusComponent) {
  3245. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  3246. }
  3247. return focusComponent;
  3248. },
  3249. createConferenceIq: function (roomName) {
  3250. // Generate create conference IQ
  3251. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  3252. // Session Id used for authentication
  3253. var sessionId = localStorage.getItem('sessionId');
  3254. var machineUID = Settings.getSettings().uid;
  3255. console.info(
  3256. "Session ID: " + sessionId + " machine UID: " + machineUID);
  3257. elem.c('conference', {
  3258. xmlns: 'http://jitsi.org/protocol/focus',
  3259. room: roomName,
  3260. 'machine-uid': machineUID
  3261. });
  3262. if (sessionId) {
  3263. elem.attrs({ 'session-id': sessionId});
  3264. }
  3265. if (this.xmppService.options.hosts.bridge !== undefined) {
  3266. elem.c(
  3267. 'property',
  3268. { name: 'bridge', value: this.xmppService.options.hosts.bridge})
  3269. .up();
  3270. }
  3271. // Tell the focus we have Jigasi configured
  3272. if (this.xmppService.options.hosts.call_control !== undefined) {
  3273. elem.c(
  3274. 'property',
  3275. { name: 'call_control', value: this.xmppService.options.hosts.call_control})
  3276. .up();
  3277. }
  3278. if (this.xmppService.options.channelLastN !== undefined) {
  3279. elem.c(
  3280. 'property',
  3281. { name: 'channelLastN', value: this.xmppService.options.channelLastN})
  3282. .up();
  3283. }
  3284. if (this.xmppService.options.adaptiveLastN !== undefined) {
  3285. elem.c(
  3286. 'property',
  3287. { name: 'adaptiveLastN', value: this.xmppService.options.adaptiveLastN})
  3288. .up();
  3289. }
  3290. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  3291. elem.c(
  3292. 'property',
  3293. { name: 'adaptiveSimulcast', value: this.xmppService.options.adaptiveSimulcast})
  3294. .up();
  3295. }
  3296. if (this.xmppService.options.openSctp !== undefined) {
  3297. elem.c(
  3298. 'property',
  3299. { name: 'openSctp', value: this.xmppService.options.openSctp})
  3300. .up();
  3301. }
  3302. if(this.xmppService.options.startAudioMuted !== undefined)
  3303. {
  3304. elem.c(
  3305. 'property',
  3306. { name: 'startAudioMuted', value: this.xmppService.options.startAudioMuted})
  3307. .up();
  3308. }
  3309. if(this.xmppService.options.startVideoMuted !== undefined)
  3310. {
  3311. elem.c(
  3312. 'property',
  3313. { name: 'startVideoMuted', value: this.xmppService.options.startVideoMuted})
  3314. .up();
  3315. }
  3316. elem.c(
  3317. 'property',
  3318. { name: 'simulcastMode', value: 'rewriting'})
  3319. .up();
  3320. elem.up();
  3321. return elem;
  3322. },
  3323. parseSessionId: function (resultIq) {
  3324. var sessionId = $(resultIq).find('conference').attr('session-id');
  3325. if (sessionId) {
  3326. console.info('Received sessionId: ' + sessionId);
  3327. localStorage.setItem('sessionId', sessionId);
  3328. }
  3329. },
  3330. parseConfigOptions: function (resultIq) {
  3331. Moderator.setFocusUserJid(
  3332. $(resultIq).find('conference').attr('focusjid'));
  3333. var authenticationEnabled
  3334. = $(resultIq).find(
  3335. '>conference>property' +
  3336. '[name=\'authentication\'][value=\'true\']').length > 0;
  3337. console.info("Authentication enabled: " + authenticationEnabled);
  3338. externalAuthEnabled = $(resultIq).find(
  3339. '>conference>property' +
  3340. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  3341. console.info('External authentication enabled: ' + externalAuthEnabled);
  3342. if (!externalAuthEnabled) {
  3343. // We expect to receive sessionId in 'internal' authentication mode
  3344. Moderator.parseSessionId(resultIq);
  3345. }
  3346. var authIdentity = $(resultIq).find('>conference').attr('identity');
  3347. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  3348. authenticationEnabled, authIdentity);
  3349. // Check if focus has auto-detected Jigasi component(this will be also
  3350. // included if we have passed our host from the config)
  3351. if ($(resultIq).find(
  3352. '>conference>property' +
  3353. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  3354. sipGatewayEnabled = true;
  3355. }
  3356. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  3357. },
  3358. // FIXME: we need to show the fact that we're waiting for the focus
  3359. // to the user(or that focus is not available)
  3360. allocateConferenceFocus: function (roomName, callback) {
  3361. // Try to use focus user JID from the config
  3362. Moderator.setFocusUserJid(this.xmppService.options.focusUserJid);
  3363. // Send create conference IQ
  3364. var iq = Moderator.createConferenceIq(roomName);
  3365. var self = this;
  3366. connection.sendIQ(
  3367. iq,
  3368. function (result) {
  3369. // Setup config options
  3370. Moderator.parseConfigOptions(result);
  3371. if ('true' === $(result).find('conference').attr('ready')) {
  3372. // Reset both timers
  3373. getNextTimeout(true);
  3374. getNextErrorTimeout(true);
  3375. // Exec callback
  3376. callback();
  3377. } else {
  3378. var waitMs = getNextTimeout();
  3379. console.info("Waiting for the focus... " + waitMs);
  3380. // Reset error timeout
  3381. getNextErrorTimeout(true);
  3382. window.setTimeout(
  3383. function () {
  3384. Moderator.allocateConferenceFocus(
  3385. roomName, callback);
  3386. }, waitMs);
  3387. }
  3388. },
  3389. function (error) {
  3390. // Invalid session ? remove and try again
  3391. // without session ID to get a new one
  3392. var invalidSession
  3393. = $(error).find('>error>session-invalid').length;
  3394. if (invalidSession) {
  3395. console.info("Session expired! - removing");
  3396. localStorage.removeItem("sessionId");
  3397. }
  3398. if ($(error).find('>error>graceful-shutdown').length) {
  3399. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  3400. return;
  3401. }
  3402. // Check for error returned by the reservation system
  3403. var reservationErr = $(error).find('>error>reservation-error');
  3404. if (reservationErr.length) {
  3405. // Trigger error event
  3406. var errorCode = reservationErr.attr('error-code');
  3407. var errorMsg;
  3408. if ($(error).find('>error>text')) {
  3409. errorMsg = $(error).find('>error>text').text();
  3410. }
  3411. eventEmitter.emit(
  3412. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  3413. return;
  3414. }
  3415. // Not authorized to create new room
  3416. if ($(error).find('>error>not-authorized').length) {
  3417. console.warn("Unauthorized to start the conference", error);
  3418. var toDomain
  3419. = Strophe.getDomainFromJid(error.getAttribute('to'));
  3420. if (toDomain !== this.xmppService.options.hosts.anonymousdomain) {
  3421. // FIXME: "is external" should come either from
  3422. // the focus or config.js
  3423. externalAuthEnabled = true;
  3424. }
  3425. eventEmitter.emit(
  3426. XMPPEvents.AUTHENTICATION_REQUIRED,
  3427. function () {
  3428. Moderator.allocateConferenceFocus(
  3429. roomName, callback);
  3430. });
  3431. return;
  3432. }
  3433. var waitMs = getNextErrorTimeout();
  3434. console.error("Focus error, retry after " + waitMs, error);
  3435. // Show message
  3436. var focusComponent = Moderator.getFocusComponent();
  3437. var retrySec = waitMs / 1000;
  3438. // FIXME: message is duplicated ?
  3439. // Do not show in case of session invalid
  3440. // which means just a retry
  3441. if (!invalidSession) {
  3442. eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  3443. focusComponent, retrySec);
  3444. }
  3445. // Reset response timeout
  3446. getNextTimeout(true);
  3447. window.setTimeout(
  3448. function () {
  3449. Moderator.allocateConferenceFocus(roomName, callback);
  3450. }, waitMs);
  3451. }
  3452. );
  3453. },
  3454. getLoginUrl: function (roomName, urlCallback) {
  3455. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  3456. iq.c('login-url', {
  3457. xmlns: 'http://jitsi.org/protocol/focus',
  3458. room: roomName,
  3459. 'machine-uid': Settings.getSettings().uid
  3460. });
  3461. connection.sendIQ(
  3462. iq,
  3463. function (result) {
  3464. var url = $(result).find('login-url').attr('url');
  3465. url = url = decodeURIComponent(url);
  3466. if (url) {
  3467. console.info("Got auth url: " + url);
  3468. urlCallback(url);
  3469. } else {
  3470. console.error(
  3471. "Failed to get auth url from the focus", result);
  3472. }
  3473. },
  3474. function (error) {
  3475. console.error("Get auth url error", error);
  3476. }
  3477. );
  3478. },
  3479. getPopupLoginUrl: function (roomName, urlCallback) {
  3480. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  3481. iq.c('login-url', {
  3482. xmlns: 'http://jitsi.org/protocol/focus',
  3483. room: roomName,
  3484. 'machine-uid': Settings.getSettings().uid,
  3485. popup: true
  3486. });
  3487. connection.sendIQ(
  3488. iq,
  3489. function (result) {
  3490. var url = $(result).find('login-url').attr('url');
  3491. url = url = decodeURIComponent(url);
  3492. if (url) {
  3493. console.info("Got POPUP auth url: " + url);
  3494. urlCallback(url);
  3495. } else {
  3496. console.error(
  3497. "Failed to get POPUP auth url from the focus", result);
  3498. }
  3499. },
  3500. function (error) {
  3501. console.error('Get POPUP auth url error', error);
  3502. }
  3503. );
  3504. },
  3505. logout: function (callback) {
  3506. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  3507. var sessionId = localStorage.getItem('sessionId');
  3508. if (!sessionId) {
  3509. callback();
  3510. return;
  3511. }
  3512. iq.c('logout', {
  3513. xmlns: 'http://jitsi.org/protocol/focus',
  3514. 'session-id': sessionId
  3515. });
  3516. connection.sendIQ(
  3517. iq,
  3518. function (result) {
  3519. var logoutUrl = $(result).find('logout').attr('logout-url');
  3520. if (logoutUrl) {
  3521. logoutUrl = decodeURIComponent(logoutUrl);
  3522. }
  3523. console.info("Log out OK, url: " + logoutUrl, result);
  3524. localStorage.removeItem('sessionId');
  3525. callback(logoutUrl);
  3526. },
  3527. function (error) {
  3528. console.error("Logout error", error);
  3529. }
  3530. );
  3531. }
  3532. };
  3533. module.exports = Moderator;
  3534. },{"../../service/authentication/AuthenticationEvents":45,"../../service/xmpp/XMPPEvents":47,"../settings/Settings":15}],18:[function(require,module,exports){
  3535. /* jshint -W117 */
  3536. /* a simple MUC connection plugin
  3537. * can only handle a single MUC room
  3538. */
  3539. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  3540. var Moderator = require("./moderator");
  3541. var RTC = require("../RTC/RTC");
  3542. var parser = {
  3543. packet2JSON: function (packet, nodes) {
  3544. var self = this;
  3545. $(packet).children().each(function (index) {
  3546. var tagName = $(this).prop("tagName");
  3547. var node = {}
  3548. node["tagName"] = tagName;
  3549. node.attributes = {};
  3550. $($(this)[0].attributes).each(function( index, attr ) {
  3551. node.attributes[ attr.name ] = attr.value;
  3552. } );
  3553. var text = Strophe.getText($(this)[0]);
  3554. if(text)
  3555. node.value = text;
  3556. node.children = [];
  3557. nodes.push(node);
  3558. self.packet2JSON($(this), node.children);
  3559. })
  3560. },
  3561. JSON2packet: function (nodes, packet) {
  3562. for(var i = 0; i < nodes.length; i++)
  3563. {
  3564. var node = nodes[i];
  3565. if(!node || node === null){
  3566. continue;
  3567. }
  3568. packet.c(node.tagName, node.attributes);
  3569. if(node.value)
  3570. packet.t(node.value);
  3571. if(node.children)
  3572. this.JSON2packet(node.children, packet);
  3573. packet.up();
  3574. }
  3575. packet.up();
  3576. }
  3577. };
  3578. function ChatRoom(connection, jid, password, XMPP, eventEmitter)
  3579. {
  3580. this.eventEmitter = eventEmitter;
  3581. this.xmpp = XMPP;
  3582. this.connection = connection;
  3583. this.roomjid = Strophe.getBareJidFromJid(jid);
  3584. this.myroomjid = jid;
  3585. this.password = password;
  3586. console.info("Joined MUC as " + this.myroomjid);
  3587. this.members = {};
  3588. this.presMap = {};
  3589. this.joined = false;
  3590. this.role = null;
  3591. this.focusMucJid = null;
  3592. this.bridgeIsDown = false;
  3593. this.initPresenceMap();
  3594. }
  3595. ChatRoom.prototype.initPresenceMap = function () {
  3596. this.presMap['to'] = this.myroomjid;
  3597. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  3598. this.presMap["nodes"] = [];
  3599. if (RTC.localAudio && RTC.localAudio.isMuted()) {
  3600. this.nodes.push({
  3601. tagName: "audiomuted",
  3602. attributes: {xmlns: "http://jitsi.org/jitmeet/audio"},
  3603. value: "true"});
  3604. }
  3605. if (RTC.localVideo && RTC.localVideo.isMuted()) {
  3606. this.nodes.push({
  3607. tagName: "videomuted",
  3608. attributes: {xmlns: "http://jitsi.org/jitmeet/video"},
  3609. value: "true"});
  3610. }
  3611. this.presMap["nodes"].push( {
  3612. "tagName": "user-agent",
  3613. "value": navigator.userAgent,
  3614. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  3615. });
  3616. };
  3617. ChatRoom.prototype.sendPresence = function () {
  3618. if (!this.presMap['to']) {
  3619. // Too early to send presence - not initialized
  3620. return;
  3621. }
  3622. var pres = $pres({to: this.presMap['to'] });
  3623. pres.c('x', {xmlns: this.presMap['xns']});
  3624. if (this.password) {
  3625. pres.c('password').t(this.password).up();
  3626. }
  3627. pres.up();
  3628. // Send XEP-0115 'c' stanza that contains our capabilities info
  3629. if (this.connection.caps) {
  3630. this.connection.caps.node = this.xmpp.options.clientNode;
  3631. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  3632. }
  3633. parser.JSON2packet(this.presMap.nodes, pres);
  3634. this.connection.send(pres);
  3635. };
  3636. ChatRoom.prototype.doLeave = function () {
  3637. console.log("do leave", this.myroomjid);
  3638. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  3639. this.presMap.length = 0;
  3640. this.connection.send(pres);
  3641. };
  3642. ChatRoom.prototype.createNonAnonymousRoom = function () {
  3643. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  3644. var getForm = $iq({type: 'get', to: this.roomjid})
  3645. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  3646. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  3647. var self = this;
  3648. this.connection.sendIQ(getForm, function (form) {
  3649. if (!$(form).find(
  3650. '>query>x[xmlns="jabber:x:data"]' +
  3651. '>field[var="muc#roomconfig_whois"]').length) {
  3652. console.error('non-anonymous rooms not supported');
  3653. return;
  3654. }
  3655. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  3656. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  3657. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  3658. formSubmit.c('field', {'var': 'FORM_TYPE'})
  3659. .c('value')
  3660. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  3661. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  3662. .c('value').t('anyone').up().up();
  3663. self.connection.sendIQ(formSubmit);
  3664. }, function (error) {
  3665. console.error("Error getting room configuration form");
  3666. });
  3667. };
  3668. ChatRoom.prototype.onPresence = function (pres) {
  3669. var from = pres.getAttribute('from');
  3670. // Parse roles.
  3671. var member = {};
  3672. member.show = $(pres).find('>show').text();
  3673. member.status = $(pres).find('>status').text();
  3674. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  3675. member.affiliation = tmp.attr('affiliation');
  3676. member.role = tmp.attr('role');
  3677. // Focus recognition
  3678. member.jid = tmp.attr('jid');
  3679. member.isFocus = false;
  3680. if (member.jid
  3681. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  3682. member.isFocus = true;
  3683. }
  3684. pres.find(">x").remove();
  3685. var nodes = [];
  3686. parser.packet2JSON(pres, nodes);
  3687. for(var i = 0; i < nodes.length; i++)
  3688. {
  3689. var node = nodes[i];
  3690. switch(node.tagName)
  3691. {
  3692. case "nick":
  3693. member.nick = node.value;
  3694. if(!member.isFocus) {
  3695. var displayName = !this.xmpp.options.displayJids
  3696. ? member.nick : Strophe.getResourceFromJid(from);
  3697. if (displayName && displayName.length > 0) {
  3698. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  3699. }
  3700. console.info("Display name: " + displayName, pres);
  3701. }
  3702. break;
  3703. case "userId":
  3704. member.id = node.value;
  3705. break;
  3706. case "email":
  3707. member.email = node.value;
  3708. break;
  3709. case "bridgeIsDown":
  3710. if(!this.bridgeIsDown) {
  3711. this.bridgeIsDown = true;
  3712. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  3713. }
  3714. break;
  3715. default :
  3716. this.processNode(node);
  3717. }
  3718. }
  3719. if (from == this.myroomjid) {
  3720. if (member.affiliation == 'owner')
  3721. if (this.role !== member.role) {
  3722. this.role = member.role;
  3723. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  3724. member, Moderator.isModerator());
  3725. }
  3726. if (!this.joined) {
  3727. this.joined = true;
  3728. this.eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  3729. }
  3730. } else if (this.members[from] === undefined) {
  3731. // new participant
  3732. this.members[from] = member;
  3733. console.log('entered', from, member);
  3734. if (member.isFocus) {
  3735. this.focusMucJid = from;
  3736. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  3737. }
  3738. else {
  3739. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, member.id || member.email, member.nick);
  3740. }
  3741. } else {
  3742. // Presence update for existing participant
  3743. // Watch role change:
  3744. if (this.members[from].role != member.role) {
  3745. this.members[from].role = member.role;
  3746. this.eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  3747. member.role, member.nick);
  3748. }
  3749. }
  3750. if(!member.isFocus)
  3751. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id || member.email);
  3752. // Trigger status message update
  3753. if (member.status) {
  3754. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  3755. }
  3756. };
  3757. ChatRoom.prototype.processNode = function (node) {
  3758. this.eventEmitter.emit(XMPPEvents.PRESENCE_SETTING, node);
  3759. };
  3760. ChatRoom.prototype.sendMessage = function (body, nickname) {
  3761. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  3762. msg.c('body', body).up();
  3763. if (nickname) {
  3764. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  3765. }
  3766. this.connection.send(msg);
  3767. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  3768. };
  3769. ChatRoom.prototype.setSubject = function (subject) {
  3770. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  3771. msg.c('subject', subject);
  3772. this.connection.send(msg);
  3773. console.log("topic changed to " + subject);
  3774. };
  3775. ChatRoom.prototype.onParticipantLeft = function (jid) {
  3776. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  3777. this.connection.jingle.terminateByJid(jid);
  3778. Moderator.onMucMemberLeft(jid);
  3779. };
  3780. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  3781. // room destroyed ?
  3782. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  3783. '>destroy').length) {
  3784. var reason;
  3785. var reasonSelect = $(pres).find(
  3786. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  3787. '>destroy>reason');
  3788. if (reasonSelect.length) {
  3789. reason = reasonSelect.text();
  3790. }
  3791. this.xmpp.disposeConference(false);
  3792. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  3793. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(jid)];
  3794. return true;
  3795. }
  3796. // Status code 110 indicates that this notification is "self-presence".
  3797. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  3798. delete this.members[from];
  3799. this.onParticipantLeft(from);
  3800. }
  3801. // If the status code is 110 this means we're leaving and we would like
  3802. // to remove everyone else from our view, so we trigger the event.
  3803. else if (Object.keys(this.members).length > 1) {
  3804. for (var i in this.members) {
  3805. var member = this.members[i];
  3806. delete this.members[i];
  3807. this.onParticipantLeft(member);
  3808. }
  3809. }
  3810. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  3811. if (this.myroomjid === from) {
  3812. this.xmpp.disposeConference(false);
  3813. this.eventEmitter.emit(XMPPEvents.KICKED);
  3814. }
  3815. }
  3816. };
  3817. ChatRoom.prototype.onMessage = function (msg, from) {
  3818. var nick =
  3819. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  3820. .text() ||
  3821. Strophe.getResourceFromJid(from);
  3822. var txt = $(msg).find('>body').text();
  3823. var type = msg.getAttribute("type");
  3824. if (type == "error") {
  3825. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  3826. $(msg).find('>text').text(), txt);
  3827. return true;
  3828. }
  3829. var subject = $(msg).find('>subject');
  3830. if (subject.length) {
  3831. var subjectText = subject.text();
  3832. if (subjectText || subjectText == "") {
  3833. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  3834. console.log("Subject is changed to " + subjectText);
  3835. }
  3836. }
  3837. // xep-0203 delay
  3838. var stamp = $(msg).find('>delay').attr('stamp');
  3839. if (!stamp) {
  3840. // or xep-0091 delay, UTC timestamp
  3841. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  3842. if (stamp) {
  3843. // the format is CCYYMMDDThh:mm:ss
  3844. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  3845. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  3846. }
  3847. }
  3848. if (txt) {
  3849. console.log('chat', nick, txt);
  3850. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  3851. from, nick, txt, this.myroomjid, stamp);
  3852. }
  3853. }
  3854. ChatRoom.prototype.onPresenceError = function (pres, from) {
  3855. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  3856. console.log('on password required', from);
  3857. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  3858. } else if ($(pres).find(
  3859. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  3860. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  3861. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  3862. // enter the room by replying with 'not-authorized'. This would
  3863. // result in reconnection from authorized domain.
  3864. // We're either missing Jicofo/Prosody config for anonymous
  3865. // domains or something is wrong.
  3866. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  3867. } else {
  3868. console.warn('onPresError ', pres);
  3869. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  3870. }
  3871. } else {
  3872. console.warn('onPresError ', pres);
  3873. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  3874. }
  3875. };
  3876. ChatRoom.prototype.kick = function (jid) {
  3877. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  3878. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  3879. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  3880. .c('reason').t('You have been kicked.').up().up().up();
  3881. this.connection.sendIQ(
  3882. kickIQ,
  3883. function (result) {
  3884. console.log('Kick participant with jid: ', jid, result);
  3885. },
  3886. function (error) {
  3887. console.log('Kick participant error: ', error);
  3888. });
  3889. };
  3890. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  3891. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  3892. var ob = this;
  3893. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  3894. function (res) {
  3895. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  3896. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  3897. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  3898. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  3899. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  3900. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  3901. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  3902. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  3903. ob.connection.sendIQ(formsubmit,
  3904. onSuccess,
  3905. onError);
  3906. } else {
  3907. onNotSupported();
  3908. }
  3909. }, onError);
  3910. };
  3911. ChatRoom.prototype.addToPresence = function (key, values) {
  3912. values.tagName = key;
  3913. this.presMap["nodes"].push(values);
  3914. };
  3915. ChatRoom.prototype.removeFromPresence = function (key) {
  3916. for(var i = 0; i < this.presMap.nodes.length; i++)
  3917. {
  3918. if(key === this.presMap.nodes[i].tagName)
  3919. this.presMap.nodes.splice(i, 1);
  3920. }
  3921. };
  3922. ChatRoom.prototype.isModerator = function (jid) {
  3923. return this.role === 'moderator';
  3924. };
  3925. ChatRoom.prototype.getMemberRole = function (peerJid) {
  3926. if (this.members[peerJid]) {
  3927. return this.members[peerJid].role;
  3928. }
  3929. return null;
  3930. };
  3931. module.exports = function(XMPP) {
  3932. Strophe.addConnectionPlugin('emuc', {
  3933. connection: null,
  3934. rooms: {},//map with the rooms
  3935. init: function (conn) {
  3936. this.connection = conn;
  3937. // add handlers (just once)
  3938. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null);
  3939. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null);
  3940. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null);
  3941. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null);
  3942. },
  3943. doJoin: function (jid, password, eventEmitter) {
  3944. var roomJid = Strophe.getBareJidFromJid(jid);
  3945. if(this.rooms[roomJid])
  3946. {
  3947. console.error("You are already in the room!");
  3948. return;
  3949. }
  3950. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, eventEmitter);
  3951. this.rooms[roomJid].sendPresence();
  3952. return this.rooms[roomJid];
  3953. },
  3954. doLeave: function (jid) {
  3955. this.rooms[jid].doLeave();
  3956. delete this.rooms[jid];
  3957. },
  3958. onPresence: function (pres) {
  3959. var from = pres.getAttribute('from');
  3960. // What is this for? A workaround for something?
  3961. if (pres.getAttribute('type')) {
  3962. return true;
  3963. }
  3964. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  3965. if(!room)
  3966. return;
  3967. // Parse status.
  3968. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  3969. room.createNonAnonymousRoom();
  3970. }
  3971. room.onPresence(pres);
  3972. return true;
  3973. },
  3974. onPresenceUnavailable: function (pres) {
  3975. var from = pres.getAttribute('from');
  3976. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  3977. if(!room)
  3978. return;
  3979. room.onPresenceUnavailable(pres, from);
  3980. return true;
  3981. },
  3982. onPresenceError: function (pres) {
  3983. var from = pres.getAttribute('from');
  3984. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  3985. if(!room)
  3986. return;
  3987. room.onPresenceError(pres, from);
  3988. return true;
  3989. },
  3990. onMessage: function (msg) {
  3991. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  3992. var from = msg.getAttribute('from');
  3993. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  3994. if(!room)
  3995. return;
  3996. room.onMessage(msg, from);
  3997. return true;
  3998. }
  3999. });
  4000. };
  4001. },{"../../service/xmpp/XMPPEvents":47,"../RTC/RTC":11,"./moderator":17}],19:[function(require,module,exports){
  4002. /* global Strophe */
  4003. module.exports = function () {
  4004. Strophe.addConnectionPlugin('logger', {
  4005. // logs raw stanzas and makes them available for download as JSON
  4006. connection: null,
  4007. log: [],
  4008. init: function (conn) {
  4009. this.connection = conn;
  4010. this.connection.rawInput = this.log_incoming.bind(this);
  4011. this.connection.rawOutput = this.log_outgoing.bind(this);
  4012. },
  4013. log_incoming: function (stanza) {
  4014. this.log.push([new Date().getTime(), 'incoming', stanza]);
  4015. },
  4016. log_outgoing: function (stanza) {
  4017. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  4018. }
  4019. });
  4020. };
  4021. },{}],20:[function(require,module,exports){
  4022. /* jshint -W117 */
  4023. module.exports = function() {
  4024. Strophe.addConnectionPlugin('rayo',
  4025. {
  4026. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  4027. connection: null,
  4028. init: function (conn) {
  4029. this.connection = conn;
  4030. if (this.connection.disco) {
  4031. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  4032. }
  4033. this.connection.addHandler(
  4034. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  4035. },
  4036. onRayo: function (iq) {
  4037. console.info("Rayo IQ", iq);
  4038. },
  4039. dial: function (to, from, roomName, roomPass) {
  4040. var self = this;
  4041. var req = $iq(
  4042. {
  4043. type: 'set',
  4044. to: this.connection.emuc.focusMucJid
  4045. }
  4046. );
  4047. req.c('dial',
  4048. {
  4049. xmlns: this.RAYO_XMLNS,
  4050. to: to,
  4051. from: from
  4052. });
  4053. req.c('header',
  4054. {
  4055. name: 'JvbRoomName',
  4056. value: roomName
  4057. }).up();
  4058. if (roomPass !== null && roomPass.length) {
  4059. req.c('header',
  4060. {
  4061. name: 'JvbRoomPassword',
  4062. value: roomPass
  4063. }).up();
  4064. }
  4065. this.connection.sendIQ(
  4066. req,
  4067. function (result) {
  4068. console.info('Dial result ', result);
  4069. var resource = $(result).find('ref').attr('uri');
  4070. this.call_resource = resource.substr('xmpp:'.length);
  4071. console.info(
  4072. "Received call resource: " + this.call_resource);
  4073. },
  4074. function (error) {
  4075. console.info('Dial error ', error);
  4076. }
  4077. );
  4078. },
  4079. hang_up: function () {
  4080. if (!this.call_resource) {
  4081. console.warn("No call in progress");
  4082. return;
  4083. }
  4084. var self = this;
  4085. var req = $iq(
  4086. {
  4087. type: 'set',
  4088. to: this.call_resource
  4089. }
  4090. );
  4091. req.c('hangup',
  4092. {
  4093. xmlns: this.RAYO_XMLNS
  4094. });
  4095. this.connection.sendIQ(
  4096. req,
  4097. function (result) {
  4098. console.info('Hangup result ', result);
  4099. self.call_resource = null;
  4100. },
  4101. function (error) {
  4102. console.info('Hangup error ', error);
  4103. self.call_resource = null;
  4104. }
  4105. );
  4106. }
  4107. }
  4108. );
  4109. };
  4110. },{}],21:[function(require,module,exports){
  4111. /**
  4112. * Strophe logger implementation. Logs from level WARN and above.
  4113. */
  4114. module.exports = function () {
  4115. Strophe.log = function (level, msg) {
  4116. switch (level) {
  4117. case Strophe.LogLevel.WARN:
  4118. console.warn("Strophe: " + msg);
  4119. break;
  4120. case Strophe.LogLevel.ERROR:
  4121. case Strophe.LogLevel.FATAL:
  4122. console.error("Strophe: " + msg);
  4123. break;
  4124. }
  4125. };
  4126. Strophe.getStatusString = function (status) {
  4127. switch (status) {
  4128. case Strophe.Status.ERROR:
  4129. return "ERROR";
  4130. case Strophe.Status.CONNECTING:
  4131. return "CONNECTING";
  4132. case Strophe.Status.CONNFAIL:
  4133. return "CONNFAIL";
  4134. case Strophe.Status.AUTHENTICATING:
  4135. return "AUTHENTICATING";
  4136. case Strophe.Status.AUTHFAIL:
  4137. return "AUTHFAIL";
  4138. case Strophe.Status.CONNECTED:
  4139. return "CONNECTED";
  4140. case Strophe.Status.DISCONNECTED:
  4141. return "DISCONNECTED";
  4142. case Strophe.Status.DISCONNECTING:
  4143. return "DISCONNECTING";
  4144. case Strophe.Status.ATTACHED:
  4145. return "ATTACHED";
  4146. default:
  4147. return "unknown";
  4148. }
  4149. };
  4150. };
  4151. },{}],22:[function(require,module,exports){
  4152. /* global $, APP, config, Strophe*/
  4153. var Moderator = require("./moderator");
  4154. var EventEmitter = require("events");
  4155. var Pako = require("pako");
  4156. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  4157. var RTCEvents = require("../../service/RTC/RTCEvents");
  4158. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  4159. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  4160. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  4161. var RTC = require("../RTC/RTC");
  4162. var authenticatedUser = false;
  4163. function createConnection(bosh) {
  4164. bosh = bosh || '/http-bind';
  4165. return new Strophe.Connection(bosh);
  4166. };
  4167. //!!!!!!!!!! FIXME: ...
  4168. function initStrophePlugins(XMPP)
  4169. {
  4170. require("./strophe.emuc")(XMPP);
  4171. // require("./strophe.jingle")(XMPP, eventEmitter);
  4172. // require("./strophe.moderate")(XMPP, eventEmitter);
  4173. require("./strophe.util")();
  4174. require("./strophe.rayo")();
  4175. require("./strophe.logger")();
  4176. }
  4177. //!!!!!!!!!! FIXME: ...
  4178. ///**
  4179. // * If given <tt>localStream</tt> is video one this method will advertise it's
  4180. // * video type in MUC presence.
  4181. // * @param localStream new or modified <tt>LocalStream</tt>.
  4182. // */
  4183. //function broadcastLocalVideoType(localStream) {
  4184. // if (localStream.videoType)
  4185. // XMPP.addToPresence('videoType', localStream.videoType);
  4186. //}
  4187. //
  4188. //function registerListeners() {
  4189. // RTC.addStreamListener(
  4190. // broadcastLocalVideoType,
  4191. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  4192. // );
  4193. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  4194. // XMPP.addToPresence("devices", devices);
  4195. // });
  4196. //}
  4197. function XMPP(options) {
  4198. this.sessionTerminated = false;
  4199. this.eventEmitter = new EventEmitter();
  4200. this.connection = null;
  4201. this.disconnectInProgress = false;
  4202. this.forceMuted = false;
  4203. this.options = options;
  4204. initStrophePlugins(this);
  4205. // registerListeners();
  4206. Moderator.init(this, this.eventEmitter);
  4207. this.connection = createConnection(options.bosh);
  4208. Moderator.setConnection(this.connection);
  4209. }
  4210. XMPP.prototype.getConnection = function(){ return connection; };
  4211. XMPP.prototype._connect = function (jid, password) {
  4212. var self = this;
  4213. // connection.connect() starts the connection process.
  4214. //
  4215. // As the connection process proceeds, the user supplied callback will
  4216. // be triggered multiple times with status updates. The callback should
  4217. // take two arguments - the status code and the error condition.
  4218. //
  4219. // The status code will be one of the values in the Strophe.Status
  4220. // constants. The error condition will be one of the conditions defined
  4221. // in RFC 3920 or the condition ‘strophe-parsererror’.
  4222. //
  4223. // The Parameters wait, hold and route are optional and only relevant
  4224. // for BOSH connections. Please see XEP 124 for a more detailed
  4225. // explanation of the optional parameters.
  4226. //
  4227. // Connection status constants for use by the connection handler
  4228. // callback.
  4229. //
  4230. // Status.ERROR - An error has occurred (websockets specific)
  4231. // Status.CONNECTING - The connection is currently being made
  4232. // Status.CONNFAIL - The connection attempt failed
  4233. // Status.AUTHENTICATING - The connection is authenticating
  4234. // Status.AUTHFAIL - The authentication attempt failed
  4235. // Status.CONNECTED - The connection has succeeded
  4236. // Status.DISCONNECTED - The connection has been terminated
  4237. // Status.DISCONNECTING - The connection is currently being terminated
  4238. // Status.ATTACHED - The connection has been attached
  4239. var anonymousConnectionFailed = false;
  4240. var connectionFailed = false;
  4241. var lastErrorMsg;
  4242. this.connection.connect(jid, password, function (status, msg) {
  4243. console.log('Strophe status changed to',
  4244. Strophe.getStatusString(status), msg);
  4245. if (status === Strophe.Status.CONNECTED) {
  4246. if (self.options.useStunTurn) {
  4247. self.connection.jingle.getStunAndTurnCredentials();
  4248. }
  4249. console.info("My Jabber ID: " + self.connection.jid);
  4250. if (password)
  4251. authenticatedUser = true;
  4252. if (self.connection && self.connection.connected &&
  4253. Strophe.getResourceFromJid(self.connection.jid)) {
  4254. // .connected is true while connecting?
  4255. self.connection.send($pres());
  4256. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  4257. Strophe.getResourceFromJid(self.connection.jid));
  4258. }
  4259. } else if (status === Strophe.Status.CONNFAIL) {
  4260. if (msg === 'x-strophe-bad-non-anon-jid') {
  4261. anonymousConnectionFailed = true;
  4262. }
  4263. else
  4264. {
  4265. connectionFailed = true;
  4266. }
  4267. lastErrorMsg = msg;
  4268. } else if (status === Strophe.Status.DISCONNECTED) {
  4269. self.disconnectInProgress = false;
  4270. if (anonymousConnectionFailed) {
  4271. // prompt user for username and password
  4272. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  4273. JitsiConnectionErrors.PASSWORD_REQUIRED);
  4274. } else if(connectionFailed) {
  4275. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  4276. JitsiConnectionErrors.OTHER_ERROR,
  4277. msg ? msg : lastErrorMsg);
  4278. } else {
  4279. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  4280. msg ? msg : lastErrorMsg);
  4281. }
  4282. } else if (status === Strophe.Status.AUTHFAIL) {
  4283. // wrong password or username, prompt user
  4284. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  4285. JitsiConnectionErrors.PASSWORD_REQUIRED);
  4286. }
  4287. });
  4288. }
  4289. XMPP.prototype.connect = function (jid, password) {
  4290. if(!jid) {
  4291. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  4292. // Force authenticated domain if room is appended with '?login=true'
  4293. if (this.options.hosts.anonymousdomain &&
  4294. window.location.search.indexOf("login=true") !== -1) {
  4295. configDomain = this.options.hosts.domain;
  4296. }
  4297. jid = configDomain || window.location.hostname;
  4298. }
  4299. return this._connect(jid, password);
  4300. };
  4301. XMPP.prototype.joinRoom = function(roomName, useNicks, nick) {
  4302. var roomjid = roomName + '@' + Strophe.getDomainFromJid(this.connection.jid);
  4303. if (useNicks) {
  4304. if (nick) {
  4305. roomjid += '/' + nick;
  4306. } else {
  4307. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  4308. }
  4309. } else {
  4310. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  4311. if(!authenticatedUser)
  4312. tmpJid = tmpJid.substr(0, 8);
  4313. roomjid += '/' + tmpJid;
  4314. }
  4315. return this.connection.emuc.doJoin(roomjid, null, this.eventEmitter);
  4316. };
  4317. XMPP.prototype.disposeConference = function (onUnload) {
  4318. var handler = this.connection.jingle.activecall;
  4319. if (handler && handler.peerconnection) {
  4320. // FIXME: probably removing streams is not required and close() should
  4321. // be enough
  4322. if (RTC.localAudio) {
  4323. handler.peerconnection.removeStream(
  4324. RTC.localAudio.getOriginalStream(), onUnload);
  4325. }
  4326. if (RTC.localVideo) {
  4327. handler.peerconnection.removeStream(
  4328. RTC.localVideo.getOriginalStream(), onUnload);
  4329. }
  4330. handler.peerconnection.close();
  4331. }
  4332. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  4333. this.connection.jingle.activecall = null;
  4334. if (!onUnload) {
  4335. this.sessionTerminated = true;
  4336. this.connection.emuc.doLeave();
  4337. }
  4338. };
  4339. XMPP.prototype.addListener = function(type, listener) {
  4340. this.eventEmitter.on(type, listener);
  4341. };
  4342. XMPP.prototype.removeListener = function (type, listener) {
  4343. this.eventEmitter.removeListener(type, listener);
  4344. };
  4345. XMPP.prototype.leaveRoom = function (jid) {
  4346. this.connection.emuc.doLeave(jid);
  4347. };
  4348. XMPP.prototype.allocateConferenceFocus = function(roomName, callback) {
  4349. Moderator.allocateConferenceFocus(roomName, callback);
  4350. };
  4351. XMPP.prototype.getLoginUrl = function (roomName, callback) {
  4352. Moderator.getLoginUrl(roomName, callback);
  4353. }
  4354. XMPP.prototype.getPopupLoginUrl = function (roomName, callback) {
  4355. Moderator.getPopupLoginUrl(roomName, callback);
  4356. };
  4357. XMPP.prototype.isModerator = function () {
  4358. return Moderator.isModerator();
  4359. };
  4360. XMPP.prototype.isSipGatewayEnabled = function () {
  4361. return Moderator.isSipGatewayEnabled();
  4362. }
  4363. XMPP.prototype.isExternalAuthEnabled = function () {
  4364. return Moderator.isExternalAuthEnabled();
  4365. };
  4366. XMPP.prototype.isConferenceInProgress = function () {
  4367. return this.connection && this.connection.jingle.activecall &&
  4368. this.connection.jingle.activecall.peerconnection;
  4369. };
  4370. XMPP.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  4371. if (this.isConferenceInProgress()) {
  4372. // FIXME: will block switchInProgress on true value in case of exception
  4373. this.connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  4374. } else {
  4375. // We are done immediately
  4376. console.warn("No conference handler or conference not started yet");
  4377. callback();
  4378. }
  4379. };
  4380. XMPP.prototype.sendVideoInfoPresence = function (mute) {
  4381. if(!this.connection)
  4382. return;
  4383. this.connection.emuc.addVideoInfoToPresence(mute);
  4384. this.connection.emuc.sendPresence();
  4385. };
  4386. XMPP.prototype.setVideoMute = function (mute, callback, options) {
  4387. if(!this.connection)
  4388. return;
  4389. var self = this;
  4390. var localCallback = function (mute) {
  4391. self.sendVideoInfoPresence(mute);
  4392. return callback(mute);
  4393. };
  4394. if(this.connection.jingle.activecall)
  4395. {
  4396. this.connection.jingle.activecall.setVideoMute(
  4397. mute, localCallback, options);
  4398. }
  4399. else {
  4400. localCallback(mute);
  4401. }
  4402. };
  4403. XMPP.prototype.setAudioMute = function (mute, callback) {
  4404. if (!(this.connection && RTC.localAudio)) {
  4405. return false;
  4406. }
  4407. if (this.forceMuted && !mute) {
  4408. console.info("Asking focus for unmute");
  4409. this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  4410. // FIXME: wait for result before resetting muted status
  4411. this.forceMuted = false;
  4412. }
  4413. if (mute == RTC.localAudio.isMuted()) {
  4414. // Nothing to do
  4415. return true;
  4416. }
  4417. RTC.localAudio.setMute(mute);
  4418. this.sendAudioInfoPresence(mute, callback);
  4419. return true;
  4420. };
  4421. XMPP.prototype.sendAudioInfoPresence = function(mute, callback) {
  4422. if(this.connection) {
  4423. this.connection.emuc.addAudioInfoToPresence(mute);
  4424. this.connection.emuc.sendPresence();
  4425. }
  4426. callback();
  4427. return true;
  4428. };
  4429. XMPP.prototype.addToPresence = function (name, values, dontSend) {
  4430. this.connection.emuc.addToPresence(name, values);
  4431. switch (name) {
  4432. case "displayName":
  4433. this.connection.emuc.addDisplayNameToPresence(value);
  4434. break;
  4435. case "prezi":
  4436. this.connection.emuc.addPreziToPresence(value, 0);
  4437. break;
  4438. case "preziSlide":
  4439. this.connection.emuc.addCurrentSlideToPresence(value);
  4440. break;
  4441. case "connectionQuality":
  4442. this.connection.emuc.addConnectionInfoToPresence(value);
  4443. break;
  4444. case "email":
  4445. this.connection.emuc.addEmailToPresence(value);
  4446. break;
  4447. case "devices":
  4448. this.connection.emuc.addDevicesToPresence(value);
  4449. break;
  4450. case "videoType":
  4451. this.connection.emuc.addVideoTypeToPresence(value);
  4452. break;
  4453. case "startMuted":
  4454. if(!Moderator.isModerator())
  4455. return;
  4456. this.connection.emuc.addStartMutedToPresence(value[0],
  4457. value[1]);
  4458. break;
  4459. default :
  4460. console.log("Unknown tag for presence: " + name);
  4461. return;
  4462. }
  4463. if (!dontSend)
  4464. this.connection.emuc.sendPresence();
  4465. };
  4466. /**
  4467. * Sends 'data' as a log message to the focus. Returns true iff a message
  4468. * was sent.
  4469. * @param data
  4470. * @returns {boolean} true iff a message was sent.
  4471. */
  4472. XMPP.prototype.sendLogs = function (data) {
  4473. if(!this.connection.emuc.focusMucJid)
  4474. return false;
  4475. var deflate = true;
  4476. var content = JSON.stringify(data);
  4477. if (deflate) {
  4478. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  4479. }
  4480. content = Base64.encode(content);
  4481. // XEP-0337-ish
  4482. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  4483. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  4484. id: 'PeerConnectionStats'});
  4485. message.c('message').t(content).up();
  4486. if (deflate) {
  4487. message.c('tag', {name: "deflated", value: "true"}).up();
  4488. }
  4489. message.up();
  4490. this.connection.send(message);
  4491. return true;
  4492. };
  4493. // Gets the logs from strophe.jingle.
  4494. XMPP.prototype.getJingleLog = function () {
  4495. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  4496. };
  4497. // Gets the logs from strophe.
  4498. XMPP.prototype.getXmppLog = function () {
  4499. return this.connection.logger ? this.connection.logger.log : null;
  4500. };
  4501. XMPP.prototype.sendChatMessage = function (message, nickname) {
  4502. this.connection.emuc.sendMessage(message, nickname);
  4503. };
  4504. XMPP.prototype.setSubject = function (topic) {
  4505. this.connection.emuc.setSubject(topic);
  4506. };
  4507. XMPP.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  4508. this.connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  4509. };
  4510. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  4511. this.connection.rayo.dial(to, from, roomName,roomPass);
  4512. };
  4513. XMPP.prototype.setMute = function (jid, mute) {
  4514. this.connection.moderate.setMute(jid, mute);
  4515. };
  4516. XMPP.prototype.eject = function (jid) {
  4517. this.connection.moderate.eject(jid);
  4518. };
  4519. XMPP.prototype.logout = function (callback) {
  4520. Moderator.logout(callback);
  4521. };
  4522. XMPP.prototype.getMembers = function () {
  4523. return this.connection.emuc.members;
  4524. };
  4525. XMPP.prototype.getJidFromSSRC = function (ssrc) {
  4526. if (!this.isConferenceInProgress())
  4527. return null;
  4528. return this.connection.jingle.activecall.getSsrcOwner(ssrc);
  4529. };
  4530. // Returns true iff we have joined the MUC.
  4531. XMPP.prototype.isMUCJoined = function () {
  4532. return this.connection.emuc.joined;
  4533. };
  4534. XMPP.prototype.getSessions = function () {
  4535. return this.connection.jingle.sessions;
  4536. };
  4537. XMPP.prototype.removeStream = function (stream) {
  4538. if (!this.isConferenceInProgress())
  4539. return;
  4540. this.connection.jingle.activecall.peerconnection.removeStream(stream);
  4541. };
  4542. XMPP.prototype.disconnect = function (callback) {
  4543. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  4544. {
  4545. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  4546. return;
  4547. }
  4548. this.disconnectInProgress = true;
  4549. this.connection.disconnect();
  4550. };
  4551. module.exports = XMPP;
  4552. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":41,"../../service/RTC/StreamEventTypes":43,"../../service/xmpp/XMPPEvents":47,"../RTC/RTC":11,"./moderator":17,"./strophe.emuc":18,"./strophe.logger":19,"./strophe.rayo":20,"./strophe.util":21,"events":48,"pako":24}],23:[function(require,module,exports){
  4553. (function (process,global){
  4554. /*!
  4555. * @overview es6-promise - a tiny implementation of Promises/A+.
  4556. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  4557. * @license Licensed under MIT license
  4558. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  4559. * @version 3.0.2
  4560. */
  4561. (function() {
  4562. "use strict";
  4563. function lib$es6$promise$utils$$objectOrFunction(x) {
  4564. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  4565. }
  4566. function lib$es6$promise$utils$$isFunction(x) {
  4567. return typeof x === 'function';
  4568. }
  4569. function lib$es6$promise$utils$$isMaybeThenable(x) {
  4570. return typeof x === 'object' && x !== null;
  4571. }
  4572. var lib$es6$promise$utils$$_isArray;
  4573. if (!Array.isArray) {
  4574. lib$es6$promise$utils$$_isArray = function (x) {
  4575. return Object.prototype.toString.call(x) === '[object Array]';
  4576. };
  4577. } else {
  4578. lib$es6$promise$utils$$_isArray = Array.isArray;
  4579. }
  4580. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  4581. var lib$es6$promise$asap$$len = 0;
  4582. var lib$es6$promise$asap$$toString = {}.toString;
  4583. var lib$es6$promise$asap$$vertxNext;
  4584. var lib$es6$promise$asap$$customSchedulerFn;
  4585. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  4586. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  4587. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  4588. lib$es6$promise$asap$$len += 2;
  4589. if (lib$es6$promise$asap$$len === 2) {
  4590. // If len is 2, that means that we need to schedule an async flush.
  4591. // If additional callbacks are queued before the queue is flushed, they
  4592. // will be processed by this flush that we are scheduling.
  4593. if (lib$es6$promise$asap$$customSchedulerFn) {
  4594. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  4595. } else {
  4596. lib$es6$promise$asap$$scheduleFlush();
  4597. }
  4598. }
  4599. }
  4600. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  4601. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  4602. }
  4603. function lib$es6$promise$asap$$setAsap(asapFn) {
  4604. lib$es6$promise$asap$$asap = asapFn;
  4605. }
  4606. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  4607. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  4608. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  4609. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  4610. // test for web worker but not in IE10
  4611. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  4612. typeof importScripts !== 'undefined' &&
  4613. typeof MessageChannel !== 'undefined';
  4614. // node
  4615. function lib$es6$promise$asap$$useNextTick() {
  4616. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  4617. // see https://github.com/cujojs/when/issues/410 for details
  4618. return function() {
  4619. process.nextTick(lib$es6$promise$asap$$flush);
  4620. };
  4621. }
  4622. // vertx
  4623. function lib$es6$promise$asap$$useVertxTimer() {
  4624. return function() {
  4625. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  4626. };
  4627. }
  4628. function lib$es6$promise$asap$$useMutationObserver() {
  4629. var iterations = 0;
  4630. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  4631. var node = document.createTextNode('');
  4632. observer.observe(node, { characterData: true });
  4633. return function() {
  4634. node.data = (iterations = ++iterations % 2);
  4635. };
  4636. }
  4637. // web worker
  4638. function lib$es6$promise$asap$$useMessageChannel() {
  4639. var channel = new MessageChannel();
  4640. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  4641. return function () {
  4642. channel.port2.postMessage(0);
  4643. };
  4644. }
  4645. function lib$es6$promise$asap$$useSetTimeout() {
  4646. return function() {
  4647. setTimeout(lib$es6$promise$asap$$flush, 1);
  4648. };
  4649. }
  4650. var lib$es6$promise$asap$$queue = new Array(1000);
  4651. function lib$es6$promise$asap$$flush() {
  4652. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  4653. var callback = lib$es6$promise$asap$$queue[i];
  4654. var arg = lib$es6$promise$asap$$queue[i+1];
  4655. callback(arg);
  4656. lib$es6$promise$asap$$queue[i] = undefined;
  4657. lib$es6$promise$asap$$queue[i+1] = undefined;
  4658. }
  4659. lib$es6$promise$asap$$len = 0;
  4660. }
  4661. function lib$es6$promise$asap$$attemptVertx() {
  4662. try {
  4663. var r = require;
  4664. var vertx = r('vertx');
  4665. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  4666. return lib$es6$promise$asap$$useVertxTimer();
  4667. } catch(e) {
  4668. return lib$es6$promise$asap$$useSetTimeout();
  4669. }
  4670. }
  4671. var lib$es6$promise$asap$$scheduleFlush;
  4672. // Decide what async method to use to triggering processing of queued callbacks:
  4673. if (lib$es6$promise$asap$$isNode) {
  4674. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  4675. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  4676. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  4677. } else if (lib$es6$promise$asap$$isWorker) {
  4678. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  4679. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  4680. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  4681. } else {
  4682. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  4683. }
  4684. function lib$es6$promise$$internal$$noop() {}
  4685. var lib$es6$promise$$internal$$PENDING = void 0;
  4686. var lib$es6$promise$$internal$$FULFILLED = 1;
  4687. var lib$es6$promise$$internal$$REJECTED = 2;
  4688. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  4689. function lib$es6$promise$$internal$$selfFulfillment() {
  4690. return new TypeError("You cannot resolve a promise with itself");
  4691. }
  4692. function lib$es6$promise$$internal$$cannotReturnOwn() {
  4693. return new TypeError('A promises callback cannot return that same promise.');
  4694. }
  4695. function lib$es6$promise$$internal$$getThen(promise) {
  4696. try {
  4697. return promise.then;
  4698. } catch(error) {
  4699. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  4700. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  4701. }
  4702. }
  4703. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  4704. try {
  4705. then.call(value, fulfillmentHandler, rejectionHandler);
  4706. } catch(e) {
  4707. return e;
  4708. }
  4709. }
  4710. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  4711. lib$es6$promise$asap$$asap(function(promise) {
  4712. var sealed = false;
  4713. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  4714. if (sealed) { return; }
  4715. sealed = true;
  4716. if (thenable !== value) {
  4717. lib$es6$promise$$internal$$resolve(promise, value);
  4718. } else {
  4719. lib$es6$promise$$internal$$fulfill(promise, value);
  4720. }
  4721. }, function(reason) {
  4722. if (sealed) { return; }
  4723. sealed = true;
  4724. lib$es6$promise$$internal$$reject(promise, reason);
  4725. }, 'Settle: ' + (promise._label || ' unknown promise'));
  4726. if (!sealed && error) {
  4727. sealed = true;
  4728. lib$es6$promise$$internal$$reject(promise, error);
  4729. }
  4730. }, promise);
  4731. }
  4732. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  4733. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  4734. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  4735. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  4736. lib$es6$promise$$internal$$reject(promise, thenable._result);
  4737. } else {
  4738. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  4739. lib$es6$promise$$internal$$resolve(promise, value);
  4740. }, function(reason) {
  4741. lib$es6$promise$$internal$$reject(promise, reason);
  4742. });
  4743. }
  4744. }
  4745. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  4746. if (maybeThenable.constructor === promise.constructor) {
  4747. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  4748. } else {
  4749. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  4750. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  4751. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  4752. } else if (then === undefined) {
  4753. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  4754. } else if (lib$es6$promise$utils$$isFunction(then)) {
  4755. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  4756. } else {
  4757. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  4758. }
  4759. }
  4760. }
  4761. function lib$es6$promise$$internal$$resolve(promise, value) {
  4762. if (promise === value) {
  4763. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  4764. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  4765. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  4766. } else {
  4767. lib$es6$promise$$internal$$fulfill(promise, value);
  4768. }
  4769. }
  4770. function lib$es6$promise$$internal$$publishRejection(promise) {
  4771. if (promise._onerror) {
  4772. promise._onerror(promise._result);
  4773. }
  4774. lib$es6$promise$$internal$$publish(promise);
  4775. }
  4776. function lib$es6$promise$$internal$$fulfill(promise, value) {
  4777. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  4778. promise._result = value;
  4779. promise._state = lib$es6$promise$$internal$$FULFILLED;
  4780. if (promise._subscribers.length !== 0) {
  4781. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  4782. }
  4783. }
  4784. function lib$es6$promise$$internal$$reject(promise, reason) {
  4785. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  4786. promise._state = lib$es6$promise$$internal$$REJECTED;
  4787. promise._result = reason;
  4788. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  4789. }
  4790. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  4791. var subscribers = parent._subscribers;
  4792. var length = subscribers.length;
  4793. parent._onerror = null;
  4794. subscribers[length] = child;
  4795. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  4796. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  4797. if (length === 0 && parent._state) {
  4798. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  4799. }
  4800. }
  4801. function lib$es6$promise$$internal$$publish(promise) {
  4802. var subscribers = promise._subscribers;
  4803. var settled = promise._state;
  4804. if (subscribers.length === 0) { return; }
  4805. var child, callback, detail = promise._result;
  4806. for (var i = 0; i < subscribers.length; i += 3) {
  4807. child = subscribers[i];
  4808. callback = subscribers[i + settled];
  4809. if (child) {
  4810. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  4811. } else {
  4812. callback(detail);
  4813. }
  4814. }
  4815. promise._subscribers.length = 0;
  4816. }
  4817. function lib$es6$promise$$internal$$ErrorObject() {
  4818. this.error = null;
  4819. }
  4820. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  4821. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  4822. try {
  4823. return callback(detail);
  4824. } catch(e) {
  4825. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  4826. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  4827. }
  4828. }
  4829. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  4830. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  4831. value, error, succeeded, failed;
  4832. if (hasCallback) {
  4833. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  4834. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  4835. failed = true;
  4836. error = value.error;
  4837. value = null;
  4838. } else {
  4839. succeeded = true;
  4840. }
  4841. if (promise === value) {
  4842. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  4843. return;
  4844. }
  4845. } else {
  4846. value = detail;
  4847. succeeded = true;
  4848. }
  4849. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  4850. // noop
  4851. } else if (hasCallback && succeeded) {
  4852. lib$es6$promise$$internal$$resolve(promise, value);
  4853. } else if (failed) {
  4854. lib$es6$promise$$internal$$reject(promise, error);
  4855. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  4856. lib$es6$promise$$internal$$fulfill(promise, value);
  4857. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  4858. lib$es6$promise$$internal$$reject(promise, value);
  4859. }
  4860. }
  4861. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  4862. try {
  4863. resolver(function resolvePromise(value){
  4864. lib$es6$promise$$internal$$resolve(promise, value);
  4865. }, function rejectPromise(reason) {
  4866. lib$es6$promise$$internal$$reject(promise, reason);
  4867. });
  4868. } catch(e) {
  4869. lib$es6$promise$$internal$$reject(promise, e);
  4870. }
  4871. }
  4872. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  4873. var enumerator = this;
  4874. enumerator._instanceConstructor = Constructor;
  4875. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  4876. if (enumerator._validateInput(input)) {
  4877. enumerator._input = input;
  4878. enumerator.length = input.length;
  4879. enumerator._remaining = input.length;
  4880. enumerator._init();
  4881. if (enumerator.length === 0) {
  4882. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  4883. } else {
  4884. enumerator.length = enumerator.length || 0;
  4885. enumerator._enumerate();
  4886. if (enumerator._remaining === 0) {
  4887. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  4888. }
  4889. }
  4890. } else {
  4891. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  4892. }
  4893. }
  4894. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  4895. return lib$es6$promise$utils$$isArray(input);
  4896. };
  4897. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  4898. return new Error('Array Methods must be provided an Array');
  4899. };
  4900. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  4901. this._result = new Array(this.length);
  4902. };
  4903. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  4904. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  4905. var enumerator = this;
  4906. var length = enumerator.length;
  4907. var promise = enumerator.promise;
  4908. var input = enumerator._input;
  4909. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  4910. enumerator._eachEntry(input[i], i);
  4911. }
  4912. };
  4913. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  4914. var enumerator = this;
  4915. var c = enumerator._instanceConstructor;
  4916. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  4917. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  4918. entry._onerror = null;
  4919. enumerator._settledAt(entry._state, i, entry._result);
  4920. } else {
  4921. enumerator._willSettleAt(c.resolve(entry), i);
  4922. }
  4923. } else {
  4924. enumerator._remaining--;
  4925. enumerator._result[i] = entry;
  4926. }
  4927. };
  4928. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  4929. var enumerator = this;
  4930. var promise = enumerator.promise;
  4931. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  4932. enumerator._remaining--;
  4933. if (state === lib$es6$promise$$internal$$REJECTED) {
  4934. lib$es6$promise$$internal$$reject(promise, value);
  4935. } else {
  4936. enumerator._result[i] = value;
  4937. }
  4938. }
  4939. if (enumerator._remaining === 0) {
  4940. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  4941. }
  4942. };
  4943. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  4944. var enumerator = this;
  4945. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  4946. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  4947. }, function(reason) {
  4948. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  4949. });
  4950. };
  4951. function lib$es6$promise$promise$all$$all(entries) {
  4952. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  4953. }
  4954. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  4955. function lib$es6$promise$promise$race$$race(entries) {
  4956. /*jshint validthis:true */
  4957. var Constructor = this;
  4958. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  4959. if (!lib$es6$promise$utils$$isArray(entries)) {
  4960. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  4961. return promise;
  4962. }
  4963. var length = entries.length;
  4964. function onFulfillment(value) {
  4965. lib$es6$promise$$internal$$resolve(promise, value);
  4966. }
  4967. function onRejection(reason) {
  4968. lib$es6$promise$$internal$$reject(promise, reason);
  4969. }
  4970. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  4971. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  4972. }
  4973. return promise;
  4974. }
  4975. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  4976. function lib$es6$promise$promise$resolve$$resolve(object) {
  4977. /*jshint validthis:true */
  4978. var Constructor = this;
  4979. if (object && typeof object === 'object' && object.constructor === Constructor) {
  4980. return object;
  4981. }
  4982. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  4983. lib$es6$promise$$internal$$resolve(promise, object);
  4984. return promise;
  4985. }
  4986. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  4987. function lib$es6$promise$promise$reject$$reject(reason) {
  4988. /*jshint validthis:true */
  4989. var Constructor = this;
  4990. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  4991. lib$es6$promise$$internal$$reject(promise, reason);
  4992. return promise;
  4993. }
  4994. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  4995. var lib$es6$promise$promise$$counter = 0;
  4996. function lib$es6$promise$promise$$needsResolver() {
  4997. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  4998. }
  4999. function lib$es6$promise$promise$$needsNew() {
  5000. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  5001. }
  5002. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  5003. /**
  5004. Promise objects represent the eventual result of an asynchronous operation. The
  5005. primary way of interacting with a promise is through its `then` method, which
  5006. registers callbacks to receive either a promise's eventual value or the reason
  5007. why the promise cannot be fulfilled.
  5008. Terminology
  5009. -----------
  5010. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  5011. - `thenable` is an object or function that defines a `then` method.
  5012. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  5013. - `exception` is a value that is thrown using the throw statement.
  5014. - `reason` is a value that indicates why a promise was rejected.
  5015. - `settled` the final resting state of a promise, fulfilled or rejected.
  5016. A promise can be in one of three states: pending, fulfilled, or rejected.
  5017. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  5018. state. Promises that are rejected have a rejection reason and are in the
  5019. rejected state. A fulfillment value is never a thenable.
  5020. Promises can also be said to *resolve* a value. If this value is also a
  5021. promise, then the original promise's settled state will match the value's
  5022. settled state. So a promise that *resolves* a promise that rejects will
  5023. itself reject, and a promise that *resolves* a promise that fulfills will
  5024. itself fulfill.
  5025. Basic Usage:
  5026. ------------
  5027. ```js
  5028. var promise = new Promise(function(resolve, reject) {
  5029. // on success
  5030. resolve(value);
  5031. // on failure
  5032. reject(reason);
  5033. });
  5034. promise.then(function(value) {
  5035. // on fulfillment
  5036. }, function(reason) {
  5037. // on rejection
  5038. });
  5039. ```
  5040. Advanced Usage:
  5041. ---------------
  5042. Promises shine when abstracting away asynchronous interactions such as
  5043. `XMLHttpRequest`s.
  5044. ```js
  5045. function getJSON(url) {
  5046. return new Promise(function(resolve, reject){
  5047. var xhr = new XMLHttpRequest();
  5048. xhr.open('GET', url);
  5049. xhr.onreadystatechange = handler;
  5050. xhr.responseType = 'json';
  5051. xhr.setRequestHeader('Accept', 'application/json');
  5052. xhr.send();
  5053. function handler() {
  5054. if (this.readyState === this.DONE) {
  5055. if (this.status === 200) {
  5056. resolve(this.response);
  5057. } else {
  5058. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  5059. }
  5060. }
  5061. };
  5062. });
  5063. }
  5064. getJSON('/posts.json').then(function(json) {
  5065. // on fulfillment
  5066. }, function(reason) {
  5067. // on rejection
  5068. });
  5069. ```
  5070. Unlike callbacks, promises are great composable primitives.
  5071. ```js
  5072. Promise.all([
  5073. getJSON('/posts'),
  5074. getJSON('/comments')
  5075. ]).then(function(values){
  5076. values[0] // => postsJSON
  5077. values[1] // => commentsJSON
  5078. return values;
  5079. });
  5080. ```
  5081. @class Promise
  5082. @param {function} resolver
  5083. Useful for tooling.
  5084. @constructor
  5085. */
  5086. function lib$es6$promise$promise$$Promise(resolver) {
  5087. this._id = lib$es6$promise$promise$$counter++;
  5088. this._state = undefined;
  5089. this._result = undefined;
  5090. this._subscribers = [];
  5091. if (lib$es6$promise$$internal$$noop !== resolver) {
  5092. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  5093. lib$es6$promise$promise$$needsResolver();
  5094. }
  5095. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  5096. lib$es6$promise$promise$$needsNew();
  5097. }
  5098. lib$es6$promise$$internal$$initializePromise(this, resolver);
  5099. }
  5100. }
  5101. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  5102. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  5103. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  5104. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  5105. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  5106. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  5107. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  5108. lib$es6$promise$promise$$Promise.prototype = {
  5109. constructor: lib$es6$promise$promise$$Promise,
  5110. /**
  5111. The primary way of interacting with a promise is through its `then` method,
  5112. which registers callbacks to receive either a promise's eventual value or the
  5113. reason why the promise cannot be fulfilled.
  5114. ```js
  5115. findUser().then(function(user){
  5116. // user is available
  5117. }, function(reason){
  5118. // user is unavailable, and you are given the reason why
  5119. });
  5120. ```
  5121. Chaining
  5122. --------
  5123. The return value of `then` is itself a promise. This second, 'downstream'
  5124. promise is resolved with the return value of the first promise's fulfillment
  5125. or rejection handler, or rejected if the handler throws an exception.
  5126. ```js
  5127. findUser().then(function (user) {
  5128. return user.name;
  5129. }, function (reason) {
  5130. return 'default name';
  5131. }).then(function (userName) {
  5132. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  5133. // will be `'default name'`
  5134. });
  5135. findUser().then(function (user) {
  5136. throw new Error('Found user, but still unhappy');
  5137. }, function (reason) {
  5138. throw new Error('`findUser` rejected and we're unhappy');
  5139. }).then(function (value) {
  5140. // never reached
  5141. }, function (reason) {
  5142. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  5143. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  5144. });
  5145. ```
  5146. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  5147. ```js
  5148. findUser().then(function (user) {
  5149. throw new PedagogicalException('Upstream error');
  5150. }).then(function (value) {
  5151. // never reached
  5152. }).then(function (value) {
  5153. // never reached
  5154. }, function (reason) {
  5155. // The `PedgagocialException` is propagated all the way down to here
  5156. });
  5157. ```
  5158. Assimilation
  5159. ------------
  5160. Sometimes the value you want to propagate to a downstream promise can only be
  5161. retrieved asynchronously. This can be achieved by returning a promise in the
  5162. fulfillment or rejection handler. The downstream promise will then be pending
  5163. until the returned promise is settled. This is called *assimilation*.
  5164. ```js
  5165. findUser().then(function (user) {
  5166. return findCommentsByAuthor(user);
  5167. }).then(function (comments) {
  5168. // The user's comments are now available
  5169. });
  5170. ```
  5171. If the assimliated promise rejects, then the downstream promise will also reject.
  5172. ```js
  5173. findUser().then(function (user) {
  5174. return findCommentsByAuthor(user);
  5175. }).then(function (comments) {
  5176. // If `findCommentsByAuthor` fulfills, we'll have the value here
  5177. }, function (reason) {
  5178. // If `findCommentsByAuthor` rejects, we'll have the reason here
  5179. });
  5180. ```
  5181. Simple Example
  5182. --------------
  5183. Synchronous Example
  5184. ```javascript
  5185. var result;
  5186. try {
  5187. result = findResult();
  5188. // success
  5189. } catch(reason) {
  5190. // failure
  5191. }
  5192. ```
  5193. Errback Example
  5194. ```js
  5195. findResult(function(result, err){
  5196. if (err) {
  5197. // failure
  5198. } else {
  5199. // success
  5200. }
  5201. });
  5202. ```
  5203. Promise Example;
  5204. ```javascript
  5205. findResult().then(function(result){
  5206. // success
  5207. }, function(reason){
  5208. // failure
  5209. });
  5210. ```
  5211. Advanced Example
  5212. --------------
  5213. Synchronous Example
  5214. ```javascript
  5215. var author, books;
  5216. try {
  5217. author = findAuthor();
  5218. books = findBooksByAuthor(author);
  5219. // success
  5220. } catch(reason) {
  5221. // failure
  5222. }
  5223. ```
  5224. Errback Example
  5225. ```js
  5226. function foundBooks(books) {
  5227. }
  5228. function failure(reason) {
  5229. }
  5230. findAuthor(function(author, err){
  5231. if (err) {
  5232. failure(err);
  5233. // failure
  5234. } else {
  5235. try {
  5236. findBoooksByAuthor(author, function(books, err) {
  5237. if (err) {
  5238. failure(err);
  5239. } else {
  5240. try {
  5241. foundBooks(books);
  5242. } catch(reason) {
  5243. failure(reason);
  5244. }
  5245. }
  5246. });
  5247. } catch(error) {
  5248. failure(err);
  5249. }
  5250. // success
  5251. }
  5252. });
  5253. ```
  5254. Promise Example;
  5255. ```javascript
  5256. findAuthor().
  5257. then(findBooksByAuthor).
  5258. then(function(books){
  5259. // found books
  5260. }).catch(function(reason){
  5261. // something went wrong
  5262. });
  5263. ```
  5264. @method then
  5265. @param {Function} onFulfilled
  5266. @param {Function} onRejected
  5267. Useful for tooling.
  5268. @return {Promise}
  5269. */
  5270. then: function(onFulfillment, onRejection) {
  5271. var parent = this;
  5272. var state = parent._state;
  5273. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  5274. return this;
  5275. }
  5276. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  5277. var result = parent._result;
  5278. if (state) {
  5279. var callback = arguments[state - 1];
  5280. lib$es6$promise$asap$$asap(function(){
  5281. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  5282. });
  5283. } else {
  5284. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  5285. }
  5286. return child;
  5287. },
  5288. /**
  5289. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  5290. as the catch block of a try/catch statement.
  5291. ```js
  5292. function findAuthor(){
  5293. throw new Error('couldn't find that author');
  5294. }
  5295. // synchronous
  5296. try {
  5297. findAuthor();
  5298. } catch(reason) {
  5299. // something went wrong
  5300. }
  5301. // async with promises
  5302. findAuthor().catch(function(reason){
  5303. // something went wrong
  5304. });
  5305. ```
  5306. @method catch
  5307. @param {Function} onRejection
  5308. Useful for tooling.
  5309. @return {Promise}
  5310. */
  5311. 'catch': function(onRejection) {
  5312. return this.then(null, onRejection);
  5313. }
  5314. };
  5315. function lib$es6$promise$polyfill$$polyfill() {
  5316. var local;
  5317. if (typeof global !== 'undefined') {
  5318. local = global;
  5319. } else if (typeof self !== 'undefined') {
  5320. local = self;
  5321. } else {
  5322. try {
  5323. local = Function('return this')();
  5324. } catch (e) {
  5325. throw new Error('polyfill failed because global object is unavailable in this environment');
  5326. }
  5327. }
  5328. var P = local.Promise;
  5329. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  5330. return;
  5331. }
  5332. local.Promise = lib$es6$promise$promise$$default;
  5333. }
  5334. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  5335. var lib$es6$promise$umd$$ES6Promise = {
  5336. 'Promise': lib$es6$promise$promise$$default,
  5337. 'polyfill': lib$es6$promise$polyfill$$default
  5338. };
  5339. /* global define:true module:true window: true */
  5340. if (typeof define === 'function' && define['amd']) {
  5341. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  5342. } else if (typeof module !== 'undefined' && module['exports']) {
  5343. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  5344. } else if (typeof this !== 'undefined') {
  5345. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  5346. }
  5347. lib$es6$promise$polyfill$$default();
  5348. }).call(this);
  5349. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  5350. },{"_process":49}],24:[function(require,module,exports){
  5351. // Top level file is just a mixin of submodules & constants
  5352. 'use strict';
  5353. var assign = require('./lib/utils/common').assign;
  5354. var deflate = require('./lib/deflate');
  5355. var inflate = require('./lib/inflate');
  5356. var constants = require('./lib/zlib/constants');
  5357. var pako = {};
  5358. assign(pako, deflate, inflate, constants);
  5359. module.exports = pako;
  5360. },{"./lib/deflate":25,"./lib/inflate":26,"./lib/utils/common":27,"./lib/zlib/constants":30}],25:[function(require,module,exports){
  5361. 'use strict';
  5362. var zlib_deflate = require('./zlib/deflate.js');
  5363. var utils = require('./utils/common');
  5364. var strings = require('./utils/strings');
  5365. var msg = require('./zlib/messages');
  5366. var zstream = require('./zlib/zstream');
  5367. var toString = Object.prototype.toString;
  5368. /* Public constants ==========================================================*/
  5369. /* ===========================================================================*/
  5370. var Z_NO_FLUSH = 0;
  5371. var Z_FINISH = 4;
  5372. var Z_OK = 0;
  5373. var Z_STREAM_END = 1;
  5374. var Z_SYNC_FLUSH = 2;
  5375. var Z_DEFAULT_COMPRESSION = -1;
  5376. var Z_DEFAULT_STRATEGY = 0;
  5377. var Z_DEFLATED = 8;
  5378. /* ===========================================================================*/
  5379. /**
  5380. * class Deflate
  5381. *
  5382. * Generic JS-style wrapper for zlib calls. If you don't need
  5383. * streaming behaviour - use more simple functions: [[deflate]],
  5384. * [[deflateRaw]] and [[gzip]].
  5385. **/
  5386. /* internal
  5387. * Deflate.chunks -> Array
  5388. *
  5389. * Chunks of output data, if [[Deflate#onData]] not overriden.
  5390. **/
  5391. /**
  5392. * Deflate.result -> Uint8Array|Array
  5393. *
  5394. * Compressed result, generated by default [[Deflate#onData]]
  5395. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  5396. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  5397. * push a chunk with explicit flush (call [[Deflate#push]] with
  5398. * `Z_SYNC_FLUSH` param).
  5399. **/
  5400. /**
  5401. * Deflate.err -> Number
  5402. *
  5403. * Error code after deflate finished. 0 (Z_OK) on success.
  5404. * You will not need it in real life, because deflate errors
  5405. * are possible only on wrong options or bad `onData` / `onEnd`
  5406. * custom handlers.
  5407. **/
  5408. /**
  5409. * Deflate.msg -> String
  5410. *
  5411. * Error message, if [[Deflate.err]] != 0
  5412. **/
  5413. /**
  5414. * new Deflate(options)
  5415. * - options (Object): zlib deflate options.
  5416. *
  5417. * Creates new deflator instance with specified params. Throws exception
  5418. * on bad params. Supported options:
  5419. *
  5420. * - `level`
  5421. * - `windowBits`
  5422. * - `memLevel`
  5423. * - `strategy`
  5424. *
  5425. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5426. * for more information on these.
  5427. *
  5428. * Additional options, for internal needs:
  5429. *
  5430. * - `chunkSize` - size of generated data chunks (16K by default)
  5431. * - `raw` (Boolean) - do raw deflate
  5432. * - `gzip` (Boolean) - create gzip wrapper
  5433. * - `to` (String) - if equal to 'string', then result will be "binary string"
  5434. * (each char code [0..255])
  5435. * - `header` (Object) - custom header for gzip
  5436. * - `text` (Boolean) - true if compressed data believed to be text
  5437. * - `time` (Number) - modification time, unix timestamp
  5438. * - `os` (Number) - operation system code
  5439. * - `extra` (Array) - array of bytes with extra data (max 65536)
  5440. * - `name` (String) - file name (binary string)
  5441. * - `comment` (String) - comment (binary string)
  5442. * - `hcrc` (Boolean) - true if header crc should be added
  5443. *
  5444. * ##### Example:
  5445. *
  5446. * ```javascript
  5447. * var pako = require('pako')
  5448. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  5449. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  5450. *
  5451. * var deflate = new pako.Deflate({ level: 3});
  5452. *
  5453. * deflate.push(chunk1, false);
  5454. * deflate.push(chunk2, true); // true -> last chunk
  5455. *
  5456. * if (deflate.err) { throw new Error(deflate.err); }
  5457. *
  5458. * console.log(deflate.result);
  5459. * ```
  5460. **/
  5461. var Deflate = function(options) {
  5462. this.options = utils.assign({
  5463. level: Z_DEFAULT_COMPRESSION,
  5464. method: Z_DEFLATED,
  5465. chunkSize: 16384,
  5466. windowBits: 15,
  5467. memLevel: 8,
  5468. strategy: Z_DEFAULT_STRATEGY,
  5469. to: ''
  5470. }, options || {});
  5471. var opt = this.options;
  5472. if (opt.raw && (opt.windowBits > 0)) {
  5473. opt.windowBits = -opt.windowBits;
  5474. }
  5475. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  5476. opt.windowBits += 16;
  5477. }
  5478. this.err = 0; // error code, if happens (0 = Z_OK)
  5479. this.msg = ''; // error message
  5480. this.ended = false; // used to avoid multiple onEnd() calls
  5481. this.chunks = []; // chunks of compressed data
  5482. this.strm = new zstream();
  5483. this.strm.avail_out = 0;
  5484. var status = zlib_deflate.deflateInit2(
  5485. this.strm,
  5486. opt.level,
  5487. opt.method,
  5488. opt.windowBits,
  5489. opt.memLevel,
  5490. opt.strategy
  5491. );
  5492. if (status !== Z_OK) {
  5493. throw new Error(msg[status]);
  5494. }
  5495. if (opt.header) {
  5496. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  5497. }
  5498. };
  5499. /**
  5500. * Deflate#push(data[, mode]) -> Boolean
  5501. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  5502. * converted to utf8 byte sequence.
  5503. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  5504. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  5505. *
  5506. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  5507. * new compressed chunks. Returns `true` on success. The last data block must have
  5508. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  5509. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  5510. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  5511. *
  5512. * On fail call [[Deflate#onEnd]] with error code and return false.
  5513. *
  5514. * We strongly recommend to use `Uint8Array` on input for best speed (output
  5515. * array format is detected automatically). Also, don't skip last param and always
  5516. * use the same type in your code (boolean or number). That will improve JS speed.
  5517. *
  5518. * For regular `Array`-s make sure all elements are [0..255].
  5519. *
  5520. * ##### Example
  5521. *
  5522. * ```javascript
  5523. * push(chunk, false); // push one of data chunks
  5524. * ...
  5525. * push(chunk, true); // push last chunk
  5526. * ```
  5527. **/
  5528. Deflate.prototype.push = function(data, mode) {
  5529. var strm = this.strm;
  5530. var chunkSize = this.options.chunkSize;
  5531. var status, _mode;
  5532. if (this.ended) { return false; }
  5533. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  5534. // Convert data if needed
  5535. if (typeof data === 'string') {
  5536. // If we need to compress text, change encoding to utf8.
  5537. strm.input = strings.string2buf(data);
  5538. } else if (toString.call(data) === '[object ArrayBuffer]') {
  5539. strm.input = new Uint8Array(data);
  5540. } else {
  5541. strm.input = data;
  5542. }
  5543. strm.next_in = 0;
  5544. strm.avail_in = strm.input.length;
  5545. do {
  5546. if (strm.avail_out === 0) {
  5547. strm.output = new utils.Buf8(chunkSize);
  5548. strm.next_out = 0;
  5549. strm.avail_out = chunkSize;
  5550. }
  5551. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  5552. if (status !== Z_STREAM_END && status !== Z_OK) {
  5553. this.onEnd(status);
  5554. this.ended = true;
  5555. return false;
  5556. }
  5557. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  5558. if (this.options.to === 'string') {
  5559. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  5560. } else {
  5561. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  5562. }
  5563. }
  5564. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  5565. // Finalize on the last chunk.
  5566. if (_mode === Z_FINISH) {
  5567. status = zlib_deflate.deflateEnd(this.strm);
  5568. this.onEnd(status);
  5569. this.ended = true;
  5570. return status === Z_OK;
  5571. }
  5572. // callback interim results if Z_SYNC_FLUSH.
  5573. if (_mode === Z_SYNC_FLUSH) {
  5574. this.onEnd(Z_OK);
  5575. strm.avail_out = 0;
  5576. return true;
  5577. }
  5578. return true;
  5579. };
  5580. /**
  5581. * Deflate#onData(chunk) -> Void
  5582. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  5583. * on js engine support. When string output requested, each chunk
  5584. * will be string.
  5585. *
  5586. * By default, stores data blocks in `chunks[]` property and glue
  5587. * those in `onEnd`. Override this handler, if you need another behaviour.
  5588. **/
  5589. Deflate.prototype.onData = function(chunk) {
  5590. this.chunks.push(chunk);
  5591. };
  5592. /**
  5593. * Deflate#onEnd(status) -> Void
  5594. * - status (Number): deflate status. 0 (Z_OK) on success,
  5595. * other if not.
  5596. *
  5597. * Called once after you tell deflate that the input stream is
  5598. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  5599. * or if an error happened. By default - join collected chunks,
  5600. * free memory and fill `results` / `err` properties.
  5601. **/
  5602. Deflate.prototype.onEnd = function(status) {
  5603. // On success - join
  5604. if (status === Z_OK) {
  5605. if (this.options.to === 'string') {
  5606. this.result = this.chunks.join('');
  5607. } else {
  5608. this.result = utils.flattenChunks(this.chunks);
  5609. }
  5610. }
  5611. this.chunks = [];
  5612. this.err = status;
  5613. this.msg = this.strm.msg;
  5614. };
  5615. /**
  5616. * deflate(data[, options]) -> Uint8Array|Array|String
  5617. * - data (Uint8Array|Array|String): input data to compress.
  5618. * - options (Object): zlib deflate options.
  5619. *
  5620. * Compress `data` with deflate alrorythm and `options`.
  5621. *
  5622. * Supported options are:
  5623. *
  5624. * - level
  5625. * - windowBits
  5626. * - memLevel
  5627. * - strategy
  5628. *
  5629. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5630. * for more information on these.
  5631. *
  5632. * Sugar (options):
  5633. *
  5634. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  5635. * negative windowBits implicitly.
  5636. * - `to` (String) - if equal to 'string', then result will be "binary string"
  5637. * (each char code [0..255])
  5638. *
  5639. * ##### Example:
  5640. *
  5641. * ```javascript
  5642. * var pako = require('pako')
  5643. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  5644. *
  5645. * console.log(pako.deflate(data));
  5646. * ```
  5647. **/
  5648. function deflate(input, options) {
  5649. var deflator = new Deflate(options);
  5650. deflator.push(input, true);
  5651. // That will never happens, if you don't cheat with options :)
  5652. if (deflator.err) { throw deflator.msg; }
  5653. return deflator.result;
  5654. }
  5655. /**
  5656. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  5657. * - data (Uint8Array|Array|String): input data to compress.
  5658. * - options (Object): zlib deflate options.
  5659. *
  5660. * The same as [[deflate]], but creates raw data, without wrapper
  5661. * (header and adler32 crc).
  5662. **/
  5663. function deflateRaw(input, options) {
  5664. options = options || {};
  5665. options.raw = true;
  5666. return deflate(input, options);
  5667. }
  5668. /**
  5669. * gzip(data[, options]) -> Uint8Array|Array|String
  5670. * - data (Uint8Array|Array|String): input data to compress.
  5671. * - options (Object): zlib deflate options.
  5672. *
  5673. * The same as [[deflate]], but create gzip wrapper instead of
  5674. * deflate one.
  5675. **/
  5676. function gzip(input, options) {
  5677. options = options || {};
  5678. options.gzip = true;
  5679. return deflate(input, options);
  5680. }
  5681. exports.Deflate = Deflate;
  5682. exports.deflate = deflate;
  5683. exports.deflateRaw = deflateRaw;
  5684. exports.gzip = gzip;
  5685. },{"./utils/common":27,"./utils/strings":28,"./zlib/deflate.js":32,"./zlib/messages":37,"./zlib/zstream":39}],26:[function(require,module,exports){
  5686. 'use strict';
  5687. var zlib_inflate = require('./zlib/inflate.js');
  5688. var utils = require('./utils/common');
  5689. var strings = require('./utils/strings');
  5690. var c = require('./zlib/constants');
  5691. var msg = require('./zlib/messages');
  5692. var zstream = require('./zlib/zstream');
  5693. var gzheader = require('./zlib/gzheader');
  5694. var toString = Object.prototype.toString;
  5695. /**
  5696. * class Inflate
  5697. *
  5698. * Generic JS-style wrapper for zlib calls. If you don't need
  5699. * streaming behaviour - use more simple functions: [[inflate]]
  5700. * and [[inflateRaw]].
  5701. **/
  5702. /* internal
  5703. * inflate.chunks -> Array
  5704. *
  5705. * Chunks of output data, if [[Inflate#onData]] not overriden.
  5706. **/
  5707. /**
  5708. * Inflate.result -> Uint8Array|Array|String
  5709. *
  5710. * Uncompressed result, generated by default [[Inflate#onData]]
  5711. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  5712. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  5713. * push a chunk with explicit flush (call [[Inflate#push]] with
  5714. * `Z_SYNC_FLUSH` param).
  5715. **/
  5716. /**
  5717. * Inflate.err -> Number
  5718. *
  5719. * Error code after inflate finished. 0 (Z_OK) on success.
  5720. * Should be checked if broken data possible.
  5721. **/
  5722. /**
  5723. * Inflate.msg -> String
  5724. *
  5725. * Error message, if [[Inflate.err]] != 0
  5726. **/
  5727. /**
  5728. * new Inflate(options)
  5729. * - options (Object): zlib inflate options.
  5730. *
  5731. * Creates new inflator instance with specified params. Throws exception
  5732. * on bad params. Supported options:
  5733. *
  5734. * - `windowBits`
  5735. *
  5736. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5737. * for more information on these.
  5738. *
  5739. * Additional options, for internal needs:
  5740. *
  5741. * - `chunkSize` - size of generated data chunks (16K by default)
  5742. * - `raw` (Boolean) - do raw inflate
  5743. * - `to` (String) - if equal to 'string', then result will be converted
  5744. * from utf8 to utf16 (javascript) string. When string output requested,
  5745. * chunk length can differ from `chunkSize`, depending on content.
  5746. *
  5747. * By default, when no options set, autodetect deflate/gzip data format via
  5748. * wrapper header.
  5749. *
  5750. * ##### Example:
  5751. *
  5752. * ```javascript
  5753. * var pako = require('pako')
  5754. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  5755. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  5756. *
  5757. * var inflate = new pako.Inflate({ level: 3});
  5758. *
  5759. * inflate.push(chunk1, false);
  5760. * inflate.push(chunk2, true); // true -> last chunk
  5761. *
  5762. * if (inflate.err) { throw new Error(inflate.err); }
  5763. *
  5764. * console.log(inflate.result);
  5765. * ```
  5766. **/
  5767. var Inflate = function(options) {
  5768. this.options = utils.assign({
  5769. chunkSize: 16384,
  5770. windowBits: 0,
  5771. to: ''
  5772. }, options || {});
  5773. var opt = this.options;
  5774. // Force window size for `raw` data, if not set directly,
  5775. // because we have no header for autodetect.
  5776. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  5777. opt.windowBits = -opt.windowBits;
  5778. if (opt.windowBits === 0) { opt.windowBits = -15; }
  5779. }
  5780. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  5781. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  5782. !(options && options.windowBits)) {
  5783. opt.windowBits += 32;
  5784. }
  5785. // Gzip header has no info about windows size, we can do autodetect only
  5786. // for deflate. So, if window size not set, force it to max when gzip possible
  5787. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  5788. // bit 3 (16) -> gzipped data
  5789. // bit 4 (32) -> autodetect gzip/deflate
  5790. if ((opt.windowBits & 15) === 0) {
  5791. opt.windowBits |= 15;
  5792. }
  5793. }
  5794. this.err = 0; // error code, if happens (0 = Z_OK)
  5795. this.msg = ''; // error message
  5796. this.ended = false; // used to avoid multiple onEnd() calls
  5797. this.chunks = []; // chunks of compressed data
  5798. this.strm = new zstream();
  5799. this.strm.avail_out = 0;
  5800. var status = zlib_inflate.inflateInit2(
  5801. this.strm,
  5802. opt.windowBits
  5803. );
  5804. if (status !== c.Z_OK) {
  5805. throw new Error(msg[status]);
  5806. }
  5807. this.header = new gzheader();
  5808. zlib_inflate.inflateGetHeader(this.strm, this.header);
  5809. };
  5810. /**
  5811. * Inflate#push(data[, mode]) -> Boolean
  5812. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  5813. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  5814. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  5815. *
  5816. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  5817. * new output chunks. Returns `true` on success. The last data block must have
  5818. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  5819. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  5820. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  5821. *
  5822. * On fail call [[Inflate#onEnd]] with error code and return false.
  5823. *
  5824. * We strongly recommend to use `Uint8Array` on input for best speed (output
  5825. * format is detected automatically). Also, don't skip last param and always
  5826. * use the same type in your code (boolean or number). That will improve JS speed.
  5827. *
  5828. * For regular `Array`-s make sure all elements are [0..255].
  5829. *
  5830. * ##### Example
  5831. *
  5832. * ```javascript
  5833. * push(chunk, false); // push one of data chunks
  5834. * ...
  5835. * push(chunk, true); // push last chunk
  5836. * ```
  5837. **/
  5838. Inflate.prototype.push = function(data, mode) {
  5839. var strm = this.strm;
  5840. var chunkSize = this.options.chunkSize;
  5841. var status, _mode;
  5842. var next_out_utf8, tail, utf8str;
  5843. if (this.ended) { return false; }
  5844. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  5845. // Convert data if needed
  5846. if (typeof data === 'string') {
  5847. // Only binary strings can be decompressed on practice
  5848. strm.input = strings.binstring2buf(data);
  5849. } else if (toString.call(data) === '[object ArrayBuffer]') {
  5850. strm.input = new Uint8Array(data);
  5851. } else {
  5852. strm.input = data;
  5853. }
  5854. strm.next_in = 0;
  5855. strm.avail_in = strm.input.length;
  5856. do {
  5857. if (strm.avail_out === 0) {
  5858. strm.output = new utils.Buf8(chunkSize);
  5859. strm.next_out = 0;
  5860. strm.avail_out = chunkSize;
  5861. }
  5862. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  5863. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  5864. this.onEnd(status);
  5865. this.ended = true;
  5866. return false;
  5867. }
  5868. if (strm.next_out) {
  5869. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  5870. if (this.options.to === 'string') {
  5871. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  5872. tail = strm.next_out - next_out_utf8;
  5873. utf8str = strings.buf2string(strm.output, next_out_utf8);
  5874. // move tail
  5875. strm.next_out = tail;
  5876. strm.avail_out = chunkSize - tail;
  5877. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  5878. this.onData(utf8str);
  5879. } else {
  5880. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  5881. }
  5882. }
  5883. }
  5884. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  5885. if (status === c.Z_STREAM_END) {
  5886. _mode = c.Z_FINISH;
  5887. }
  5888. // Finalize on the last chunk.
  5889. if (_mode === c.Z_FINISH) {
  5890. status = zlib_inflate.inflateEnd(this.strm);
  5891. this.onEnd(status);
  5892. this.ended = true;
  5893. return status === c.Z_OK;
  5894. }
  5895. // callback interim results if Z_SYNC_FLUSH.
  5896. if (_mode === c.Z_SYNC_FLUSH) {
  5897. this.onEnd(c.Z_OK);
  5898. strm.avail_out = 0;
  5899. return true;
  5900. }
  5901. return true;
  5902. };
  5903. /**
  5904. * Inflate#onData(chunk) -> Void
  5905. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  5906. * on js engine support. When string output requested, each chunk
  5907. * will be string.
  5908. *
  5909. * By default, stores data blocks in `chunks[]` property and glue
  5910. * those in `onEnd`. Override this handler, if you need another behaviour.
  5911. **/
  5912. Inflate.prototype.onData = function(chunk) {
  5913. this.chunks.push(chunk);
  5914. };
  5915. /**
  5916. * Inflate#onEnd(status) -> Void
  5917. * - status (Number): inflate status. 0 (Z_OK) on success,
  5918. * other if not.
  5919. *
  5920. * Called either after you tell inflate that the input stream is
  5921. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  5922. * or if an error happened. By default - join collected chunks,
  5923. * free memory and fill `results` / `err` properties.
  5924. **/
  5925. Inflate.prototype.onEnd = function(status) {
  5926. // On success - join
  5927. if (status === c.Z_OK) {
  5928. if (this.options.to === 'string') {
  5929. // Glue & convert here, until we teach pako to send
  5930. // utf8 alligned strings to onData
  5931. this.result = this.chunks.join('');
  5932. } else {
  5933. this.result = utils.flattenChunks(this.chunks);
  5934. }
  5935. }
  5936. this.chunks = [];
  5937. this.err = status;
  5938. this.msg = this.strm.msg;
  5939. };
  5940. /**
  5941. * inflate(data[, options]) -> Uint8Array|Array|String
  5942. * - data (Uint8Array|Array|String): input data to decompress.
  5943. * - options (Object): zlib inflate options.
  5944. *
  5945. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  5946. * format via wrapper header by default. That's why we don't provide
  5947. * separate `ungzip` method.
  5948. *
  5949. * Supported options are:
  5950. *
  5951. * - windowBits
  5952. *
  5953. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5954. * for more information.
  5955. *
  5956. * Sugar (options):
  5957. *
  5958. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  5959. * negative windowBits implicitly.
  5960. * - `to` (String) - if equal to 'string', then result will be converted
  5961. * from utf8 to utf16 (javascript) string. When string output requested,
  5962. * chunk length can differ from `chunkSize`, depending on content.
  5963. *
  5964. *
  5965. * ##### Example:
  5966. *
  5967. * ```javascript
  5968. * var pako = require('pako')
  5969. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  5970. * , output;
  5971. *
  5972. * try {
  5973. * output = pako.inflate(input);
  5974. * } catch (err)
  5975. * console.log(err);
  5976. * }
  5977. * ```
  5978. **/
  5979. function inflate(input, options) {
  5980. var inflator = new Inflate(options);
  5981. inflator.push(input, true);
  5982. // That will never happens, if you don't cheat with options :)
  5983. if (inflator.err) { throw inflator.msg; }
  5984. return inflator.result;
  5985. }
  5986. /**
  5987. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  5988. * - data (Uint8Array|Array|String): input data to decompress.
  5989. * - options (Object): zlib inflate options.
  5990. *
  5991. * The same as [[inflate]], but creates raw data, without wrapper
  5992. * (header and adler32 crc).
  5993. **/
  5994. function inflateRaw(input, options) {
  5995. options = options || {};
  5996. options.raw = true;
  5997. return inflate(input, options);
  5998. }
  5999. /**
  6000. * ungzip(data[, options]) -> Uint8Array|Array|String
  6001. * - data (Uint8Array|Array|String): input data to decompress.
  6002. * - options (Object): zlib inflate options.
  6003. *
  6004. * Just shortcut to [[inflate]], because it autodetects format
  6005. * by header.content. Done for convenience.
  6006. **/
  6007. exports.Inflate = Inflate;
  6008. exports.inflate = inflate;
  6009. exports.inflateRaw = inflateRaw;
  6010. exports.ungzip = inflate;
  6011. },{"./utils/common":27,"./utils/strings":28,"./zlib/constants":30,"./zlib/gzheader":33,"./zlib/inflate.js":35,"./zlib/messages":37,"./zlib/zstream":39}],27:[function(require,module,exports){
  6012. 'use strict';
  6013. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  6014. (typeof Uint16Array !== 'undefined') &&
  6015. (typeof Int32Array !== 'undefined');
  6016. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  6017. var sources = Array.prototype.slice.call(arguments, 1);
  6018. while (sources.length) {
  6019. var source = sources.shift();
  6020. if (!source) { continue; }
  6021. if (typeof source !== 'object') {
  6022. throw new TypeError(source + 'must be non-object');
  6023. }
  6024. for (var p in source) {
  6025. if (source.hasOwnProperty(p)) {
  6026. obj[p] = source[p];
  6027. }
  6028. }
  6029. }
  6030. return obj;
  6031. };
  6032. // reduce buffer size, avoiding mem copy
  6033. exports.shrinkBuf = function (buf, size) {
  6034. if (buf.length === size) { return buf; }
  6035. if (buf.subarray) { return buf.subarray(0, size); }
  6036. buf.length = size;
  6037. return buf;
  6038. };
  6039. var fnTyped = {
  6040. arraySet: function (dest, src, src_offs, len, dest_offs) {
  6041. if (src.subarray && dest.subarray) {
  6042. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  6043. return;
  6044. }
  6045. // Fallback to ordinary array
  6046. for (var i=0; i<len; i++) {
  6047. dest[dest_offs + i] = src[src_offs + i];
  6048. }
  6049. },
  6050. // Join array of chunks to single array.
  6051. flattenChunks: function(chunks) {
  6052. var i, l, len, pos, chunk, result;
  6053. // calculate data length
  6054. len = 0;
  6055. for (i=0, l=chunks.length; i<l; i++) {
  6056. len += chunks[i].length;
  6057. }
  6058. // join chunks
  6059. result = new Uint8Array(len);
  6060. pos = 0;
  6061. for (i=0, l=chunks.length; i<l; i++) {
  6062. chunk = chunks[i];
  6063. result.set(chunk, pos);
  6064. pos += chunk.length;
  6065. }
  6066. return result;
  6067. }
  6068. };
  6069. var fnUntyped = {
  6070. arraySet: function (dest, src, src_offs, len, dest_offs) {
  6071. for (var i=0; i<len; i++) {
  6072. dest[dest_offs + i] = src[src_offs + i];
  6073. }
  6074. },
  6075. // Join array of chunks to single array.
  6076. flattenChunks: function(chunks) {
  6077. return [].concat.apply([], chunks);
  6078. }
  6079. };
  6080. // Enable/Disable typed arrays use, for testing
  6081. //
  6082. exports.setTyped = function (on) {
  6083. if (on) {
  6084. exports.Buf8 = Uint8Array;
  6085. exports.Buf16 = Uint16Array;
  6086. exports.Buf32 = Int32Array;
  6087. exports.assign(exports, fnTyped);
  6088. } else {
  6089. exports.Buf8 = Array;
  6090. exports.Buf16 = Array;
  6091. exports.Buf32 = Array;
  6092. exports.assign(exports, fnUntyped);
  6093. }
  6094. };
  6095. exports.setTyped(TYPED_OK);
  6096. },{}],28:[function(require,module,exports){
  6097. // String encode/decode helpers
  6098. 'use strict';
  6099. var utils = require('./common');
  6100. // Quick check if we can use fast array to bin string conversion
  6101. //
  6102. // - apply(Array) can fail on Android 2.2
  6103. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  6104. //
  6105. var STR_APPLY_OK = true;
  6106. var STR_APPLY_UIA_OK = true;
  6107. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  6108. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  6109. // Table with utf8 lengths (calculated by first byte of sequence)
  6110. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  6111. // because max possible codepoint is 0x10ffff
  6112. var _utf8len = new utils.Buf8(256);
  6113. for (var q=0; q<256; q++) {
  6114. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  6115. }
  6116. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  6117. // convert string to array (typed, when possible)
  6118. exports.string2buf = function (str) {
  6119. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  6120. // count binary size
  6121. for (m_pos = 0; m_pos < str_len; m_pos++) {
  6122. c = str.charCodeAt(m_pos);
  6123. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  6124. c2 = str.charCodeAt(m_pos+1);
  6125. if ((c2 & 0xfc00) === 0xdc00) {
  6126. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  6127. m_pos++;
  6128. }
  6129. }
  6130. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  6131. }
  6132. // allocate buffer
  6133. buf = new utils.Buf8(buf_len);
  6134. // convert
  6135. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  6136. c = str.charCodeAt(m_pos);
  6137. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  6138. c2 = str.charCodeAt(m_pos+1);
  6139. if ((c2 & 0xfc00) === 0xdc00) {
  6140. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  6141. m_pos++;
  6142. }
  6143. }
  6144. if (c < 0x80) {
  6145. /* one byte */
  6146. buf[i++] = c;
  6147. } else if (c < 0x800) {
  6148. /* two bytes */
  6149. buf[i++] = 0xC0 | (c >>> 6);
  6150. buf[i++] = 0x80 | (c & 0x3f);
  6151. } else if (c < 0x10000) {
  6152. /* three bytes */
  6153. buf[i++] = 0xE0 | (c >>> 12);
  6154. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  6155. buf[i++] = 0x80 | (c & 0x3f);
  6156. } else {
  6157. /* four bytes */
  6158. buf[i++] = 0xf0 | (c >>> 18);
  6159. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  6160. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  6161. buf[i++] = 0x80 | (c & 0x3f);
  6162. }
  6163. }
  6164. return buf;
  6165. };
  6166. // Helper (used in 2 places)
  6167. function buf2binstring(buf, len) {
  6168. // use fallback for big arrays to avoid stack overflow
  6169. if (len < 65537) {
  6170. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  6171. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  6172. }
  6173. }
  6174. var result = '';
  6175. for (var i=0; i < len; i++) {
  6176. result += String.fromCharCode(buf[i]);
  6177. }
  6178. return result;
  6179. }
  6180. // Convert byte array to binary string
  6181. exports.buf2binstring = function(buf) {
  6182. return buf2binstring(buf, buf.length);
  6183. };
  6184. // Convert binary string (typed, when possible)
  6185. exports.binstring2buf = function(str) {
  6186. var buf = new utils.Buf8(str.length);
  6187. for (var i=0, len=buf.length; i < len; i++) {
  6188. buf[i] = str.charCodeAt(i);
  6189. }
  6190. return buf;
  6191. };
  6192. // convert array to string
  6193. exports.buf2string = function (buf, max) {
  6194. var i, out, c, c_len;
  6195. var len = max || buf.length;
  6196. // Reserve max possible length (2 words per char)
  6197. // NB: by unknown reasons, Array is significantly faster for
  6198. // String.fromCharCode.apply than Uint16Array.
  6199. var utf16buf = new Array(len*2);
  6200. for (out=0, i=0; i<len;) {
  6201. c = buf[i++];
  6202. // quick process ascii
  6203. if (c < 0x80) { utf16buf[out++] = c; continue; }
  6204. c_len = _utf8len[c];
  6205. // skip 5 & 6 byte codes
  6206. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  6207. // apply mask on first byte
  6208. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  6209. // join the rest
  6210. while (c_len > 1 && i < len) {
  6211. c = (c << 6) | (buf[i++] & 0x3f);
  6212. c_len--;
  6213. }
  6214. // terminated by end of string?
  6215. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  6216. if (c < 0x10000) {
  6217. utf16buf[out++] = c;
  6218. } else {
  6219. c -= 0x10000;
  6220. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  6221. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  6222. }
  6223. }
  6224. return buf2binstring(utf16buf, out);
  6225. };
  6226. // Calculate max possible position in utf8 buffer,
  6227. // that will not break sequence. If that's not possible
  6228. // - (very small limits) return max size as is.
  6229. //
  6230. // buf[] - utf8 bytes array
  6231. // max - length limit (mandatory);
  6232. exports.utf8border = function(buf, max) {
  6233. var pos;
  6234. max = max || buf.length;
  6235. if (max > buf.length) { max = buf.length; }
  6236. // go back from last position, until start of sequence found
  6237. pos = max-1;
  6238. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  6239. // Fuckup - very small and broken sequence,
  6240. // return max, because we should return something anyway.
  6241. if (pos < 0) { return max; }
  6242. // If we came to start of buffer - that means vuffer is too small,
  6243. // return max too.
  6244. if (pos === 0) { return max; }
  6245. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  6246. };
  6247. },{"./common":27}],29:[function(require,module,exports){
  6248. 'use strict';
  6249. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  6250. // It doesn't worth to make additional optimizationa as in original.
  6251. // Small size is preferable.
  6252. function adler32(adler, buf, len, pos) {
  6253. var s1 = (adler & 0xffff) |0,
  6254. s2 = ((adler >>> 16) & 0xffff) |0,
  6255. n = 0;
  6256. while (len !== 0) {
  6257. // Set limit ~ twice less than 5552, to keep
  6258. // s2 in 31-bits, because we force signed ints.
  6259. // in other case %= will fail.
  6260. n = len > 2000 ? 2000 : len;
  6261. len -= n;
  6262. do {
  6263. s1 = (s1 + buf[pos++]) |0;
  6264. s2 = (s2 + s1) |0;
  6265. } while (--n);
  6266. s1 %= 65521;
  6267. s2 %= 65521;
  6268. }
  6269. return (s1 | (s2 << 16)) |0;
  6270. }
  6271. module.exports = adler32;
  6272. },{}],30:[function(require,module,exports){
  6273. module.exports = {
  6274. /* Allowed flush values; see deflate() and inflate() below for details */
  6275. Z_NO_FLUSH: 0,
  6276. Z_PARTIAL_FLUSH: 1,
  6277. Z_SYNC_FLUSH: 2,
  6278. Z_FULL_FLUSH: 3,
  6279. Z_FINISH: 4,
  6280. Z_BLOCK: 5,
  6281. Z_TREES: 6,
  6282. /* Return codes for the compression/decompression functions. Negative values
  6283. * are errors, positive values are used for special but normal events.
  6284. */
  6285. Z_OK: 0,
  6286. Z_STREAM_END: 1,
  6287. Z_NEED_DICT: 2,
  6288. Z_ERRNO: -1,
  6289. Z_STREAM_ERROR: -2,
  6290. Z_DATA_ERROR: -3,
  6291. //Z_MEM_ERROR: -4,
  6292. Z_BUF_ERROR: -5,
  6293. //Z_VERSION_ERROR: -6,
  6294. /* compression levels */
  6295. Z_NO_COMPRESSION: 0,
  6296. Z_BEST_SPEED: 1,
  6297. Z_BEST_COMPRESSION: 9,
  6298. Z_DEFAULT_COMPRESSION: -1,
  6299. Z_FILTERED: 1,
  6300. Z_HUFFMAN_ONLY: 2,
  6301. Z_RLE: 3,
  6302. Z_FIXED: 4,
  6303. Z_DEFAULT_STRATEGY: 0,
  6304. /* Possible values of the data_type field (though see inflate()) */
  6305. Z_BINARY: 0,
  6306. Z_TEXT: 1,
  6307. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  6308. Z_UNKNOWN: 2,
  6309. /* The deflate compression method */
  6310. Z_DEFLATED: 8
  6311. //Z_NULL: null // Use -1 or null inline, depending on var type
  6312. };
  6313. },{}],31:[function(require,module,exports){
  6314. 'use strict';
  6315. // Note: we can't get significant speed boost here.
  6316. // So write code to minimize size - no pregenerated tables
  6317. // and array tools dependencies.
  6318. // Use ordinary array, since untyped makes no boost here
  6319. function makeTable() {
  6320. var c, table = [];
  6321. for (var n =0; n < 256; n++) {
  6322. c = n;
  6323. for (var k =0; k < 8; k++) {
  6324. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  6325. }
  6326. table[n] = c;
  6327. }
  6328. return table;
  6329. }
  6330. // Create table on load. Just 255 signed longs. Not a problem.
  6331. var crcTable = makeTable();
  6332. function crc32(crc, buf, len, pos) {
  6333. var t = crcTable,
  6334. end = pos + len;
  6335. crc = crc ^ (-1);
  6336. for (var i = pos; i < end; i++) {
  6337. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  6338. }
  6339. return (crc ^ (-1)); // >>> 0;
  6340. }
  6341. module.exports = crc32;
  6342. },{}],32:[function(require,module,exports){
  6343. 'use strict';
  6344. var utils = require('../utils/common');
  6345. var trees = require('./trees');
  6346. var adler32 = require('./adler32');
  6347. var crc32 = require('./crc32');
  6348. var msg = require('./messages');
  6349. /* Public constants ==========================================================*/
  6350. /* ===========================================================================*/
  6351. /* Allowed flush values; see deflate() and inflate() below for details */
  6352. var Z_NO_FLUSH = 0;
  6353. var Z_PARTIAL_FLUSH = 1;
  6354. //var Z_SYNC_FLUSH = 2;
  6355. var Z_FULL_FLUSH = 3;
  6356. var Z_FINISH = 4;
  6357. var Z_BLOCK = 5;
  6358. //var Z_TREES = 6;
  6359. /* Return codes for the compression/decompression functions. Negative values
  6360. * are errors, positive values are used for special but normal events.
  6361. */
  6362. var Z_OK = 0;
  6363. var Z_STREAM_END = 1;
  6364. //var Z_NEED_DICT = 2;
  6365. //var Z_ERRNO = -1;
  6366. var Z_STREAM_ERROR = -2;
  6367. var Z_DATA_ERROR = -3;
  6368. //var Z_MEM_ERROR = -4;
  6369. var Z_BUF_ERROR = -5;
  6370. //var Z_VERSION_ERROR = -6;
  6371. /* compression levels */
  6372. //var Z_NO_COMPRESSION = 0;
  6373. //var Z_BEST_SPEED = 1;
  6374. //var Z_BEST_COMPRESSION = 9;
  6375. var Z_DEFAULT_COMPRESSION = -1;
  6376. var Z_FILTERED = 1;
  6377. var Z_HUFFMAN_ONLY = 2;
  6378. var Z_RLE = 3;
  6379. var Z_FIXED = 4;
  6380. var Z_DEFAULT_STRATEGY = 0;
  6381. /* Possible values of the data_type field (though see inflate()) */
  6382. //var Z_BINARY = 0;
  6383. //var Z_TEXT = 1;
  6384. //var Z_ASCII = 1; // = Z_TEXT
  6385. var Z_UNKNOWN = 2;
  6386. /* The deflate compression method */
  6387. var Z_DEFLATED = 8;
  6388. /*============================================================================*/
  6389. var MAX_MEM_LEVEL = 9;
  6390. /* Maximum value for memLevel in deflateInit2 */
  6391. var MAX_WBITS = 15;
  6392. /* 32K LZ77 window */
  6393. var DEF_MEM_LEVEL = 8;
  6394. var LENGTH_CODES = 29;
  6395. /* number of length codes, not counting the special END_BLOCK code */
  6396. var LITERALS = 256;
  6397. /* number of literal bytes 0..255 */
  6398. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  6399. /* number of Literal or Length codes, including the END_BLOCK code */
  6400. var D_CODES = 30;
  6401. /* number of distance codes */
  6402. var BL_CODES = 19;
  6403. /* number of codes used to transfer the bit lengths */
  6404. var HEAP_SIZE = 2*L_CODES + 1;
  6405. /* maximum heap size */
  6406. var MAX_BITS = 15;
  6407. /* All codes must not exceed MAX_BITS bits */
  6408. var MIN_MATCH = 3;
  6409. var MAX_MATCH = 258;
  6410. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  6411. var PRESET_DICT = 0x20;
  6412. var INIT_STATE = 42;
  6413. var EXTRA_STATE = 69;
  6414. var NAME_STATE = 73;
  6415. var COMMENT_STATE = 91;
  6416. var HCRC_STATE = 103;
  6417. var BUSY_STATE = 113;
  6418. var FINISH_STATE = 666;
  6419. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  6420. var BS_BLOCK_DONE = 2; /* block flush performed */
  6421. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  6422. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  6423. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  6424. function err(strm, errorCode) {
  6425. strm.msg = msg[errorCode];
  6426. return errorCode;
  6427. }
  6428. function rank(f) {
  6429. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  6430. }
  6431. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  6432. /* =========================================================================
  6433. * Flush as much pending output as possible. All deflate() output goes
  6434. * through this function so some applications may wish to modify it
  6435. * to avoid allocating a large strm->output buffer and copying into it.
  6436. * (See also read_buf()).
  6437. */
  6438. function flush_pending(strm) {
  6439. var s = strm.state;
  6440. //_tr_flush_bits(s);
  6441. var len = s.pending;
  6442. if (len > strm.avail_out) {
  6443. len = strm.avail_out;
  6444. }
  6445. if (len === 0) { return; }
  6446. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  6447. strm.next_out += len;
  6448. s.pending_out += len;
  6449. strm.total_out += len;
  6450. strm.avail_out -= len;
  6451. s.pending -= len;
  6452. if (s.pending === 0) {
  6453. s.pending_out = 0;
  6454. }
  6455. }
  6456. function flush_block_only (s, last) {
  6457. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  6458. s.block_start = s.strstart;
  6459. flush_pending(s.strm);
  6460. }
  6461. function put_byte(s, b) {
  6462. s.pending_buf[s.pending++] = b;
  6463. }
  6464. /* =========================================================================
  6465. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  6466. * IN assertion: the stream state is correct and there is enough room in
  6467. * pending_buf.
  6468. */
  6469. function putShortMSB(s, b) {
  6470. // put_byte(s, (Byte)(b >> 8));
  6471. // put_byte(s, (Byte)(b & 0xff));
  6472. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  6473. s.pending_buf[s.pending++] = b & 0xff;
  6474. }
  6475. /* ===========================================================================
  6476. * Read a new buffer from the current input stream, update the adler32
  6477. * and total number of bytes read. All deflate() input goes through
  6478. * this function so some applications may wish to modify it to avoid
  6479. * allocating a large strm->input buffer and copying from it.
  6480. * (See also flush_pending()).
  6481. */
  6482. function read_buf(strm, buf, start, size) {
  6483. var len = strm.avail_in;
  6484. if (len > size) { len = size; }
  6485. if (len === 0) { return 0; }
  6486. strm.avail_in -= len;
  6487. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  6488. if (strm.state.wrap === 1) {
  6489. strm.adler = adler32(strm.adler, buf, len, start);
  6490. }
  6491. else if (strm.state.wrap === 2) {
  6492. strm.adler = crc32(strm.adler, buf, len, start);
  6493. }
  6494. strm.next_in += len;
  6495. strm.total_in += len;
  6496. return len;
  6497. }
  6498. /* ===========================================================================
  6499. * Set match_start to the longest match starting at the given string and
  6500. * return its length. Matches shorter or equal to prev_length are discarded,
  6501. * in which case the result is equal to prev_length and match_start is
  6502. * garbage.
  6503. * IN assertions: cur_match is the head of the hash chain for the current
  6504. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  6505. * OUT assertion: the match length is not greater than s->lookahead.
  6506. */
  6507. function longest_match(s, cur_match) {
  6508. var chain_length = s.max_chain_length; /* max hash chain length */
  6509. var scan = s.strstart; /* current string */
  6510. var match; /* matched string */
  6511. var len; /* length of current match */
  6512. var best_len = s.prev_length; /* best match length so far */
  6513. var nice_match = s.nice_match; /* stop if match long enough */
  6514. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  6515. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  6516. var _win = s.window; // shortcut
  6517. var wmask = s.w_mask;
  6518. var prev = s.prev;
  6519. /* Stop when cur_match becomes <= limit. To simplify the code,
  6520. * we prevent matches with the string of window index 0.
  6521. */
  6522. var strend = s.strstart + MAX_MATCH;
  6523. var scan_end1 = _win[scan + best_len - 1];
  6524. var scan_end = _win[scan + best_len];
  6525. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  6526. * It is easy to get rid of this optimization if necessary.
  6527. */
  6528. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  6529. /* Do not waste too much time if we already have a good match: */
  6530. if (s.prev_length >= s.good_match) {
  6531. chain_length >>= 2;
  6532. }
  6533. /* Do not look for matches beyond the end of the input. This is necessary
  6534. * to make deflate deterministic.
  6535. */
  6536. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  6537. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  6538. do {
  6539. // Assert(cur_match < s->strstart, "no future");
  6540. match = cur_match;
  6541. /* Skip to next match if the match length cannot increase
  6542. * or if the match length is less than 2. Note that the checks below
  6543. * for insufficient lookahead only occur occasionally for performance
  6544. * reasons. Therefore uninitialized memory will be accessed, and
  6545. * conditional jumps will be made that depend on those values.
  6546. * However the length of the match is limited to the lookahead, so
  6547. * the output of deflate is not affected by the uninitialized values.
  6548. */
  6549. if (_win[match + best_len] !== scan_end ||
  6550. _win[match + best_len - 1] !== scan_end1 ||
  6551. _win[match] !== _win[scan] ||
  6552. _win[++match] !== _win[scan + 1]) {
  6553. continue;
  6554. }
  6555. /* The check at best_len-1 can be removed because it will be made
  6556. * again later. (This heuristic is not always a win.)
  6557. * It is not necessary to compare scan[2] and match[2] since they
  6558. * are always equal when the other bytes match, given that
  6559. * the hash keys are equal and that HASH_BITS >= 8.
  6560. */
  6561. scan += 2;
  6562. match++;
  6563. // Assert(*scan == *match, "match[2]?");
  6564. /* We check for insufficient lookahead only every 8th comparison;
  6565. * the 256th check will be made at strstart+258.
  6566. */
  6567. do {
  6568. /*jshint noempty:false*/
  6569. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6570. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6571. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6572. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6573. scan < strend);
  6574. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  6575. len = MAX_MATCH - (strend - scan);
  6576. scan = strend - MAX_MATCH;
  6577. if (len > best_len) {
  6578. s.match_start = cur_match;
  6579. best_len = len;
  6580. if (len >= nice_match) {
  6581. break;
  6582. }
  6583. scan_end1 = _win[scan + best_len - 1];
  6584. scan_end = _win[scan + best_len];
  6585. }
  6586. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  6587. if (best_len <= s.lookahead) {
  6588. return best_len;
  6589. }
  6590. return s.lookahead;
  6591. }
  6592. /* ===========================================================================
  6593. * Fill the window when the lookahead becomes insufficient.
  6594. * Updates strstart and lookahead.
  6595. *
  6596. * IN assertion: lookahead < MIN_LOOKAHEAD
  6597. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  6598. * At least one byte has been read, or avail_in == 0; reads are
  6599. * performed for at least two bytes (required for the zip translate_eol
  6600. * option -- not supported here).
  6601. */
  6602. function fill_window(s) {
  6603. var _w_size = s.w_size;
  6604. var p, n, m, more, str;
  6605. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  6606. do {
  6607. more = s.window_size - s.lookahead - s.strstart;
  6608. // JS ints have 32 bit, block below not needed
  6609. /* Deal with !@#$% 64K limit: */
  6610. //if (sizeof(int) <= 2) {
  6611. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  6612. // more = wsize;
  6613. //
  6614. // } else if (more == (unsigned)(-1)) {
  6615. // /* Very unlikely, but possible on 16 bit machine if
  6616. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  6617. // */
  6618. // more--;
  6619. // }
  6620. //}
  6621. /* If the window is almost full and there is insufficient lookahead,
  6622. * move the upper half to the lower one to make room in the upper half.
  6623. */
  6624. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  6625. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  6626. s.match_start -= _w_size;
  6627. s.strstart -= _w_size;
  6628. /* we now have strstart >= MAX_DIST */
  6629. s.block_start -= _w_size;
  6630. /* Slide the hash table (could be avoided with 32 bit values
  6631. at the expense of memory usage). We slide even when level == 0
  6632. to keep the hash table consistent if we switch back to level > 0
  6633. later. (Using level 0 permanently is not an optimal usage of
  6634. zlib, so we don't care about this pathological case.)
  6635. */
  6636. n = s.hash_size;
  6637. p = n;
  6638. do {
  6639. m = s.head[--p];
  6640. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  6641. } while (--n);
  6642. n = _w_size;
  6643. p = n;
  6644. do {
  6645. m = s.prev[--p];
  6646. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  6647. /* If n is not on any hash chain, prev[n] is garbage but
  6648. * its value will never be used.
  6649. */
  6650. } while (--n);
  6651. more += _w_size;
  6652. }
  6653. if (s.strm.avail_in === 0) {
  6654. break;
  6655. }
  6656. /* If there was no sliding:
  6657. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  6658. * more == window_size - lookahead - strstart
  6659. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  6660. * => more >= window_size - 2*WSIZE + 2
  6661. * In the BIG_MEM or MMAP case (not yet supported),
  6662. * window_size == input_size + MIN_LOOKAHEAD &&
  6663. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  6664. * Otherwise, window_size == 2*WSIZE so more >= 2.
  6665. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  6666. */
  6667. //Assert(more >= 2, "more < 2");
  6668. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  6669. s.lookahead += n;
  6670. /* Initialize the hash value now that we have some input: */
  6671. if (s.lookahead + s.insert >= MIN_MATCH) {
  6672. str = s.strstart - s.insert;
  6673. s.ins_h = s.window[str];
  6674. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  6675. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  6676. //#if MIN_MATCH != 3
  6677. // Call update_hash() MIN_MATCH-3 more times
  6678. //#endif
  6679. while (s.insert) {
  6680. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  6681. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  6682. s.prev[str & s.w_mask] = s.head[s.ins_h];
  6683. s.head[s.ins_h] = str;
  6684. str++;
  6685. s.insert--;
  6686. if (s.lookahead + s.insert < MIN_MATCH) {
  6687. break;
  6688. }
  6689. }
  6690. }
  6691. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  6692. * but this is not important since only literal bytes will be emitted.
  6693. */
  6694. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  6695. /* If the WIN_INIT bytes after the end of the current data have never been
  6696. * written, then zero those bytes in order to avoid memory check reports of
  6697. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  6698. * the longest match routines. Update the high water mark for the next
  6699. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  6700. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  6701. */
  6702. // if (s.high_water < s.window_size) {
  6703. // var curr = s.strstart + s.lookahead;
  6704. // var init = 0;
  6705. //
  6706. // if (s.high_water < curr) {
  6707. // /* Previous high water mark below current data -- zero WIN_INIT
  6708. // * bytes or up to end of window, whichever is less.
  6709. // */
  6710. // init = s.window_size - curr;
  6711. // if (init > WIN_INIT)
  6712. // init = WIN_INIT;
  6713. // zmemzero(s->window + curr, (unsigned)init);
  6714. // s->high_water = curr + init;
  6715. // }
  6716. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  6717. // /* High water mark at or above current data, but below current data
  6718. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  6719. // * to end of window, whichever is less.
  6720. // */
  6721. // init = (ulg)curr + WIN_INIT - s->high_water;
  6722. // if (init > s->window_size - s->high_water)
  6723. // init = s->window_size - s->high_water;
  6724. // zmemzero(s->window + s->high_water, (unsigned)init);
  6725. // s->high_water += init;
  6726. // }
  6727. // }
  6728. //
  6729. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  6730. // "not enough room for search");
  6731. }
  6732. /* ===========================================================================
  6733. * Copy without compression as much as possible from the input stream, return
  6734. * the current block state.
  6735. * This function does not insert new strings in the dictionary since
  6736. * uncompressible data is probably not useful. This function is used
  6737. * only for the level=0 compression option.
  6738. * NOTE: this function should be optimized to avoid extra copying from
  6739. * window to pending_buf.
  6740. */
  6741. function deflate_stored(s, flush) {
  6742. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  6743. * to pending_buf_size, and each stored block has a 5 byte header:
  6744. */
  6745. var max_block_size = 0xffff;
  6746. if (max_block_size > s.pending_buf_size - 5) {
  6747. max_block_size = s.pending_buf_size - 5;
  6748. }
  6749. /* Copy as much as possible from input to output: */
  6750. for (;;) {
  6751. /* Fill the window as much as possible: */
  6752. if (s.lookahead <= 1) {
  6753. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  6754. // s->block_start >= (long)s->w_size, "slide too late");
  6755. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  6756. // s.block_start >= s.w_size)) {
  6757. // throw new Error("slide too late");
  6758. // }
  6759. fill_window(s);
  6760. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  6761. return BS_NEED_MORE;
  6762. }
  6763. if (s.lookahead === 0) {
  6764. break;
  6765. }
  6766. /* flush the current block */
  6767. }
  6768. //Assert(s->block_start >= 0L, "block gone");
  6769. // if (s.block_start < 0) throw new Error("block gone");
  6770. s.strstart += s.lookahead;
  6771. s.lookahead = 0;
  6772. /* Emit a stored block if pending_buf will be full: */
  6773. var max_start = s.block_start + max_block_size;
  6774. if (s.strstart === 0 || s.strstart >= max_start) {
  6775. /* strstart == 0 is possible when wraparound on 16-bit machine */
  6776. s.lookahead = s.strstart - max_start;
  6777. s.strstart = max_start;
  6778. /*** FLUSH_BLOCK(s, 0); ***/
  6779. flush_block_only(s, false);
  6780. if (s.strm.avail_out === 0) {
  6781. return BS_NEED_MORE;
  6782. }
  6783. /***/
  6784. }
  6785. /* Flush if we may have to slide, otherwise block_start may become
  6786. * negative and the data will be gone:
  6787. */
  6788. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  6789. /*** FLUSH_BLOCK(s, 0); ***/
  6790. flush_block_only(s, false);
  6791. if (s.strm.avail_out === 0) {
  6792. return BS_NEED_MORE;
  6793. }
  6794. /***/
  6795. }
  6796. }
  6797. s.insert = 0;
  6798. if (flush === Z_FINISH) {
  6799. /*** FLUSH_BLOCK(s, 1); ***/
  6800. flush_block_only(s, true);
  6801. if (s.strm.avail_out === 0) {
  6802. return BS_FINISH_STARTED;
  6803. }
  6804. /***/
  6805. return BS_FINISH_DONE;
  6806. }
  6807. if (s.strstart > s.block_start) {
  6808. /*** FLUSH_BLOCK(s, 0); ***/
  6809. flush_block_only(s, false);
  6810. if (s.strm.avail_out === 0) {
  6811. return BS_NEED_MORE;
  6812. }
  6813. /***/
  6814. }
  6815. return BS_NEED_MORE;
  6816. }
  6817. /* ===========================================================================
  6818. * Compress as much as possible from the input stream, return the current
  6819. * block state.
  6820. * This function does not perform lazy evaluation of matches and inserts
  6821. * new strings in the dictionary only for unmatched strings or for short
  6822. * matches. It is used only for the fast compression options.
  6823. */
  6824. function deflate_fast(s, flush) {
  6825. var hash_head; /* head of the hash chain */
  6826. var bflush; /* set if current block must be flushed */
  6827. for (;;) {
  6828. /* Make sure that we always have enough lookahead, except
  6829. * at the end of the input file. We need MAX_MATCH bytes
  6830. * for the next match, plus MIN_MATCH bytes to insert the
  6831. * string following the next match.
  6832. */
  6833. if (s.lookahead < MIN_LOOKAHEAD) {
  6834. fill_window(s);
  6835. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  6836. return BS_NEED_MORE;
  6837. }
  6838. if (s.lookahead === 0) {
  6839. break; /* flush the current block */
  6840. }
  6841. }
  6842. /* Insert the string window[strstart .. strstart+2] in the
  6843. * dictionary, and set hash_head to the head of the hash chain:
  6844. */
  6845. hash_head = 0/*NIL*/;
  6846. if (s.lookahead >= MIN_MATCH) {
  6847. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6848. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6849. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6850. s.head[s.ins_h] = s.strstart;
  6851. /***/
  6852. }
  6853. /* Find the longest match, discarding those <= prev_length.
  6854. * At this point we have always match_length < MIN_MATCH
  6855. */
  6856. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  6857. /* To simplify the code, we prevent matches with the string
  6858. * of window index 0 (in particular we have to avoid a match
  6859. * of the string with itself at the start of the input file).
  6860. */
  6861. s.match_length = longest_match(s, hash_head);
  6862. /* longest_match() sets match_start */
  6863. }
  6864. if (s.match_length >= MIN_MATCH) {
  6865. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  6866. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  6867. s.match_length - MIN_MATCH, bflush); ***/
  6868. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  6869. s.lookahead -= s.match_length;
  6870. /* Insert new strings in the hash table only if the match length
  6871. * is not too large. This saves time but degrades compression.
  6872. */
  6873. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  6874. s.match_length--; /* string at strstart already in table */
  6875. do {
  6876. s.strstart++;
  6877. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6878. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6879. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6880. s.head[s.ins_h] = s.strstart;
  6881. /***/
  6882. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  6883. * always MIN_MATCH bytes ahead.
  6884. */
  6885. } while (--s.match_length !== 0);
  6886. s.strstart++;
  6887. } else
  6888. {
  6889. s.strstart += s.match_length;
  6890. s.match_length = 0;
  6891. s.ins_h = s.window[s.strstart];
  6892. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  6893. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  6894. //#if MIN_MATCH != 3
  6895. // Call UPDATE_HASH() MIN_MATCH-3 more times
  6896. //#endif
  6897. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  6898. * matter since it will be recomputed at next deflate call.
  6899. */
  6900. }
  6901. } else {
  6902. /* No match, output a literal byte */
  6903. //Tracevv((stderr,"%c", s.window[s.strstart]));
  6904. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  6905. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  6906. s.lookahead--;
  6907. s.strstart++;
  6908. }
  6909. if (bflush) {
  6910. /*** FLUSH_BLOCK(s, 0); ***/
  6911. flush_block_only(s, false);
  6912. if (s.strm.avail_out === 0) {
  6913. return BS_NEED_MORE;
  6914. }
  6915. /***/
  6916. }
  6917. }
  6918. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  6919. if (flush === Z_FINISH) {
  6920. /*** FLUSH_BLOCK(s, 1); ***/
  6921. flush_block_only(s, true);
  6922. if (s.strm.avail_out === 0) {
  6923. return BS_FINISH_STARTED;
  6924. }
  6925. /***/
  6926. return BS_FINISH_DONE;
  6927. }
  6928. if (s.last_lit) {
  6929. /*** FLUSH_BLOCK(s, 0); ***/
  6930. flush_block_only(s, false);
  6931. if (s.strm.avail_out === 0) {
  6932. return BS_NEED_MORE;
  6933. }
  6934. /***/
  6935. }
  6936. return BS_BLOCK_DONE;
  6937. }
  6938. /* ===========================================================================
  6939. * Same as above, but achieves better compression. We use a lazy
  6940. * evaluation for matches: a match is finally adopted only if there is
  6941. * no better match at the next window position.
  6942. */
  6943. function deflate_slow(s, flush) {
  6944. var hash_head; /* head of hash chain */
  6945. var bflush; /* set if current block must be flushed */
  6946. var max_insert;
  6947. /* Process the input block. */
  6948. for (;;) {
  6949. /* Make sure that we always have enough lookahead, except
  6950. * at the end of the input file. We need MAX_MATCH bytes
  6951. * for the next match, plus MIN_MATCH bytes to insert the
  6952. * string following the next match.
  6953. */
  6954. if (s.lookahead < MIN_LOOKAHEAD) {
  6955. fill_window(s);
  6956. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  6957. return BS_NEED_MORE;
  6958. }
  6959. if (s.lookahead === 0) { break; } /* flush the current block */
  6960. }
  6961. /* Insert the string window[strstart .. strstart+2] in the
  6962. * dictionary, and set hash_head to the head of the hash chain:
  6963. */
  6964. hash_head = 0/*NIL*/;
  6965. if (s.lookahead >= MIN_MATCH) {
  6966. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6967. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6968. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6969. s.head[s.ins_h] = s.strstart;
  6970. /***/
  6971. }
  6972. /* Find the longest match, discarding those <= prev_length.
  6973. */
  6974. s.prev_length = s.match_length;
  6975. s.prev_match = s.match_start;
  6976. s.match_length = MIN_MATCH-1;
  6977. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  6978. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  6979. /* To simplify the code, we prevent matches with the string
  6980. * of window index 0 (in particular we have to avoid a match
  6981. * of the string with itself at the start of the input file).
  6982. */
  6983. s.match_length = longest_match(s, hash_head);
  6984. /* longest_match() sets match_start */
  6985. if (s.match_length <= 5 &&
  6986. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  6987. /* If prev_match is also MIN_MATCH, match_start is garbage
  6988. * but we will ignore the current match anyway.
  6989. */
  6990. s.match_length = MIN_MATCH-1;
  6991. }
  6992. }
  6993. /* If there was a match at the previous step and the current
  6994. * match is not better, output the previous match:
  6995. */
  6996. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  6997. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  6998. /* Do not insert strings in hash table beyond this. */
  6999. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  7000. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  7001. s.prev_length - MIN_MATCH, bflush);***/
  7002. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  7003. /* Insert in hash table all strings up to the end of the match.
  7004. * strstart-1 and strstart are already inserted. If there is not
  7005. * enough lookahead, the last two strings are not inserted in
  7006. * the hash table.
  7007. */
  7008. s.lookahead -= s.prev_length-1;
  7009. s.prev_length -= 2;
  7010. do {
  7011. if (++s.strstart <= max_insert) {
  7012. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  7013. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  7014. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  7015. s.head[s.ins_h] = s.strstart;
  7016. /***/
  7017. }
  7018. } while (--s.prev_length !== 0);
  7019. s.match_available = 0;
  7020. s.match_length = MIN_MATCH-1;
  7021. s.strstart++;
  7022. if (bflush) {
  7023. /*** FLUSH_BLOCK(s, 0); ***/
  7024. flush_block_only(s, false);
  7025. if (s.strm.avail_out === 0) {
  7026. return BS_NEED_MORE;
  7027. }
  7028. /***/
  7029. }
  7030. } else if (s.match_available) {
  7031. /* If there was no match at the previous position, output a
  7032. * single literal. If there was a match but the current match
  7033. * is longer, truncate the previous match to a single literal.
  7034. */
  7035. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  7036. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  7037. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  7038. if (bflush) {
  7039. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  7040. flush_block_only(s, false);
  7041. /***/
  7042. }
  7043. s.strstart++;
  7044. s.lookahead--;
  7045. if (s.strm.avail_out === 0) {
  7046. return BS_NEED_MORE;
  7047. }
  7048. } else {
  7049. /* There is no previous match to compare with, wait for
  7050. * the next step to decide.
  7051. */
  7052. s.match_available = 1;
  7053. s.strstart++;
  7054. s.lookahead--;
  7055. }
  7056. }
  7057. //Assert (flush != Z_NO_FLUSH, "no flush?");
  7058. if (s.match_available) {
  7059. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  7060. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  7061. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  7062. s.match_available = 0;
  7063. }
  7064. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  7065. if (flush === Z_FINISH) {
  7066. /*** FLUSH_BLOCK(s, 1); ***/
  7067. flush_block_only(s, true);
  7068. if (s.strm.avail_out === 0) {
  7069. return BS_FINISH_STARTED;
  7070. }
  7071. /***/
  7072. return BS_FINISH_DONE;
  7073. }
  7074. if (s.last_lit) {
  7075. /*** FLUSH_BLOCK(s, 0); ***/
  7076. flush_block_only(s, false);
  7077. if (s.strm.avail_out === 0) {
  7078. return BS_NEED_MORE;
  7079. }
  7080. /***/
  7081. }
  7082. return BS_BLOCK_DONE;
  7083. }
  7084. /* ===========================================================================
  7085. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  7086. * one. Do not maintain a hash table. (It will be regenerated if this run of
  7087. * deflate switches away from Z_RLE.)
  7088. */
  7089. function deflate_rle(s, flush) {
  7090. var bflush; /* set if current block must be flushed */
  7091. var prev; /* byte at distance one to match */
  7092. var scan, strend; /* scan goes up to strend for length of run */
  7093. var _win = s.window;
  7094. for (;;) {
  7095. /* Make sure that we always have enough lookahead, except
  7096. * at the end of the input file. We need MAX_MATCH bytes
  7097. * for the longest run, plus one for the unrolled loop.
  7098. */
  7099. if (s.lookahead <= MAX_MATCH) {
  7100. fill_window(s);
  7101. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  7102. return BS_NEED_MORE;
  7103. }
  7104. if (s.lookahead === 0) { break; } /* flush the current block */
  7105. }
  7106. /* See how many times the previous byte repeats */
  7107. s.match_length = 0;
  7108. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  7109. scan = s.strstart - 1;
  7110. prev = _win[scan];
  7111. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  7112. strend = s.strstart + MAX_MATCH;
  7113. do {
  7114. /*jshint noempty:false*/
  7115. } while (prev === _win[++scan] && prev === _win[++scan] &&
  7116. prev === _win[++scan] && prev === _win[++scan] &&
  7117. prev === _win[++scan] && prev === _win[++scan] &&
  7118. prev === _win[++scan] && prev === _win[++scan] &&
  7119. scan < strend);
  7120. s.match_length = MAX_MATCH - (strend - scan);
  7121. if (s.match_length > s.lookahead) {
  7122. s.match_length = s.lookahead;
  7123. }
  7124. }
  7125. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  7126. }
  7127. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  7128. if (s.match_length >= MIN_MATCH) {
  7129. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  7130. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  7131. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  7132. s.lookahead -= s.match_length;
  7133. s.strstart += s.match_length;
  7134. s.match_length = 0;
  7135. } else {
  7136. /* No match, output a literal byte */
  7137. //Tracevv((stderr,"%c", s->window[s->strstart]));
  7138. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  7139. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  7140. s.lookahead--;
  7141. s.strstart++;
  7142. }
  7143. if (bflush) {
  7144. /*** FLUSH_BLOCK(s, 0); ***/
  7145. flush_block_only(s, false);
  7146. if (s.strm.avail_out === 0) {
  7147. return BS_NEED_MORE;
  7148. }
  7149. /***/
  7150. }
  7151. }
  7152. s.insert = 0;
  7153. if (flush === Z_FINISH) {
  7154. /*** FLUSH_BLOCK(s, 1); ***/
  7155. flush_block_only(s, true);
  7156. if (s.strm.avail_out === 0) {
  7157. return BS_FINISH_STARTED;
  7158. }
  7159. /***/
  7160. return BS_FINISH_DONE;
  7161. }
  7162. if (s.last_lit) {
  7163. /*** FLUSH_BLOCK(s, 0); ***/
  7164. flush_block_only(s, false);
  7165. if (s.strm.avail_out === 0) {
  7166. return BS_NEED_MORE;
  7167. }
  7168. /***/
  7169. }
  7170. return BS_BLOCK_DONE;
  7171. }
  7172. /* ===========================================================================
  7173. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  7174. * (It will be regenerated if this run of deflate switches away from Huffman.)
  7175. */
  7176. function deflate_huff(s, flush) {
  7177. var bflush; /* set if current block must be flushed */
  7178. for (;;) {
  7179. /* Make sure that we have a literal to write. */
  7180. if (s.lookahead === 0) {
  7181. fill_window(s);
  7182. if (s.lookahead === 0) {
  7183. if (flush === Z_NO_FLUSH) {
  7184. return BS_NEED_MORE;
  7185. }
  7186. break; /* flush the current block */
  7187. }
  7188. }
  7189. /* Output a literal byte */
  7190. s.match_length = 0;
  7191. //Tracevv((stderr,"%c", s->window[s->strstart]));
  7192. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  7193. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  7194. s.lookahead--;
  7195. s.strstart++;
  7196. if (bflush) {
  7197. /*** FLUSH_BLOCK(s, 0); ***/
  7198. flush_block_only(s, false);
  7199. if (s.strm.avail_out === 0) {
  7200. return BS_NEED_MORE;
  7201. }
  7202. /***/
  7203. }
  7204. }
  7205. s.insert = 0;
  7206. if (flush === Z_FINISH) {
  7207. /*** FLUSH_BLOCK(s, 1); ***/
  7208. flush_block_only(s, true);
  7209. if (s.strm.avail_out === 0) {
  7210. return BS_FINISH_STARTED;
  7211. }
  7212. /***/
  7213. return BS_FINISH_DONE;
  7214. }
  7215. if (s.last_lit) {
  7216. /*** FLUSH_BLOCK(s, 0); ***/
  7217. flush_block_only(s, false);
  7218. if (s.strm.avail_out === 0) {
  7219. return BS_NEED_MORE;
  7220. }
  7221. /***/
  7222. }
  7223. return BS_BLOCK_DONE;
  7224. }
  7225. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  7226. * the desired pack level (0..9). The values given below have been tuned to
  7227. * exclude worst case performance for pathological files. Better values may be
  7228. * found for specific files.
  7229. */
  7230. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  7231. this.good_length = good_length;
  7232. this.max_lazy = max_lazy;
  7233. this.nice_length = nice_length;
  7234. this.max_chain = max_chain;
  7235. this.func = func;
  7236. };
  7237. var configuration_table;
  7238. configuration_table = [
  7239. /* good lazy nice chain */
  7240. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  7241. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  7242. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  7243. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  7244. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  7245. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  7246. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  7247. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  7248. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  7249. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  7250. ];
  7251. /* ===========================================================================
  7252. * Initialize the "longest match" routines for a new zlib stream
  7253. */
  7254. function lm_init(s) {
  7255. s.window_size = 2 * s.w_size;
  7256. /*** CLEAR_HASH(s); ***/
  7257. zero(s.head); // Fill with NIL (= 0);
  7258. /* Set the default configuration parameters:
  7259. */
  7260. s.max_lazy_match = configuration_table[s.level].max_lazy;
  7261. s.good_match = configuration_table[s.level].good_length;
  7262. s.nice_match = configuration_table[s.level].nice_length;
  7263. s.max_chain_length = configuration_table[s.level].max_chain;
  7264. s.strstart = 0;
  7265. s.block_start = 0;
  7266. s.lookahead = 0;
  7267. s.insert = 0;
  7268. s.match_length = s.prev_length = MIN_MATCH - 1;
  7269. s.match_available = 0;
  7270. s.ins_h = 0;
  7271. }
  7272. function DeflateState() {
  7273. this.strm = null; /* pointer back to this zlib stream */
  7274. this.status = 0; /* as the name implies */
  7275. this.pending_buf = null; /* output still pending */
  7276. this.pending_buf_size = 0; /* size of pending_buf */
  7277. this.pending_out = 0; /* next pending byte to output to the stream */
  7278. this.pending = 0; /* nb of bytes in the pending buffer */
  7279. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  7280. this.gzhead = null; /* gzip header information to write */
  7281. this.gzindex = 0; /* where in extra, name, or comment */
  7282. this.method = Z_DEFLATED; /* can only be DEFLATED */
  7283. this.last_flush = -1; /* value of flush param for previous deflate call */
  7284. this.w_size = 0; /* LZ77 window size (32K by default) */
  7285. this.w_bits = 0; /* log2(w_size) (8..16) */
  7286. this.w_mask = 0; /* w_size - 1 */
  7287. this.window = null;
  7288. /* Sliding window. Input bytes are read into the second half of the window,
  7289. * and move to the first half later to keep a dictionary of at least wSize
  7290. * bytes. With this organization, matches are limited to a distance of
  7291. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  7292. * performed with a length multiple of the block size.
  7293. */
  7294. this.window_size = 0;
  7295. /* Actual size of window: 2*wSize, except when the user input buffer
  7296. * is directly used as sliding window.
  7297. */
  7298. this.prev = null;
  7299. /* Link to older string with same hash index. To limit the size of this
  7300. * array to 64K, this link is maintained only for the last 32K strings.
  7301. * An index in this array is thus a window index modulo 32K.
  7302. */
  7303. this.head = null; /* Heads of the hash chains or NIL. */
  7304. this.ins_h = 0; /* hash index of string to be inserted */
  7305. this.hash_size = 0; /* number of elements in hash table */
  7306. this.hash_bits = 0; /* log2(hash_size) */
  7307. this.hash_mask = 0; /* hash_size-1 */
  7308. this.hash_shift = 0;
  7309. /* Number of bits by which ins_h must be shifted at each input
  7310. * step. It must be such that after MIN_MATCH steps, the oldest
  7311. * byte no longer takes part in the hash key, that is:
  7312. * hash_shift * MIN_MATCH >= hash_bits
  7313. */
  7314. this.block_start = 0;
  7315. /* Window position at the beginning of the current output block. Gets
  7316. * negative when the window is moved backwards.
  7317. */
  7318. this.match_length = 0; /* length of best match */
  7319. this.prev_match = 0; /* previous match */
  7320. this.match_available = 0; /* set if previous match exists */
  7321. this.strstart = 0; /* start of string to insert */
  7322. this.match_start = 0; /* start of matching string */
  7323. this.lookahead = 0; /* number of valid bytes ahead in window */
  7324. this.prev_length = 0;
  7325. /* Length of the best match at previous step. Matches not greater than this
  7326. * are discarded. This is used in the lazy match evaluation.
  7327. */
  7328. this.max_chain_length = 0;
  7329. /* To speed up deflation, hash chains are never searched beyond this
  7330. * length. A higher limit improves compression ratio but degrades the
  7331. * speed.
  7332. */
  7333. this.max_lazy_match = 0;
  7334. /* Attempt to find a better match only when the current match is strictly
  7335. * smaller than this value. This mechanism is used only for compression
  7336. * levels >= 4.
  7337. */
  7338. // That's alias to max_lazy_match, don't use directly
  7339. //this.max_insert_length = 0;
  7340. /* Insert new strings in the hash table only if the match length is not
  7341. * greater than this length. This saves time but degrades compression.
  7342. * max_insert_length is used only for compression levels <= 3.
  7343. */
  7344. this.level = 0; /* compression level (1..9) */
  7345. this.strategy = 0; /* favor or force Huffman coding*/
  7346. this.good_match = 0;
  7347. /* Use a faster search when the previous match is longer than this */
  7348. this.nice_match = 0; /* Stop searching when current match exceeds this */
  7349. /* used by trees.c: */
  7350. /* Didn't use ct_data typedef below to suppress compiler warning */
  7351. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  7352. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  7353. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  7354. // Use flat array of DOUBLE size, with interleaved fata,
  7355. // because JS does not support effective
  7356. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  7357. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  7358. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  7359. zero(this.dyn_ltree);
  7360. zero(this.dyn_dtree);
  7361. zero(this.bl_tree);
  7362. this.l_desc = null; /* desc. for literal tree */
  7363. this.d_desc = null; /* desc. for distance tree */
  7364. this.bl_desc = null; /* desc. for bit length tree */
  7365. //ush bl_count[MAX_BITS+1];
  7366. this.bl_count = new utils.Buf16(MAX_BITS+1);
  7367. /* number of codes at each bit length for an optimal tree */
  7368. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  7369. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  7370. zero(this.heap);
  7371. this.heap_len = 0; /* number of elements in the heap */
  7372. this.heap_max = 0; /* element of largest frequency */
  7373. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  7374. * The same heap array is used to build all trees.
  7375. */
  7376. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  7377. zero(this.depth);
  7378. /* Depth of each subtree used as tie breaker for trees of equal frequency
  7379. */
  7380. this.l_buf = 0; /* buffer index for literals or lengths */
  7381. this.lit_bufsize = 0;
  7382. /* Size of match buffer for literals/lengths. There are 4 reasons for
  7383. * limiting lit_bufsize to 64K:
  7384. * - frequencies can be kept in 16 bit counters
  7385. * - if compression is not successful for the first block, all input
  7386. * data is still in the window so we can still emit a stored block even
  7387. * when input comes from standard input. (This can also be done for
  7388. * all blocks if lit_bufsize is not greater than 32K.)
  7389. * - if compression is not successful for a file smaller than 64K, we can
  7390. * even emit a stored file instead of a stored block (saving 5 bytes).
  7391. * This is applicable only for zip (not gzip or zlib).
  7392. * - creating new Huffman trees less frequently may not provide fast
  7393. * adaptation to changes in the input data statistics. (Take for
  7394. * example a binary file with poorly compressible code followed by
  7395. * a highly compressible string table.) Smaller buffer sizes give
  7396. * fast adaptation but have of course the overhead of transmitting
  7397. * trees more frequently.
  7398. * - I can't count above 4
  7399. */
  7400. this.last_lit = 0; /* running index in l_buf */
  7401. this.d_buf = 0;
  7402. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  7403. * the same number of elements. To use different lengths, an extra flag
  7404. * array would be necessary.
  7405. */
  7406. this.opt_len = 0; /* bit length of current block with optimal trees */
  7407. this.static_len = 0; /* bit length of current block with static trees */
  7408. this.matches = 0; /* number of string matches in current block */
  7409. this.insert = 0; /* bytes at end of window left to insert */
  7410. this.bi_buf = 0;
  7411. /* Output buffer. bits are inserted starting at the bottom (least
  7412. * significant bits).
  7413. */
  7414. this.bi_valid = 0;
  7415. /* Number of valid bits in bi_buf. All bits above the last valid bit
  7416. * are always zero.
  7417. */
  7418. // Used for window memory init. We safely ignore it for JS. That makes
  7419. // sense only for pointers and memory check tools.
  7420. //this.high_water = 0;
  7421. /* High water mark offset in window for initialized bytes -- bytes above
  7422. * this are set to zero in order to avoid memory check warnings when
  7423. * longest match routines access bytes past the input. This is then
  7424. * updated to the new high water mark.
  7425. */
  7426. }
  7427. function deflateResetKeep(strm) {
  7428. var s;
  7429. if (!strm || !strm.state) {
  7430. return err(strm, Z_STREAM_ERROR);
  7431. }
  7432. strm.total_in = strm.total_out = 0;
  7433. strm.data_type = Z_UNKNOWN;
  7434. s = strm.state;
  7435. s.pending = 0;
  7436. s.pending_out = 0;
  7437. if (s.wrap < 0) {
  7438. s.wrap = -s.wrap;
  7439. /* was made negative by deflate(..., Z_FINISH); */
  7440. }
  7441. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  7442. strm.adler = (s.wrap === 2) ?
  7443. 0 // crc32(0, Z_NULL, 0)
  7444. :
  7445. 1; // adler32(0, Z_NULL, 0)
  7446. s.last_flush = Z_NO_FLUSH;
  7447. trees._tr_init(s);
  7448. return Z_OK;
  7449. }
  7450. function deflateReset(strm) {
  7451. var ret = deflateResetKeep(strm);
  7452. if (ret === Z_OK) {
  7453. lm_init(strm.state);
  7454. }
  7455. return ret;
  7456. }
  7457. function deflateSetHeader(strm, head) {
  7458. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  7459. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  7460. strm.state.gzhead = head;
  7461. return Z_OK;
  7462. }
  7463. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  7464. if (!strm) { // === Z_NULL
  7465. return Z_STREAM_ERROR;
  7466. }
  7467. var wrap = 1;
  7468. if (level === Z_DEFAULT_COMPRESSION) {
  7469. level = 6;
  7470. }
  7471. if (windowBits < 0) { /* suppress zlib wrapper */
  7472. wrap = 0;
  7473. windowBits = -windowBits;
  7474. }
  7475. else if (windowBits > 15) {
  7476. wrap = 2; /* write gzip wrapper instead */
  7477. windowBits -= 16;
  7478. }
  7479. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  7480. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  7481. strategy < 0 || strategy > Z_FIXED) {
  7482. return err(strm, Z_STREAM_ERROR);
  7483. }
  7484. if (windowBits === 8) {
  7485. windowBits = 9;
  7486. }
  7487. /* until 256-byte window bug fixed */
  7488. var s = new DeflateState();
  7489. strm.state = s;
  7490. s.strm = strm;
  7491. s.wrap = wrap;
  7492. s.gzhead = null;
  7493. s.w_bits = windowBits;
  7494. s.w_size = 1 << s.w_bits;
  7495. s.w_mask = s.w_size - 1;
  7496. s.hash_bits = memLevel + 7;
  7497. s.hash_size = 1 << s.hash_bits;
  7498. s.hash_mask = s.hash_size - 1;
  7499. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  7500. s.window = new utils.Buf8(s.w_size * 2);
  7501. s.head = new utils.Buf16(s.hash_size);
  7502. s.prev = new utils.Buf16(s.w_size);
  7503. // Don't need mem init magic for JS.
  7504. //s.high_water = 0; /* nothing written to s->window yet */
  7505. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  7506. s.pending_buf_size = s.lit_bufsize * 4;
  7507. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  7508. s.d_buf = s.lit_bufsize >> 1;
  7509. s.l_buf = (1 + 2) * s.lit_bufsize;
  7510. s.level = level;
  7511. s.strategy = strategy;
  7512. s.method = method;
  7513. return deflateReset(strm);
  7514. }
  7515. function deflateInit(strm, level) {
  7516. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  7517. }
  7518. function deflate(strm, flush) {
  7519. var old_flush, s;
  7520. var beg, val; // for gzip header write only
  7521. if (!strm || !strm.state ||
  7522. flush > Z_BLOCK || flush < 0) {
  7523. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  7524. }
  7525. s = strm.state;
  7526. if (!strm.output ||
  7527. (!strm.input && strm.avail_in !== 0) ||
  7528. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  7529. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  7530. }
  7531. s.strm = strm; /* just in case */
  7532. old_flush = s.last_flush;
  7533. s.last_flush = flush;
  7534. /* Write the header */
  7535. if (s.status === INIT_STATE) {
  7536. if (s.wrap === 2) { // GZIP header
  7537. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  7538. put_byte(s, 31);
  7539. put_byte(s, 139);
  7540. put_byte(s, 8);
  7541. if (!s.gzhead) { // s->gzhead == Z_NULL
  7542. put_byte(s, 0);
  7543. put_byte(s, 0);
  7544. put_byte(s, 0);
  7545. put_byte(s, 0);
  7546. put_byte(s, 0);
  7547. put_byte(s, s.level === 9 ? 2 :
  7548. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  7549. 4 : 0));
  7550. put_byte(s, OS_CODE);
  7551. s.status = BUSY_STATE;
  7552. }
  7553. else {
  7554. put_byte(s, (s.gzhead.text ? 1 : 0) +
  7555. (s.gzhead.hcrc ? 2 : 0) +
  7556. (!s.gzhead.extra ? 0 : 4) +
  7557. (!s.gzhead.name ? 0 : 8) +
  7558. (!s.gzhead.comment ? 0 : 16)
  7559. );
  7560. put_byte(s, s.gzhead.time & 0xff);
  7561. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  7562. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  7563. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  7564. put_byte(s, s.level === 9 ? 2 :
  7565. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  7566. 4 : 0));
  7567. put_byte(s, s.gzhead.os & 0xff);
  7568. if (s.gzhead.extra && s.gzhead.extra.length) {
  7569. put_byte(s, s.gzhead.extra.length & 0xff);
  7570. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  7571. }
  7572. if (s.gzhead.hcrc) {
  7573. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  7574. }
  7575. s.gzindex = 0;
  7576. s.status = EXTRA_STATE;
  7577. }
  7578. }
  7579. else // DEFLATE header
  7580. {
  7581. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  7582. var level_flags = -1;
  7583. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  7584. level_flags = 0;
  7585. } else if (s.level < 6) {
  7586. level_flags = 1;
  7587. } else if (s.level === 6) {
  7588. level_flags = 2;
  7589. } else {
  7590. level_flags = 3;
  7591. }
  7592. header |= (level_flags << 6);
  7593. if (s.strstart !== 0) { header |= PRESET_DICT; }
  7594. header += 31 - (header % 31);
  7595. s.status = BUSY_STATE;
  7596. putShortMSB(s, header);
  7597. /* Save the adler32 of the preset dictionary: */
  7598. if (s.strstart !== 0) {
  7599. putShortMSB(s, strm.adler >>> 16);
  7600. putShortMSB(s, strm.adler & 0xffff);
  7601. }
  7602. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  7603. }
  7604. }
  7605. //#ifdef GZIP
  7606. if (s.status === EXTRA_STATE) {
  7607. if (s.gzhead.extra/* != Z_NULL*/) {
  7608. beg = s.pending; /* start of bytes to update crc */
  7609. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  7610. if (s.pending === s.pending_buf_size) {
  7611. if (s.gzhead.hcrc && s.pending > beg) {
  7612. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7613. }
  7614. flush_pending(strm);
  7615. beg = s.pending;
  7616. if (s.pending === s.pending_buf_size) {
  7617. break;
  7618. }
  7619. }
  7620. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  7621. s.gzindex++;
  7622. }
  7623. if (s.gzhead.hcrc && s.pending > beg) {
  7624. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7625. }
  7626. if (s.gzindex === s.gzhead.extra.length) {
  7627. s.gzindex = 0;
  7628. s.status = NAME_STATE;
  7629. }
  7630. }
  7631. else {
  7632. s.status = NAME_STATE;
  7633. }
  7634. }
  7635. if (s.status === NAME_STATE) {
  7636. if (s.gzhead.name/* != Z_NULL*/) {
  7637. beg = s.pending; /* start of bytes to update crc */
  7638. //int val;
  7639. do {
  7640. if (s.pending === s.pending_buf_size) {
  7641. if (s.gzhead.hcrc && s.pending > beg) {
  7642. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7643. }
  7644. flush_pending(strm);
  7645. beg = s.pending;
  7646. if (s.pending === s.pending_buf_size) {
  7647. val = 1;
  7648. break;
  7649. }
  7650. }
  7651. // JS specific: little magic to add zero terminator to end of string
  7652. if (s.gzindex < s.gzhead.name.length) {
  7653. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  7654. } else {
  7655. val = 0;
  7656. }
  7657. put_byte(s, val);
  7658. } while (val !== 0);
  7659. if (s.gzhead.hcrc && s.pending > beg) {
  7660. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7661. }
  7662. if (val === 0) {
  7663. s.gzindex = 0;
  7664. s.status = COMMENT_STATE;
  7665. }
  7666. }
  7667. else {
  7668. s.status = COMMENT_STATE;
  7669. }
  7670. }
  7671. if (s.status === COMMENT_STATE) {
  7672. if (s.gzhead.comment/* != Z_NULL*/) {
  7673. beg = s.pending; /* start of bytes to update crc */
  7674. //int val;
  7675. do {
  7676. if (s.pending === s.pending_buf_size) {
  7677. if (s.gzhead.hcrc && s.pending > beg) {
  7678. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7679. }
  7680. flush_pending(strm);
  7681. beg = s.pending;
  7682. if (s.pending === s.pending_buf_size) {
  7683. val = 1;
  7684. break;
  7685. }
  7686. }
  7687. // JS specific: little magic to add zero terminator to end of string
  7688. if (s.gzindex < s.gzhead.comment.length) {
  7689. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  7690. } else {
  7691. val = 0;
  7692. }
  7693. put_byte(s, val);
  7694. } while (val !== 0);
  7695. if (s.gzhead.hcrc && s.pending > beg) {
  7696. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7697. }
  7698. if (val === 0) {
  7699. s.status = HCRC_STATE;
  7700. }
  7701. }
  7702. else {
  7703. s.status = HCRC_STATE;
  7704. }
  7705. }
  7706. if (s.status === HCRC_STATE) {
  7707. if (s.gzhead.hcrc) {
  7708. if (s.pending + 2 > s.pending_buf_size) {
  7709. flush_pending(strm);
  7710. }
  7711. if (s.pending + 2 <= s.pending_buf_size) {
  7712. put_byte(s, strm.adler & 0xff);
  7713. put_byte(s, (strm.adler >> 8) & 0xff);
  7714. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  7715. s.status = BUSY_STATE;
  7716. }
  7717. }
  7718. else {
  7719. s.status = BUSY_STATE;
  7720. }
  7721. }
  7722. //#endif
  7723. /* Flush as much pending output as possible */
  7724. if (s.pending !== 0) {
  7725. flush_pending(strm);
  7726. if (strm.avail_out === 0) {
  7727. /* Since avail_out is 0, deflate will be called again with
  7728. * more output space, but possibly with both pending and
  7729. * avail_in equal to zero. There won't be anything to do,
  7730. * but this is not an error situation so make sure we
  7731. * return OK instead of BUF_ERROR at next call of deflate:
  7732. */
  7733. s.last_flush = -1;
  7734. return Z_OK;
  7735. }
  7736. /* Make sure there is something to do and avoid duplicate consecutive
  7737. * flushes. For repeated and useless calls with Z_FINISH, we keep
  7738. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  7739. */
  7740. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  7741. flush !== Z_FINISH) {
  7742. return err(strm, Z_BUF_ERROR);
  7743. }
  7744. /* User must not provide more input after the first FINISH: */
  7745. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  7746. return err(strm, Z_BUF_ERROR);
  7747. }
  7748. /* Start a new block or continue the current one.
  7749. */
  7750. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  7751. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  7752. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  7753. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  7754. configuration_table[s.level].func(s, flush));
  7755. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  7756. s.status = FINISH_STATE;
  7757. }
  7758. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  7759. if (strm.avail_out === 0) {
  7760. s.last_flush = -1;
  7761. /* avoid BUF_ERROR next call, see above */
  7762. }
  7763. return Z_OK;
  7764. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  7765. * of deflate should use the same flush parameter to make sure
  7766. * that the flush is complete. So we don't have to output an
  7767. * empty block here, this will be done at next call. This also
  7768. * ensures that for a very small output buffer, we emit at most
  7769. * one empty block.
  7770. */
  7771. }
  7772. if (bstate === BS_BLOCK_DONE) {
  7773. if (flush === Z_PARTIAL_FLUSH) {
  7774. trees._tr_align(s);
  7775. }
  7776. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  7777. trees._tr_stored_block(s, 0, 0, false);
  7778. /* For a full flush, this empty block will be recognized
  7779. * as a special marker by inflate_sync().
  7780. */
  7781. if (flush === Z_FULL_FLUSH) {
  7782. /*** CLEAR_HASH(s); ***/ /* forget history */
  7783. zero(s.head); // Fill with NIL (= 0);
  7784. if (s.lookahead === 0) {
  7785. s.strstart = 0;
  7786. s.block_start = 0;
  7787. s.insert = 0;
  7788. }
  7789. }
  7790. }
  7791. flush_pending(strm);
  7792. if (strm.avail_out === 0) {
  7793. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  7794. return Z_OK;
  7795. }
  7796. }
  7797. }
  7798. //Assert(strm->avail_out > 0, "bug2");
  7799. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  7800. if (flush !== Z_FINISH) { return Z_OK; }
  7801. if (s.wrap <= 0) { return Z_STREAM_END; }
  7802. /* Write the trailer */
  7803. if (s.wrap === 2) {
  7804. put_byte(s, strm.adler & 0xff);
  7805. put_byte(s, (strm.adler >> 8) & 0xff);
  7806. put_byte(s, (strm.adler >> 16) & 0xff);
  7807. put_byte(s, (strm.adler >> 24) & 0xff);
  7808. put_byte(s, strm.total_in & 0xff);
  7809. put_byte(s, (strm.total_in >> 8) & 0xff);
  7810. put_byte(s, (strm.total_in >> 16) & 0xff);
  7811. put_byte(s, (strm.total_in >> 24) & 0xff);
  7812. }
  7813. else
  7814. {
  7815. putShortMSB(s, strm.adler >>> 16);
  7816. putShortMSB(s, strm.adler & 0xffff);
  7817. }
  7818. flush_pending(strm);
  7819. /* If avail_out is zero, the application will call deflate again
  7820. * to flush the rest.
  7821. */
  7822. if (s.wrap > 0) { s.wrap = -s.wrap; }
  7823. /* write the trailer only once! */
  7824. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  7825. }
  7826. function deflateEnd(strm) {
  7827. var status;
  7828. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  7829. return Z_STREAM_ERROR;
  7830. }
  7831. status = strm.state.status;
  7832. if (status !== INIT_STATE &&
  7833. status !== EXTRA_STATE &&
  7834. status !== NAME_STATE &&
  7835. status !== COMMENT_STATE &&
  7836. status !== HCRC_STATE &&
  7837. status !== BUSY_STATE &&
  7838. status !== FINISH_STATE
  7839. ) {
  7840. return err(strm, Z_STREAM_ERROR);
  7841. }
  7842. strm.state = null;
  7843. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  7844. }
  7845. /* =========================================================================
  7846. * Copy the source state to the destination state
  7847. */
  7848. //function deflateCopy(dest, source) {
  7849. //
  7850. //}
  7851. exports.deflateInit = deflateInit;
  7852. exports.deflateInit2 = deflateInit2;
  7853. exports.deflateReset = deflateReset;
  7854. exports.deflateResetKeep = deflateResetKeep;
  7855. exports.deflateSetHeader = deflateSetHeader;
  7856. exports.deflate = deflate;
  7857. exports.deflateEnd = deflateEnd;
  7858. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  7859. /* Not implemented
  7860. exports.deflateBound = deflateBound;
  7861. exports.deflateCopy = deflateCopy;
  7862. exports.deflateSetDictionary = deflateSetDictionary;
  7863. exports.deflateParams = deflateParams;
  7864. exports.deflatePending = deflatePending;
  7865. exports.deflatePrime = deflatePrime;
  7866. exports.deflateTune = deflateTune;
  7867. */
  7868. },{"../utils/common":27,"./adler32":29,"./crc32":31,"./messages":37,"./trees":38}],33:[function(require,module,exports){
  7869. 'use strict';
  7870. function GZheader() {
  7871. /* true if compressed data believed to be text */
  7872. this.text = 0;
  7873. /* modification time */
  7874. this.time = 0;
  7875. /* extra flags (not used when writing a gzip file) */
  7876. this.xflags = 0;
  7877. /* operating system */
  7878. this.os = 0;
  7879. /* pointer to extra field or Z_NULL if none */
  7880. this.extra = null;
  7881. /* extra field length (valid if extra != Z_NULL) */
  7882. this.extra_len = 0; // Actually, we don't need it in JS,
  7883. // but leave for few code modifications
  7884. //
  7885. // Setup limits is not necessary because in js we should not preallocate memory
  7886. // for inflate use constant limit in 65536 bytes
  7887. //
  7888. /* space at extra (only when reading header) */
  7889. // this.extra_max = 0;
  7890. /* pointer to zero-terminated file name or Z_NULL */
  7891. this.name = '';
  7892. /* space at name (only when reading header) */
  7893. // this.name_max = 0;
  7894. /* pointer to zero-terminated comment or Z_NULL */
  7895. this.comment = '';
  7896. /* space at comment (only when reading header) */
  7897. // this.comm_max = 0;
  7898. /* true if there was or will be a header crc */
  7899. this.hcrc = 0;
  7900. /* true when done reading gzip header (not used when writing a gzip file) */
  7901. this.done = false;
  7902. }
  7903. module.exports = GZheader;
  7904. },{}],34:[function(require,module,exports){
  7905. 'use strict';
  7906. // See state defs from inflate.js
  7907. var BAD = 30; /* got a data error -- remain here until reset */
  7908. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  7909. /*
  7910. Decode literal, length, and distance codes and write out the resulting
  7911. literal and match bytes until either not enough input or output is
  7912. available, an end-of-block is encountered, or a data error is encountered.
  7913. When large enough input and output buffers are supplied to inflate(), for
  7914. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  7915. inflate execution time is spent in this routine.
  7916. Entry assumptions:
  7917. state.mode === LEN
  7918. strm.avail_in >= 6
  7919. strm.avail_out >= 258
  7920. start >= strm.avail_out
  7921. state.bits < 8
  7922. On return, state.mode is one of:
  7923. LEN -- ran out of enough output space or enough available input
  7924. TYPE -- reached end of block code, inflate() to interpret next block
  7925. BAD -- error in block data
  7926. Notes:
  7927. - The maximum input bits used by a length/distance pair is 15 bits for the
  7928. length code, 5 bits for the length extra, 15 bits for the distance code,
  7929. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  7930. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  7931. checking for available input while decoding.
  7932. - The maximum bytes that a single length/distance pair can output is 258
  7933. bytes, which is the maximum length that can be coded. inflate_fast()
  7934. requires strm.avail_out >= 258 for each loop to avoid checking for
  7935. output space.
  7936. */
  7937. module.exports = function inflate_fast(strm, start) {
  7938. var state;
  7939. var _in; /* local strm.input */
  7940. var last; /* have enough input while in < last */
  7941. var _out; /* local strm.output */
  7942. var beg; /* inflate()'s initial strm.output */
  7943. var end; /* while out < end, enough space available */
  7944. //#ifdef INFLATE_STRICT
  7945. var dmax; /* maximum distance from zlib header */
  7946. //#endif
  7947. var wsize; /* window size or zero if not using window */
  7948. var whave; /* valid bytes in the window */
  7949. var wnext; /* window write index */
  7950. var window; /* allocated sliding window, if wsize != 0 */
  7951. var hold; /* local strm.hold */
  7952. var bits; /* local strm.bits */
  7953. var lcode; /* local strm.lencode */
  7954. var dcode; /* local strm.distcode */
  7955. var lmask; /* mask for first level of length codes */
  7956. var dmask; /* mask for first level of distance codes */
  7957. var here; /* retrieved table entry */
  7958. var op; /* code bits, operation, extra bits, or */
  7959. /* window position, window bytes to copy */
  7960. var len; /* match length, unused bytes */
  7961. var dist; /* match distance */
  7962. var from; /* where to copy match from */
  7963. var from_source;
  7964. var input, output; // JS specific, because we have no pointers
  7965. /* copy state to local variables */
  7966. state = strm.state;
  7967. //here = state.here;
  7968. _in = strm.next_in;
  7969. input = strm.input;
  7970. last = _in + (strm.avail_in - 5);
  7971. _out = strm.next_out;
  7972. output = strm.output;
  7973. beg = _out - (start - strm.avail_out);
  7974. end = _out + (strm.avail_out - 257);
  7975. //#ifdef INFLATE_STRICT
  7976. dmax = state.dmax;
  7977. //#endif
  7978. wsize = state.wsize;
  7979. whave = state.whave;
  7980. wnext = state.wnext;
  7981. window = state.window;
  7982. hold = state.hold;
  7983. bits = state.bits;
  7984. lcode = state.lencode;
  7985. dcode = state.distcode;
  7986. lmask = (1 << state.lenbits) - 1;
  7987. dmask = (1 << state.distbits) - 1;
  7988. /* decode literals and length/distances until end-of-block or not enough
  7989. input data or output space */
  7990. top:
  7991. do {
  7992. if (bits < 15) {
  7993. hold += input[_in++] << bits;
  7994. bits += 8;
  7995. hold += input[_in++] << bits;
  7996. bits += 8;
  7997. }
  7998. here = lcode[hold & lmask];
  7999. dolen:
  8000. for (;;) { // Goto emulation
  8001. op = here >>> 24/*here.bits*/;
  8002. hold >>>= op;
  8003. bits -= op;
  8004. op = (here >>> 16) & 0xff/*here.op*/;
  8005. if (op === 0) { /* literal */
  8006. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  8007. // "inflate: literal '%c'\n" :
  8008. // "inflate: literal 0x%02x\n", here.val));
  8009. output[_out++] = here & 0xffff/*here.val*/;
  8010. }
  8011. else if (op & 16) { /* length base */
  8012. len = here & 0xffff/*here.val*/;
  8013. op &= 15; /* number of extra bits */
  8014. if (op) {
  8015. if (bits < op) {
  8016. hold += input[_in++] << bits;
  8017. bits += 8;
  8018. }
  8019. len += hold & ((1 << op) - 1);
  8020. hold >>>= op;
  8021. bits -= op;
  8022. }
  8023. //Tracevv((stderr, "inflate: length %u\n", len));
  8024. if (bits < 15) {
  8025. hold += input[_in++] << bits;
  8026. bits += 8;
  8027. hold += input[_in++] << bits;
  8028. bits += 8;
  8029. }
  8030. here = dcode[hold & dmask];
  8031. dodist:
  8032. for (;;) { // goto emulation
  8033. op = here >>> 24/*here.bits*/;
  8034. hold >>>= op;
  8035. bits -= op;
  8036. op = (here >>> 16) & 0xff/*here.op*/;
  8037. if (op & 16) { /* distance base */
  8038. dist = here & 0xffff/*here.val*/;
  8039. op &= 15; /* number of extra bits */
  8040. if (bits < op) {
  8041. hold += input[_in++] << bits;
  8042. bits += 8;
  8043. if (bits < op) {
  8044. hold += input[_in++] << bits;
  8045. bits += 8;
  8046. }
  8047. }
  8048. dist += hold & ((1 << op) - 1);
  8049. //#ifdef INFLATE_STRICT
  8050. if (dist > dmax) {
  8051. strm.msg = 'invalid distance too far back';
  8052. state.mode = BAD;
  8053. break top;
  8054. }
  8055. //#endif
  8056. hold >>>= op;
  8057. bits -= op;
  8058. //Tracevv((stderr, "inflate: distance %u\n", dist));
  8059. op = _out - beg; /* max distance in output */
  8060. if (dist > op) { /* see if copy from window */
  8061. op = dist - op; /* distance back in window */
  8062. if (op > whave) {
  8063. if (state.sane) {
  8064. strm.msg = 'invalid distance too far back';
  8065. state.mode = BAD;
  8066. break top;
  8067. }
  8068. // (!) This block is disabled in zlib defailts,
  8069. // don't enable it for binary compatibility
  8070. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  8071. // if (len <= op - whave) {
  8072. // do {
  8073. // output[_out++] = 0;
  8074. // } while (--len);
  8075. // continue top;
  8076. // }
  8077. // len -= op - whave;
  8078. // do {
  8079. // output[_out++] = 0;
  8080. // } while (--op > whave);
  8081. // if (op === 0) {
  8082. // from = _out - dist;
  8083. // do {
  8084. // output[_out++] = output[from++];
  8085. // } while (--len);
  8086. // continue top;
  8087. // }
  8088. //#endif
  8089. }
  8090. from = 0; // window index
  8091. from_source = window;
  8092. if (wnext === 0) { /* very common case */
  8093. from += wsize - op;
  8094. if (op < len) { /* some from window */
  8095. len -= op;
  8096. do {
  8097. output[_out++] = window[from++];
  8098. } while (--op);
  8099. from = _out - dist; /* rest from output */
  8100. from_source = output;
  8101. }
  8102. }
  8103. else if (wnext < op) { /* wrap around window */
  8104. from += wsize + wnext - op;
  8105. op -= wnext;
  8106. if (op < len) { /* some from end of window */
  8107. len -= op;
  8108. do {
  8109. output[_out++] = window[from++];
  8110. } while (--op);
  8111. from = 0;
  8112. if (wnext < len) { /* some from start of window */
  8113. op = wnext;
  8114. len -= op;
  8115. do {
  8116. output[_out++] = window[from++];
  8117. } while (--op);
  8118. from = _out - dist; /* rest from output */
  8119. from_source = output;
  8120. }
  8121. }
  8122. }
  8123. else { /* contiguous in window */
  8124. from += wnext - op;
  8125. if (op < len) { /* some from window */
  8126. len -= op;
  8127. do {
  8128. output[_out++] = window[from++];
  8129. } while (--op);
  8130. from = _out - dist; /* rest from output */
  8131. from_source = output;
  8132. }
  8133. }
  8134. while (len > 2) {
  8135. output[_out++] = from_source[from++];
  8136. output[_out++] = from_source[from++];
  8137. output[_out++] = from_source[from++];
  8138. len -= 3;
  8139. }
  8140. if (len) {
  8141. output[_out++] = from_source[from++];
  8142. if (len > 1) {
  8143. output[_out++] = from_source[from++];
  8144. }
  8145. }
  8146. }
  8147. else {
  8148. from = _out - dist; /* copy direct from output */
  8149. do { /* minimum length is three */
  8150. output[_out++] = output[from++];
  8151. output[_out++] = output[from++];
  8152. output[_out++] = output[from++];
  8153. len -= 3;
  8154. } while (len > 2);
  8155. if (len) {
  8156. output[_out++] = output[from++];
  8157. if (len > 1) {
  8158. output[_out++] = output[from++];
  8159. }
  8160. }
  8161. }
  8162. }
  8163. else if ((op & 64) === 0) { /* 2nd level distance code */
  8164. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  8165. continue dodist;
  8166. }
  8167. else {
  8168. strm.msg = 'invalid distance code';
  8169. state.mode = BAD;
  8170. break top;
  8171. }
  8172. break; // need to emulate goto via "continue"
  8173. }
  8174. }
  8175. else if ((op & 64) === 0) { /* 2nd level length code */
  8176. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  8177. continue dolen;
  8178. }
  8179. else if (op & 32) { /* end-of-block */
  8180. //Tracevv((stderr, "inflate: end of block\n"));
  8181. state.mode = TYPE;
  8182. break top;
  8183. }
  8184. else {
  8185. strm.msg = 'invalid literal/length code';
  8186. state.mode = BAD;
  8187. break top;
  8188. }
  8189. break; // need to emulate goto via "continue"
  8190. }
  8191. } while (_in < last && _out < end);
  8192. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  8193. len = bits >> 3;
  8194. _in -= len;
  8195. bits -= len << 3;
  8196. hold &= (1 << bits) - 1;
  8197. /* update state and return */
  8198. strm.next_in = _in;
  8199. strm.next_out = _out;
  8200. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  8201. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  8202. state.hold = hold;
  8203. state.bits = bits;
  8204. return;
  8205. };
  8206. },{}],35:[function(require,module,exports){
  8207. 'use strict';
  8208. var utils = require('../utils/common');
  8209. var adler32 = require('./adler32');
  8210. var crc32 = require('./crc32');
  8211. var inflate_fast = require('./inffast');
  8212. var inflate_table = require('./inftrees');
  8213. var CODES = 0;
  8214. var LENS = 1;
  8215. var DISTS = 2;
  8216. /* Public constants ==========================================================*/
  8217. /* ===========================================================================*/
  8218. /* Allowed flush values; see deflate() and inflate() below for details */
  8219. //var Z_NO_FLUSH = 0;
  8220. //var Z_PARTIAL_FLUSH = 1;
  8221. //var Z_SYNC_FLUSH = 2;
  8222. //var Z_FULL_FLUSH = 3;
  8223. var Z_FINISH = 4;
  8224. var Z_BLOCK = 5;
  8225. var Z_TREES = 6;
  8226. /* Return codes for the compression/decompression functions. Negative values
  8227. * are errors, positive values are used for special but normal events.
  8228. */
  8229. var Z_OK = 0;
  8230. var Z_STREAM_END = 1;
  8231. var Z_NEED_DICT = 2;
  8232. //var Z_ERRNO = -1;
  8233. var Z_STREAM_ERROR = -2;
  8234. var Z_DATA_ERROR = -3;
  8235. var Z_MEM_ERROR = -4;
  8236. var Z_BUF_ERROR = -5;
  8237. //var Z_VERSION_ERROR = -6;
  8238. /* The deflate compression method */
  8239. var Z_DEFLATED = 8;
  8240. /* STATES ====================================================================*/
  8241. /* ===========================================================================*/
  8242. var HEAD = 1; /* i: waiting for magic header */
  8243. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  8244. var TIME = 3; /* i: waiting for modification time (gzip) */
  8245. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  8246. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  8247. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  8248. var NAME = 7; /* i: waiting for end of file name (gzip) */
  8249. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  8250. var HCRC = 9; /* i: waiting for header crc (gzip) */
  8251. var DICTID = 10; /* i: waiting for dictionary check value */
  8252. var DICT = 11; /* waiting for inflateSetDictionary() call */
  8253. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  8254. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  8255. var STORED = 14; /* i: waiting for stored size (length and complement) */
  8256. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  8257. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  8258. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  8259. var LENLENS = 18; /* i: waiting for code length code lengths */
  8260. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  8261. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  8262. var LEN = 21; /* i: waiting for length/lit/eob code */
  8263. var LENEXT = 22; /* i: waiting for length extra bits */
  8264. var DIST = 23; /* i: waiting for distance code */
  8265. var DISTEXT = 24; /* i: waiting for distance extra bits */
  8266. var MATCH = 25; /* o: waiting for output space to copy string */
  8267. var LIT = 26; /* o: waiting for output space to write literal */
  8268. var CHECK = 27; /* i: waiting for 32-bit check value */
  8269. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  8270. var DONE = 29; /* finished check, done -- remain here until reset */
  8271. var BAD = 30; /* got a data error -- remain here until reset */
  8272. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  8273. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  8274. /* ===========================================================================*/
  8275. var ENOUGH_LENS = 852;
  8276. var ENOUGH_DISTS = 592;
  8277. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  8278. var MAX_WBITS = 15;
  8279. /* 32K LZ77 window */
  8280. var DEF_WBITS = MAX_WBITS;
  8281. function ZSWAP32(q) {
  8282. return (((q >>> 24) & 0xff) +
  8283. ((q >>> 8) & 0xff00) +
  8284. ((q & 0xff00) << 8) +
  8285. ((q & 0xff) << 24));
  8286. }
  8287. function InflateState() {
  8288. this.mode = 0; /* current inflate mode */
  8289. this.last = false; /* true if processing last block */
  8290. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  8291. this.havedict = false; /* true if dictionary provided */
  8292. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  8293. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  8294. this.check = 0; /* protected copy of check value */
  8295. this.total = 0; /* protected copy of output count */
  8296. // TODO: may be {}
  8297. this.head = null; /* where to save gzip header information */
  8298. /* sliding window */
  8299. this.wbits = 0; /* log base 2 of requested window size */
  8300. this.wsize = 0; /* window size or zero if not using window */
  8301. this.whave = 0; /* valid bytes in the window */
  8302. this.wnext = 0; /* window write index */
  8303. this.window = null; /* allocated sliding window, if needed */
  8304. /* bit accumulator */
  8305. this.hold = 0; /* input bit accumulator */
  8306. this.bits = 0; /* number of bits in "in" */
  8307. /* for string and stored block copying */
  8308. this.length = 0; /* literal or length of data to copy */
  8309. this.offset = 0; /* distance back to copy string from */
  8310. /* for table and code decoding */
  8311. this.extra = 0; /* extra bits needed */
  8312. /* fixed and dynamic code tables */
  8313. this.lencode = null; /* starting table for length/literal codes */
  8314. this.distcode = null; /* starting table for distance codes */
  8315. this.lenbits = 0; /* index bits for lencode */
  8316. this.distbits = 0; /* index bits for distcode */
  8317. /* dynamic table building */
  8318. this.ncode = 0; /* number of code length code lengths */
  8319. this.nlen = 0; /* number of length code lengths */
  8320. this.ndist = 0; /* number of distance code lengths */
  8321. this.have = 0; /* number of code lengths in lens[] */
  8322. this.next = null; /* next available space in codes[] */
  8323. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  8324. this.work = new utils.Buf16(288); /* work area for code table building */
  8325. /*
  8326. because we don't have pointers in js, we use lencode and distcode directly
  8327. as buffers so we don't need codes
  8328. */
  8329. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  8330. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  8331. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  8332. this.sane = 0; /* if false, allow invalid distance too far */
  8333. this.back = 0; /* bits back of last unprocessed length/lit */
  8334. this.was = 0; /* initial length of match */
  8335. }
  8336. function inflateResetKeep(strm) {
  8337. var state;
  8338. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8339. state = strm.state;
  8340. strm.total_in = strm.total_out = state.total = 0;
  8341. strm.msg = ''; /*Z_NULL*/
  8342. if (state.wrap) { /* to support ill-conceived Java test suite */
  8343. strm.adler = state.wrap & 1;
  8344. }
  8345. state.mode = HEAD;
  8346. state.last = 0;
  8347. state.havedict = 0;
  8348. state.dmax = 32768;
  8349. state.head = null/*Z_NULL*/;
  8350. state.hold = 0;
  8351. state.bits = 0;
  8352. //state.lencode = state.distcode = state.next = state.codes;
  8353. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  8354. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  8355. state.sane = 1;
  8356. state.back = -1;
  8357. //Tracev((stderr, "inflate: reset\n"));
  8358. return Z_OK;
  8359. }
  8360. function inflateReset(strm) {
  8361. var state;
  8362. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8363. state = strm.state;
  8364. state.wsize = 0;
  8365. state.whave = 0;
  8366. state.wnext = 0;
  8367. return inflateResetKeep(strm);
  8368. }
  8369. function inflateReset2(strm, windowBits) {
  8370. var wrap;
  8371. var state;
  8372. /* get the state */
  8373. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8374. state = strm.state;
  8375. /* extract wrap request from windowBits parameter */
  8376. if (windowBits < 0) {
  8377. wrap = 0;
  8378. windowBits = -windowBits;
  8379. }
  8380. else {
  8381. wrap = (windowBits >> 4) + 1;
  8382. if (windowBits < 48) {
  8383. windowBits &= 15;
  8384. }
  8385. }
  8386. /* set number of window bits, free window if different */
  8387. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  8388. return Z_STREAM_ERROR;
  8389. }
  8390. if (state.window !== null && state.wbits !== windowBits) {
  8391. state.window = null;
  8392. }
  8393. /* update state and reset the rest of it */
  8394. state.wrap = wrap;
  8395. state.wbits = windowBits;
  8396. return inflateReset(strm);
  8397. }
  8398. function inflateInit2(strm, windowBits) {
  8399. var ret;
  8400. var state;
  8401. if (!strm) { return Z_STREAM_ERROR; }
  8402. //strm.msg = Z_NULL; /* in case we return an error */
  8403. state = new InflateState();
  8404. //if (state === Z_NULL) return Z_MEM_ERROR;
  8405. //Tracev((stderr, "inflate: allocated\n"));
  8406. strm.state = state;
  8407. state.window = null/*Z_NULL*/;
  8408. ret = inflateReset2(strm, windowBits);
  8409. if (ret !== Z_OK) {
  8410. strm.state = null/*Z_NULL*/;
  8411. }
  8412. return ret;
  8413. }
  8414. function inflateInit(strm) {
  8415. return inflateInit2(strm, DEF_WBITS);
  8416. }
  8417. /*
  8418. Return state with length and distance decoding tables and index sizes set to
  8419. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  8420. If BUILDFIXED is defined, then instead this routine builds the tables the
  8421. first time it's called, and returns those tables the first time and
  8422. thereafter. This reduces the size of the code by about 2K bytes, in
  8423. exchange for a little execution time. However, BUILDFIXED should not be
  8424. used for threaded applications, since the rewriting of the tables and virgin
  8425. may not be thread-safe.
  8426. */
  8427. var virgin = true;
  8428. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  8429. function fixedtables(state) {
  8430. /* build fixed huffman tables if first call (may not be thread safe) */
  8431. if (virgin) {
  8432. var sym;
  8433. lenfix = new utils.Buf32(512);
  8434. distfix = new utils.Buf32(32);
  8435. /* literal/length table */
  8436. sym = 0;
  8437. while (sym < 144) { state.lens[sym++] = 8; }
  8438. while (sym < 256) { state.lens[sym++] = 9; }
  8439. while (sym < 280) { state.lens[sym++] = 7; }
  8440. while (sym < 288) { state.lens[sym++] = 8; }
  8441. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  8442. /* distance table */
  8443. sym = 0;
  8444. while (sym < 32) { state.lens[sym++] = 5; }
  8445. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  8446. /* do this just once */
  8447. virgin = false;
  8448. }
  8449. state.lencode = lenfix;
  8450. state.lenbits = 9;
  8451. state.distcode = distfix;
  8452. state.distbits = 5;
  8453. }
  8454. /*
  8455. Update the window with the last wsize (normally 32K) bytes written before
  8456. returning. If window does not exist yet, create it. This is only called
  8457. when a window is already in use, or when output has been written during this
  8458. inflate call, but the end of the deflate stream has not been reached yet.
  8459. It is also called to create a window for dictionary data when a dictionary
  8460. is loaded.
  8461. Providing output buffers larger than 32K to inflate() should provide a speed
  8462. advantage, since only the last 32K of output is copied to the sliding window
  8463. upon return from inflate(), and since all distances after the first 32K of
  8464. output will fall in the output data, making match copies simpler and faster.
  8465. The advantage may be dependent on the size of the processor's data caches.
  8466. */
  8467. function updatewindow(strm, src, end, copy) {
  8468. var dist;
  8469. var state = strm.state;
  8470. /* if it hasn't been done already, allocate space for the window */
  8471. if (state.window === null) {
  8472. state.wsize = 1 << state.wbits;
  8473. state.wnext = 0;
  8474. state.whave = 0;
  8475. state.window = new utils.Buf8(state.wsize);
  8476. }
  8477. /* copy state->wsize or less output bytes into the circular window */
  8478. if (copy >= state.wsize) {
  8479. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  8480. state.wnext = 0;
  8481. state.whave = state.wsize;
  8482. }
  8483. else {
  8484. dist = state.wsize - state.wnext;
  8485. if (dist > copy) {
  8486. dist = copy;
  8487. }
  8488. //zmemcpy(state->window + state->wnext, end - copy, dist);
  8489. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  8490. copy -= dist;
  8491. if (copy) {
  8492. //zmemcpy(state->window, end - copy, copy);
  8493. utils.arraySet(state.window,src, end - copy, copy, 0);
  8494. state.wnext = copy;
  8495. state.whave = state.wsize;
  8496. }
  8497. else {
  8498. state.wnext += dist;
  8499. if (state.wnext === state.wsize) { state.wnext = 0; }
  8500. if (state.whave < state.wsize) { state.whave += dist; }
  8501. }
  8502. }
  8503. return 0;
  8504. }
  8505. function inflate(strm, flush) {
  8506. var state;
  8507. var input, output; // input/output buffers
  8508. var next; /* next input INDEX */
  8509. var put; /* next output INDEX */
  8510. var have, left; /* available input and output */
  8511. var hold; /* bit buffer */
  8512. var bits; /* bits in bit buffer */
  8513. var _in, _out; /* save starting available input and output */
  8514. var copy; /* number of stored or match bytes to copy */
  8515. var from; /* where to copy match bytes from */
  8516. var from_source;
  8517. var here = 0; /* current decoding table entry */
  8518. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  8519. //var last; /* parent table entry */
  8520. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  8521. var len; /* length to copy for repeats, bits to drop */
  8522. var ret; /* return code */
  8523. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  8524. var opts;
  8525. var n; // temporary var for NEED_BITS
  8526. var order = /* permutation of code lengths */
  8527. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  8528. if (!strm || !strm.state || !strm.output ||
  8529. (!strm.input && strm.avail_in !== 0)) {
  8530. return Z_STREAM_ERROR;
  8531. }
  8532. state = strm.state;
  8533. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  8534. //--- LOAD() ---
  8535. put = strm.next_out;
  8536. output = strm.output;
  8537. left = strm.avail_out;
  8538. next = strm.next_in;
  8539. input = strm.input;
  8540. have = strm.avail_in;
  8541. hold = state.hold;
  8542. bits = state.bits;
  8543. //---
  8544. _in = have;
  8545. _out = left;
  8546. ret = Z_OK;
  8547. inf_leave: // goto emulation
  8548. for (;;) {
  8549. switch (state.mode) {
  8550. case HEAD:
  8551. if (state.wrap === 0) {
  8552. state.mode = TYPEDO;
  8553. break;
  8554. }
  8555. //=== NEEDBITS(16);
  8556. while (bits < 16) {
  8557. if (have === 0) { break inf_leave; }
  8558. have--;
  8559. hold += input[next++] << bits;
  8560. bits += 8;
  8561. }
  8562. //===//
  8563. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  8564. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  8565. //=== CRC2(state.check, hold);
  8566. hbuf[0] = hold & 0xff;
  8567. hbuf[1] = (hold >>> 8) & 0xff;
  8568. state.check = crc32(state.check, hbuf, 2, 0);
  8569. //===//
  8570. //=== INITBITS();
  8571. hold = 0;
  8572. bits = 0;
  8573. //===//
  8574. state.mode = FLAGS;
  8575. break;
  8576. }
  8577. state.flags = 0; /* expect zlib header */
  8578. if (state.head) {
  8579. state.head.done = false;
  8580. }
  8581. if (!(state.wrap & 1) || /* check if zlib header allowed */
  8582. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  8583. strm.msg = 'incorrect header check';
  8584. state.mode = BAD;
  8585. break;
  8586. }
  8587. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  8588. strm.msg = 'unknown compression method';
  8589. state.mode = BAD;
  8590. break;
  8591. }
  8592. //--- DROPBITS(4) ---//
  8593. hold >>>= 4;
  8594. bits -= 4;
  8595. //---//
  8596. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  8597. if (state.wbits === 0) {
  8598. state.wbits = len;
  8599. }
  8600. else if (len > state.wbits) {
  8601. strm.msg = 'invalid window size';
  8602. state.mode = BAD;
  8603. break;
  8604. }
  8605. state.dmax = 1 << len;
  8606. //Tracev((stderr, "inflate: zlib header ok\n"));
  8607. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  8608. state.mode = hold & 0x200 ? DICTID : TYPE;
  8609. //=== INITBITS();
  8610. hold = 0;
  8611. bits = 0;
  8612. //===//
  8613. break;
  8614. case FLAGS:
  8615. //=== NEEDBITS(16); */
  8616. while (bits < 16) {
  8617. if (have === 0) { break inf_leave; }
  8618. have--;
  8619. hold += input[next++] << bits;
  8620. bits += 8;
  8621. }
  8622. //===//
  8623. state.flags = hold;
  8624. if ((state.flags & 0xff) !== Z_DEFLATED) {
  8625. strm.msg = 'unknown compression method';
  8626. state.mode = BAD;
  8627. break;
  8628. }
  8629. if (state.flags & 0xe000) {
  8630. strm.msg = 'unknown header flags set';
  8631. state.mode = BAD;
  8632. break;
  8633. }
  8634. if (state.head) {
  8635. state.head.text = ((hold >> 8) & 1);
  8636. }
  8637. if (state.flags & 0x0200) {
  8638. //=== CRC2(state.check, hold);
  8639. hbuf[0] = hold & 0xff;
  8640. hbuf[1] = (hold >>> 8) & 0xff;
  8641. state.check = crc32(state.check, hbuf, 2, 0);
  8642. //===//
  8643. }
  8644. //=== INITBITS();
  8645. hold = 0;
  8646. bits = 0;
  8647. //===//
  8648. state.mode = TIME;
  8649. /* falls through */
  8650. case TIME:
  8651. //=== NEEDBITS(32); */
  8652. while (bits < 32) {
  8653. if (have === 0) { break inf_leave; }
  8654. have--;
  8655. hold += input[next++] << bits;
  8656. bits += 8;
  8657. }
  8658. //===//
  8659. if (state.head) {
  8660. state.head.time = hold;
  8661. }
  8662. if (state.flags & 0x0200) {
  8663. //=== CRC4(state.check, hold)
  8664. hbuf[0] = hold & 0xff;
  8665. hbuf[1] = (hold >>> 8) & 0xff;
  8666. hbuf[2] = (hold >>> 16) & 0xff;
  8667. hbuf[3] = (hold >>> 24) & 0xff;
  8668. state.check = crc32(state.check, hbuf, 4, 0);
  8669. //===
  8670. }
  8671. //=== INITBITS();
  8672. hold = 0;
  8673. bits = 0;
  8674. //===//
  8675. state.mode = OS;
  8676. /* falls through */
  8677. case OS:
  8678. //=== NEEDBITS(16); */
  8679. while (bits < 16) {
  8680. if (have === 0) { break inf_leave; }
  8681. have--;
  8682. hold += input[next++] << bits;
  8683. bits += 8;
  8684. }
  8685. //===//
  8686. if (state.head) {
  8687. state.head.xflags = (hold & 0xff);
  8688. state.head.os = (hold >> 8);
  8689. }
  8690. if (state.flags & 0x0200) {
  8691. //=== CRC2(state.check, hold);
  8692. hbuf[0] = hold & 0xff;
  8693. hbuf[1] = (hold >>> 8) & 0xff;
  8694. state.check = crc32(state.check, hbuf, 2, 0);
  8695. //===//
  8696. }
  8697. //=== INITBITS();
  8698. hold = 0;
  8699. bits = 0;
  8700. //===//
  8701. state.mode = EXLEN;
  8702. /* falls through */
  8703. case EXLEN:
  8704. if (state.flags & 0x0400) {
  8705. //=== NEEDBITS(16); */
  8706. while (bits < 16) {
  8707. if (have === 0) { break inf_leave; }
  8708. have--;
  8709. hold += input[next++] << bits;
  8710. bits += 8;
  8711. }
  8712. //===//
  8713. state.length = hold;
  8714. if (state.head) {
  8715. state.head.extra_len = hold;
  8716. }
  8717. if (state.flags & 0x0200) {
  8718. //=== CRC2(state.check, hold);
  8719. hbuf[0] = hold & 0xff;
  8720. hbuf[1] = (hold >>> 8) & 0xff;
  8721. state.check = crc32(state.check, hbuf, 2, 0);
  8722. //===//
  8723. }
  8724. //=== INITBITS();
  8725. hold = 0;
  8726. bits = 0;
  8727. //===//
  8728. }
  8729. else if (state.head) {
  8730. state.head.extra = null/*Z_NULL*/;
  8731. }
  8732. state.mode = EXTRA;
  8733. /* falls through */
  8734. case EXTRA:
  8735. if (state.flags & 0x0400) {
  8736. copy = state.length;
  8737. if (copy > have) { copy = have; }
  8738. if (copy) {
  8739. if (state.head) {
  8740. len = state.head.extra_len - state.length;
  8741. if (!state.head.extra) {
  8742. // Use untyped array for more conveniend processing later
  8743. state.head.extra = new Array(state.head.extra_len);
  8744. }
  8745. utils.arraySet(
  8746. state.head.extra,
  8747. input,
  8748. next,
  8749. // extra field is limited to 65536 bytes
  8750. // - no need for additional size check
  8751. copy,
  8752. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  8753. len
  8754. );
  8755. //zmemcpy(state.head.extra + len, next,
  8756. // len + copy > state.head.extra_max ?
  8757. // state.head.extra_max - len : copy);
  8758. }
  8759. if (state.flags & 0x0200) {
  8760. state.check = crc32(state.check, input, copy, next);
  8761. }
  8762. have -= copy;
  8763. next += copy;
  8764. state.length -= copy;
  8765. }
  8766. if (state.length) { break inf_leave; }
  8767. }
  8768. state.length = 0;
  8769. state.mode = NAME;
  8770. /* falls through */
  8771. case NAME:
  8772. if (state.flags & 0x0800) {
  8773. if (have === 0) { break inf_leave; }
  8774. copy = 0;
  8775. do {
  8776. // TODO: 2 or 1 bytes?
  8777. len = input[next + copy++];
  8778. /* use constant limit because in js we should not preallocate memory */
  8779. if (state.head && len &&
  8780. (state.length < 65536 /*state.head.name_max*/)) {
  8781. state.head.name += String.fromCharCode(len);
  8782. }
  8783. } while (len && copy < have);
  8784. if (state.flags & 0x0200) {
  8785. state.check = crc32(state.check, input, copy, next);
  8786. }
  8787. have -= copy;
  8788. next += copy;
  8789. if (len) { break inf_leave; }
  8790. }
  8791. else if (state.head) {
  8792. state.head.name = null;
  8793. }
  8794. state.length = 0;
  8795. state.mode = COMMENT;
  8796. /* falls through */
  8797. case COMMENT:
  8798. if (state.flags & 0x1000) {
  8799. if (have === 0) { break inf_leave; }
  8800. copy = 0;
  8801. do {
  8802. len = input[next + copy++];
  8803. /* use constant limit because in js we should not preallocate memory */
  8804. if (state.head && len &&
  8805. (state.length < 65536 /*state.head.comm_max*/)) {
  8806. state.head.comment += String.fromCharCode(len);
  8807. }
  8808. } while (len && copy < have);
  8809. if (state.flags & 0x0200) {
  8810. state.check = crc32(state.check, input, copy, next);
  8811. }
  8812. have -= copy;
  8813. next += copy;
  8814. if (len) { break inf_leave; }
  8815. }
  8816. else if (state.head) {
  8817. state.head.comment = null;
  8818. }
  8819. state.mode = HCRC;
  8820. /* falls through */
  8821. case HCRC:
  8822. if (state.flags & 0x0200) {
  8823. //=== NEEDBITS(16); */
  8824. while (bits < 16) {
  8825. if (have === 0) { break inf_leave; }
  8826. have--;
  8827. hold += input[next++] << bits;
  8828. bits += 8;
  8829. }
  8830. //===//
  8831. if (hold !== (state.check & 0xffff)) {
  8832. strm.msg = 'header crc mismatch';
  8833. state.mode = BAD;
  8834. break;
  8835. }
  8836. //=== INITBITS();
  8837. hold = 0;
  8838. bits = 0;
  8839. //===//
  8840. }
  8841. if (state.head) {
  8842. state.head.hcrc = ((state.flags >> 9) & 1);
  8843. state.head.done = true;
  8844. }
  8845. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  8846. state.mode = TYPE;
  8847. break;
  8848. case DICTID:
  8849. //=== NEEDBITS(32); */
  8850. while (bits < 32) {
  8851. if (have === 0) { break inf_leave; }
  8852. have--;
  8853. hold += input[next++] << bits;
  8854. bits += 8;
  8855. }
  8856. //===//
  8857. strm.adler = state.check = ZSWAP32(hold);
  8858. //=== INITBITS();
  8859. hold = 0;
  8860. bits = 0;
  8861. //===//
  8862. state.mode = DICT;
  8863. /* falls through */
  8864. case DICT:
  8865. if (state.havedict === 0) {
  8866. //--- RESTORE() ---
  8867. strm.next_out = put;
  8868. strm.avail_out = left;
  8869. strm.next_in = next;
  8870. strm.avail_in = have;
  8871. state.hold = hold;
  8872. state.bits = bits;
  8873. //---
  8874. return Z_NEED_DICT;
  8875. }
  8876. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  8877. state.mode = TYPE;
  8878. /* falls through */
  8879. case TYPE:
  8880. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  8881. /* falls through */
  8882. case TYPEDO:
  8883. if (state.last) {
  8884. //--- BYTEBITS() ---//
  8885. hold >>>= bits & 7;
  8886. bits -= bits & 7;
  8887. //---//
  8888. state.mode = CHECK;
  8889. break;
  8890. }
  8891. //=== NEEDBITS(3); */
  8892. while (bits < 3) {
  8893. if (have === 0) { break inf_leave; }
  8894. have--;
  8895. hold += input[next++] << bits;
  8896. bits += 8;
  8897. }
  8898. //===//
  8899. state.last = (hold & 0x01)/*BITS(1)*/;
  8900. //--- DROPBITS(1) ---//
  8901. hold >>>= 1;
  8902. bits -= 1;
  8903. //---//
  8904. switch ((hold & 0x03)/*BITS(2)*/) {
  8905. case 0: /* stored block */
  8906. //Tracev((stderr, "inflate: stored block%s\n",
  8907. // state.last ? " (last)" : ""));
  8908. state.mode = STORED;
  8909. break;
  8910. case 1: /* fixed block */
  8911. fixedtables(state);
  8912. //Tracev((stderr, "inflate: fixed codes block%s\n",
  8913. // state.last ? " (last)" : ""));
  8914. state.mode = LEN_; /* decode codes */
  8915. if (flush === Z_TREES) {
  8916. //--- DROPBITS(2) ---//
  8917. hold >>>= 2;
  8918. bits -= 2;
  8919. //---//
  8920. break inf_leave;
  8921. }
  8922. break;
  8923. case 2: /* dynamic block */
  8924. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  8925. // state.last ? " (last)" : ""));
  8926. state.mode = TABLE;
  8927. break;
  8928. case 3:
  8929. strm.msg = 'invalid block type';
  8930. state.mode = BAD;
  8931. }
  8932. //--- DROPBITS(2) ---//
  8933. hold >>>= 2;
  8934. bits -= 2;
  8935. //---//
  8936. break;
  8937. case STORED:
  8938. //--- BYTEBITS() ---// /* go to byte boundary */
  8939. hold >>>= bits & 7;
  8940. bits -= bits & 7;
  8941. //---//
  8942. //=== NEEDBITS(32); */
  8943. while (bits < 32) {
  8944. if (have === 0) { break inf_leave; }
  8945. have--;
  8946. hold += input[next++] << bits;
  8947. bits += 8;
  8948. }
  8949. //===//
  8950. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  8951. strm.msg = 'invalid stored block lengths';
  8952. state.mode = BAD;
  8953. break;
  8954. }
  8955. state.length = hold & 0xffff;
  8956. //Tracev((stderr, "inflate: stored length %u\n",
  8957. // state.length));
  8958. //=== INITBITS();
  8959. hold = 0;
  8960. bits = 0;
  8961. //===//
  8962. state.mode = COPY_;
  8963. if (flush === Z_TREES) { break inf_leave; }
  8964. /* falls through */
  8965. case COPY_:
  8966. state.mode = COPY;
  8967. /* falls through */
  8968. case COPY:
  8969. copy = state.length;
  8970. if (copy) {
  8971. if (copy > have) { copy = have; }
  8972. if (copy > left) { copy = left; }
  8973. if (copy === 0) { break inf_leave; }
  8974. //--- zmemcpy(put, next, copy); ---
  8975. utils.arraySet(output, input, next, copy, put);
  8976. //---//
  8977. have -= copy;
  8978. next += copy;
  8979. left -= copy;
  8980. put += copy;
  8981. state.length -= copy;
  8982. break;
  8983. }
  8984. //Tracev((stderr, "inflate: stored end\n"));
  8985. state.mode = TYPE;
  8986. break;
  8987. case TABLE:
  8988. //=== NEEDBITS(14); */
  8989. while (bits < 14) {
  8990. if (have === 0) { break inf_leave; }
  8991. have--;
  8992. hold += input[next++] << bits;
  8993. bits += 8;
  8994. }
  8995. //===//
  8996. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  8997. //--- DROPBITS(5) ---//
  8998. hold >>>= 5;
  8999. bits -= 5;
  9000. //---//
  9001. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  9002. //--- DROPBITS(5) ---//
  9003. hold >>>= 5;
  9004. bits -= 5;
  9005. //---//
  9006. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  9007. //--- DROPBITS(4) ---//
  9008. hold >>>= 4;
  9009. bits -= 4;
  9010. //---//
  9011. //#ifndef PKZIP_BUG_WORKAROUND
  9012. if (state.nlen > 286 || state.ndist > 30) {
  9013. strm.msg = 'too many length or distance symbols';
  9014. state.mode = BAD;
  9015. break;
  9016. }
  9017. //#endif
  9018. //Tracev((stderr, "inflate: table sizes ok\n"));
  9019. state.have = 0;
  9020. state.mode = LENLENS;
  9021. /* falls through */
  9022. case LENLENS:
  9023. while (state.have < state.ncode) {
  9024. //=== NEEDBITS(3);
  9025. while (bits < 3) {
  9026. if (have === 0) { break inf_leave; }
  9027. have--;
  9028. hold += input[next++] << bits;
  9029. bits += 8;
  9030. }
  9031. //===//
  9032. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  9033. //--- DROPBITS(3) ---//
  9034. hold >>>= 3;
  9035. bits -= 3;
  9036. //---//
  9037. }
  9038. while (state.have < 19) {
  9039. state.lens[order[state.have++]] = 0;
  9040. }
  9041. // We have separate tables & no pointers. 2 commented lines below not needed.
  9042. //state.next = state.codes;
  9043. //state.lencode = state.next;
  9044. // Switch to use dynamic table
  9045. state.lencode = state.lendyn;
  9046. state.lenbits = 7;
  9047. opts = {bits: state.lenbits};
  9048. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  9049. state.lenbits = opts.bits;
  9050. if (ret) {
  9051. strm.msg = 'invalid code lengths set';
  9052. state.mode = BAD;
  9053. break;
  9054. }
  9055. //Tracev((stderr, "inflate: code lengths ok\n"));
  9056. state.have = 0;
  9057. state.mode = CODELENS;
  9058. /* falls through */
  9059. case CODELENS:
  9060. while (state.have < state.nlen + state.ndist) {
  9061. for (;;) {
  9062. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  9063. here_bits = here >>> 24;
  9064. here_op = (here >>> 16) & 0xff;
  9065. here_val = here & 0xffff;
  9066. if ((here_bits) <= bits) { break; }
  9067. //--- PULLBYTE() ---//
  9068. if (have === 0) { break inf_leave; }
  9069. have--;
  9070. hold += input[next++] << bits;
  9071. bits += 8;
  9072. //---//
  9073. }
  9074. if (here_val < 16) {
  9075. //--- DROPBITS(here.bits) ---//
  9076. hold >>>= here_bits;
  9077. bits -= here_bits;
  9078. //---//
  9079. state.lens[state.have++] = here_val;
  9080. }
  9081. else {
  9082. if (here_val === 16) {
  9083. //=== NEEDBITS(here.bits + 2);
  9084. n = here_bits + 2;
  9085. while (bits < n) {
  9086. if (have === 0) { break inf_leave; }
  9087. have--;
  9088. hold += input[next++] << bits;
  9089. bits += 8;
  9090. }
  9091. //===//
  9092. //--- DROPBITS(here.bits) ---//
  9093. hold >>>= here_bits;
  9094. bits -= here_bits;
  9095. //---//
  9096. if (state.have === 0) {
  9097. strm.msg = 'invalid bit length repeat';
  9098. state.mode = BAD;
  9099. break;
  9100. }
  9101. len = state.lens[state.have - 1];
  9102. copy = 3 + (hold & 0x03);//BITS(2);
  9103. //--- DROPBITS(2) ---//
  9104. hold >>>= 2;
  9105. bits -= 2;
  9106. //---//
  9107. }
  9108. else if (here_val === 17) {
  9109. //=== NEEDBITS(here.bits + 3);
  9110. n = here_bits + 3;
  9111. while (bits < n) {
  9112. if (have === 0) { break inf_leave; }
  9113. have--;
  9114. hold += input[next++] << bits;
  9115. bits += 8;
  9116. }
  9117. //===//
  9118. //--- DROPBITS(here.bits) ---//
  9119. hold >>>= here_bits;
  9120. bits -= here_bits;
  9121. //---//
  9122. len = 0;
  9123. copy = 3 + (hold & 0x07);//BITS(3);
  9124. //--- DROPBITS(3) ---//
  9125. hold >>>= 3;
  9126. bits -= 3;
  9127. //---//
  9128. }
  9129. else {
  9130. //=== NEEDBITS(here.bits + 7);
  9131. n = here_bits + 7;
  9132. while (bits < n) {
  9133. if (have === 0) { break inf_leave; }
  9134. have--;
  9135. hold += input[next++] << bits;
  9136. bits += 8;
  9137. }
  9138. //===//
  9139. //--- DROPBITS(here.bits) ---//
  9140. hold >>>= here_bits;
  9141. bits -= here_bits;
  9142. //---//
  9143. len = 0;
  9144. copy = 11 + (hold & 0x7f);//BITS(7);
  9145. //--- DROPBITS(7) ---//
  9146. hold >>>= 7;
  9147. bits -= 7;
  9148. //---//
  9149. }
  9150. if (state.have + copy > state.nlen + state.ndist) {
  9151. strm.msg = 'invalid bit length repeat';
  9152. state.mode = BAD;
  9153. break;
  9154. }
  9155. while (copy--) {
  9156. state.lens[state.have++] = len;
  9157. }
  9158. }
  9159. }
  9160. /* handle error breaks in while */
  9161. if (state.mode === BAD) { break; }
  9162. /* check for end-of-block code (better have one) */
  9163. if (state.lens[256] === 0) {
  9164. strm.msg = 'invalid code -- missing end-of-block';
  9165. state.mode = BAD;
  9166. break;
  9167. }
  9168. /* build code tables -- note: do not change the lenbits or distbits
  9169. values here (9 and 6) without reading the comments in inftrees.h
  9170. concerning the ENOUGH constants, which depend on those values */
  9171. state.lenbits = 9;
  9172. opts = {bits: state.lenbits};
  9173. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  9174. // We have separate tables & no pointers. 2 commented lines below not needed.
  9175. // state.next_index = opts.table_index;
  9176. state.lenbits = opts.bits;
  9177. // state.lencode = state.next;
  9178. if (ret) {
  9179. strm.msg = 'invalid literal/lengths set';
  9180. state.mode = BAD;
  9181. break;
  9182. }
  9183. state.distbits = 6;
  9184. //state.distcode.copy(state.codes);
  9185. // Switch to use dynamic table
  9186. state.distcode = state.distdyn;
  9187. opts = {bits: state.distbits};
  9188. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  9189. // We have separate tables & no pointers. 2 commented lines below not needed.
  9190. // state.next_index = opts.table_index;
  9191. state.distbits = opts.bits;
  9192. // state.distcode = state.next;
  9193. if (ret) {
  9194. strm.msg = 'invalid distances set';
  9195. state.mode = BAD;
  9196. break;
  9197. }
  9198. //Tracev((stderr, 'inflate: codes ok\n'));
  9199. state.mode = LEN_;
  9200. if (flush === Z_TREES) { break inf_leave; }
  9201. /* falls through */
  9202. case LEN_:
  9203. state.mode = LEN;
  9204. /* falls through */
  9205. case LEN:
  9206. if (have >= 6 && left >= 258) {
  9207. //--- RESTORE() ---
  9208. strm.next_out = put;
  9209. strm.avail_out = left;
  9210. strm.next_in = next;
  9211. strm.avail_in = have;
  9212. state.hold = hold;
  9213. state.bits = bits;
  9214. //---
  9215. inflate_fast(strm, _out);
  9216. //--- LOAD() ---
  9217. put = strm.next_out;
  9218. output = strm.output;
  9219. left = strm.avail_out;
  9220. next = strm.next_in;
  9221. input = strm.input;
  9222. have = strm.avail_in;
  9223. hold = state.hold;
  9224. bits = state.bits;
  9225. //---
  9226. if (state.mode === TYPE) {
  9227. state.back = -1;
  9228. }
  9229. break;
  9230. }
  9231. state.back = 0;
  9232. for (;;) {
  9233. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  9234. here_bits = here >>> 24;
  9235. here_op = (here >>> 16) & 0xff;
  9236. here_val = here & 0xffff;
  9237. if (here_bits <= bits) { break; }
  9238. //--- PULLBYTE() ---//
  9239. if (have === 0) { break inf_leave; }
  9240. have--;
  9241. hold += input[next++] << bits;
  9242. bits += 8;
  9243. //---//
  9244. }
  9245. if (here_op && (here_op & 0xf0) === 0) {
  9246. last_bits = here_bits;
  9247. last_op = here_op;
  9248. last_val = here_val;
  9249. for (;;) {
  9250. here = state.lencode[last_val +
  9251. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  9252. here_bits = here >>> 24;
  9253. here_op = (here >>> 16) & 0xff;
  9254. here_val = here & 0xffff;
  9255. if ((last_bits + here_bits) <= bits) { break; }
  9256. //--- PULLBYTE() ---//
  9257. if (have === 0) { break inf_leave; }
  9258. have--;
  9259. hold += input[next++] << bits;
  9260. bits += 8;
  9261. //---//
  9262. }
  9263. //--- DROPBITS(last.bits) ---//
  9264. hold >>>= last_bits;
  9265. bits -= last_bits;
  9266. //---//
  9267. state.back += last_bits;
  9268. }
  9269. //--- DROPBITS(here.bits) ---//
  9270. hold >>>= here_bits;
  9271. bits -= here_bits;
  9272. //---//
  9273. state.back += here_bits;
  9274. state.length = here_val;
  9275. if (here_op === 0) {
  9276. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  9277. // "inflate: literal '%c'\n" :
  9278. // "inflate: literal 0x%02x\n", here.val));
  9279. state.mode = LIT;
  9280. break;
  9281. }
  9282. if (here_op & 32) {
  9283. //Tracevv((stderr, "inflate: end of block\n"));
  9284. state.back = -1;
  9285. state.mode = TYPE;
  9286. break;
  9287. }
  9288. if (here_op & 64) {
  9289. strm.msg = 'invalid literal/length code';
  9290. state.mode = BAD;
  9291. break;
  9292. }
  9293. state.extra = here_op & 15;
  9294. state.mode = LENEXT;
  9295. /* falls through */
  9296. case LENEXT:
  9297. if (state.extra) {
  9298. //=== NEEDBITS(state.extra);
  9299. n = state.extra;
  9300. while (bits < n) {
  9301. if (have === 0) { break inf_leave; }
  9302. have--;
  9303. hold += input[next++] << bits;
  9304. bits += 8;
  9305. }
  9306. //===//
  9307. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  9308. //--- DROPBITS(state.extra) ---//
  9309. hold >>>= state.extra;
  9310. bits -= state.extra;
  9311. //---//
  9312. state.back += state.extra;
  9313. }
  9314. //Tracevv((stderr, "inflate: length %u\n", state.length));
  9315. state.was = state.length;
  9316. state.mode = DIST;
  9317. /* falls through */
  9318. case DIST:
  9319. for (;;) {
  9320. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  9321. here_bits = here >>> 24;
  9322. here_op = (here >>> 16) & 0xff;
  9323. here_val = here & 0xffff;
  9324. if ((here_bits) <= bits) { break; }
  9325. //--- PULLBYTE() ---//
  9326. if (have === 0) { break inf_leave; }
  9327. have--;
  9328. hold += input[next++] << bits;
  9329. bits += 8;
  9330. //---//
  9331. }
  9332. if ((here_op & 0xf0) === 0) {
  9333. last_bits = here_bits;
  9334. last_op = here_op;
  9335. last_val = here_val;
  9336. for (;;) {
  9337. here = state.distcode[last_val +
  9338. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  9339. here_bits = here >>> 24;
  9340. here_op = (here >>> 16) & 0xff;
  9341. here_val = here & 0xffff;
  9342. if ((last_bits + here_bits) <= bits) { break; }
  9343. //--- PULLBYTE() ---//
  9344. if (have === 0) { break inf_leave; }
  9345. have--;
  9346. hold += input[next++] << bits;
  9347. bits += 8;
  9348. //---//
  9349. }
  9350. //--- DROPBITS(last.bits) ---//
  9351. hold >>>= last_bits;
  9352. bits -= last_bits;
  9353. //---//
  9354. state.back += last_bits;
  9355. }
  9356. //--- DROPBITS(here.bits) ---//
  9357. hold >>>= here_bits;
  9358. bits -= here_bits;
  9359. //---//
  9360. state.back += here_bits;
  9361. if (here_op & 64) {
  9362. strm.msg = 'invalid distance code';
  9363. state.mode = BAD;
  9364. break;
  9365. }
  9366. state.offset = here_val;
  9367. state.extra = (here_op) & 15;
  9368. state.mode = DISTEXT;
  9369. /* falls through */
  9370. case DISTEXT:
  9371. if (state.extra) {
  9372. //=== NEEDBITS(state.extra);
  9373. n = state.extra;
  9374. while (bits < n) {
  9375. if (have === 0) { break inf_leave; }
  9376. have--;
  9377. hold += input[next++] << bits;
  9378. bits += 8;
  9379. }
  9380. //===//
  9381. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  9382. //--- DROPBITS(state.extra) ---//
  9383. hold >>>= state.extra;
  9384. bits -= state.extra;
  9385. //---//
  9386. state.back += state.extra;
  9387. }
  9388. //#ifdef INFLATE_STRICT
  9389. if (state.offset > state.dmax) {
  9390. strm.msg = 'invalid distance too far back';
  9391. state.mode = BAD;
  9392. break;
  9393. }
  9394. //#endif
  9395. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  9396. state.mode = MATCH;
  9397. /* falls through */
  9398. case MATCH:
  9399. if (left === 0) { break inf_leave; }
  9400. copy = _out - left;
  9401. if (state.offset > copy) { /* copy from window */
  9402. copy = state.offset - copy;
  9403. if (copy > state.whave) {
  9404. if (state.sane) {
  9405. strm.msg = 'invalid distance too far back';
  9406. state.mode = BAD;
  9407. break;
  9408. }
  9409. // (!) This block is disabled in zlib defailts,
  9410. // don't enable it for binary compatibility
  9411. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  9412. // Trace((stderr, "inflate.c too far\n"));
  9413. // copy -= state.whave;
  9414. // if (copy > state.length) { copy = state.length; }
  9415. // if (copy > left) { copy = left; }
  9416. // left -= copy;
  9417. // state.length -= copy;
  9418. // do {
  9419. // output[put++] = 0;
  9420. // } while (--copy);
  9421. // if (state.length === 0) { state.mode = LEN; }
  9422. // break;
  9423. //#endif
  9424. }
  9425. if (copy > state.wnext) {
  9426. copy -= state.wnext;
  9427. from = state.wsize - copy;
  9428. }
  9429. else {
  9430. from = state.wnext - copy;
  9431. }
  9432. if (copy > state.length) { copy = state.length; }
  9433. from_source = state.window;
  9434. }
  9435. else { /* copy from output */
  9436. from_source = output;
  9437. from = put - state.offset;
  9438. copy = state.length;
  9439. }
  9440. if (copy > left) { copy = left; }
  9441. left -= copy;
  9442. state.length -= copy;
  9443. do {
  9444. output[put++] = from_source[from++];
  9445. } while (--copy);
  9446. if (state.length === 0) { state.mode = LEN; }
  9447. break;
  9448. case LIT:
  9449. if (left === 0) { break inf_leave; }
  9450. output[put++] = state.length;
  9451. left--;
  9452. state.mode = LEN;
  9453. break;
  9454. case CHECK:
  9455. if (state.wrap) {
  9456. //=== NEEDBITS(32);
  9457. while (bits < 32) {
  9458. if (have === 0) { break inf_leave; }
  9459. have--;
  9460. // Use '|' insdead of '+' to make sure that result is signed
  9461. hold |= input[next++] << bits;
  9462. bits += 8;
  9463. }
  9464. //===//
  9465. _out -= left;
  9466. strm.total_out += _out;
  9467. state.total += _out;
  9468. if (_out) {
  9469. strm.adler = state.check =
  9470. /*UPDATE(state.check, put - _out, _out);*/
  9471. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  9472. }
  9473. _out = left;
  9474. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  9475. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  9476. strm.msg = 'incorrect data check';
  9477. state.mode = BAD;
  9478. break;
  9479. }
  9480. //=== INITBITS();
  9481. hold = 0;
  9482. bits = 0;
  9483. //===//
  9484. //Tracev((stderr, "inflate: check matches trailer\n"));
  9485. }
  9486. state.mode = LENGTH;
  9487. /* falls through */
  9488. case LENGTH:
  9489. if (state.wrap && state.flags) {
  9490. //=== NEEDBITS(32);
  9491. while (bits < 32) {
  9492. if (have === 0) { break inf_leave; }
  9493. have--;
  9494. hold += input[next++] << bits;
  9495. bits += 8;
  9496. }
  9497. //===//
  9498. if (hold !== (state.total & 0xffffffff)) {
  9499. strm.msg = 'incorrect length check';
  9500. state.mode = BAD;
  9501. break;
  9502. }
  9503. //=== INITBITS();
  9504. hold = 0;
  9505. bits = 0;
  9506. //===//
  9507. //Tracev((stderr, "inflate: length matches trailer\n"));
  9508. }
  9509. state.mode = DONE;
  9510. /* falls through */
  9511. case DONE:
  9512. ret = Z_STREAM_END;
  9513. break inf_leave;
  9514. case BAD:
  9515. ret = Z_DATA_ERROR;
  9516. break inf_leave;
  9517. case MEM:
  9518. return Z_MEM_ERROR;
  9519. case SYNC:
  9520. /* falls through */
  9521. default:
  9522. return Z_STREAM_ERROR;
  9523. }
  9524. }
  9525. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  9526. /*
  9527. Return from inflate(), updating the total counts and the check value.
  9528. If there was no progress during the inflate() call, return a buffer
  9529. error. Call updatewindow() to create and/or update the window state.
  9530. Note: a memory error from inflate() is non-recoverable.
  9531. */
  9532. //--- RESTORE() ---
  9533. strm.next_out = put;
  9534. strm.avail_out = left;
  9535. strm.next_in = next;
  9536. strm.avail_in = have;
  9537. state.hold = hold;
  9538. state.bits = bits;
  9539. //---
  9540. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  9541. (state.mode < CHECK || flush !== Z_FINISH))) {
  9542. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  9543. state.mode = MEM;
  9544. return Z_MEM_ERROR;
  9545. }
  9546. }
  9547. _in -= strm.avail_in;
  9548. _out -= strm.avail_out;
  9549. strm.total_in += _in;
  9550. strm.total_out += _out;
  9551. state.total += _out;
  9552. if (state.wrap && _out) {
  9553. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  9554. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  9555. }
  9556. strm.data_type = state.bits + (state.last ? 64 : 0) +
  9557. (state.mode === TYPE ? 128 : 0) +
  9558. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  9559. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  9560. ret = Z_BUF_ERROR;
  9561. }
  9562. return ret;
  9563. }
  9564. function inflateEnd(strm) {
  9565. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  9566. return Z_STREAM_ERROR;
  9567. }
  9568. var state = strm.state;
  9569. if (state.window) {
  9570. state.window = null;
  9571. }
  9572. strm.state = null;
  9573. return Z_OK;
  9574. }
  9575. function inflateGetHeader(strm, head) {
  9576. var state;
  9577. /* check state */
  9578. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  9579. state = strm.state;
  9580. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  9581. /* save header structure */
  9582. state.head = head;
  9583. head.done = false;
  9584. return Z_OK;
  9585. }
  9586. exports.inflateReset = inflateReset;
  9587. exports.inflateReset2 = inflateReset2;
  9588. exports.inflateResetKeep = inflateResetKeep;
  9589. exports.inflateInit = inflateInit;
  9590. exports.inflateInit2 = inflateInit2;
  9591. exports.inflate = inflate;
  9592. exports.inflateEnd = inflateEnd;
  9593. exports.inflateGetHeader = inflateGetHeader;
  9594. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  9595. /* Not implemented
  9596. exports.inflateCopy = inflateCopy;
  9597. exports.inflateGetDictionary = inflateGetDictionary;
  9598. exports.inflateMark = inflateMark;
  9599. exports.inflatePrime = inflatePrime;
  9600. exports.inflateSetDictionary = inflateSetDictionary;
  9601. exports.inflateSync = inflateSync;
  9602. exports.inflateSyncPoint = inflateSyncPoint;
  9603. exports.inflateUndermine = inflateUndermine;
  9604. */
  9605. },{"../utils/common":27,"./adler32":29,"./crc32":31,"./inffast":34,"./inftrees":36}],36:[function(require,module,exports){
  9606. 'use strict';
  9607. var utils = require('../utils/common');
  9608. var MAXBITS = 15;
  9609. var ENOUGH_LENS = 852;
  9610. var ENOUGH_DISTS = 592;
  9611. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  9612. var CODES = 0;
  9613. var LENS = 1;
  9614. var DISTS = 2;
  9615. var lbase = [ /* Length codes 257..285 base */
  9616. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  9617. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  9618. ];
  9619. var lext = [ /* Length codes 257..285 extra */
  9620. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  9621. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  9622. ];
  9623. var dbase = [ /* Distance codes 0..29 base */
  9624. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  9625. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  9626. 8193, 12289, 16385, 24577, 0, 0
  9627. ];
  9628. var dext = [ /* Distance codes 0..29 extra */
  9629. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  9630. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  9631. 28, 28, 29, 29, 64, 64
  9632. ];
  9633. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  9634. {
  9635. var bits = opts.bits;
  9636. //here = opts.here; /* table entry for duplication */
  9637. var len = 0; /* a code's length in bits */
  9638. var sym = 0; /* index of code symbols */
  9639. var min = 0, max = 0; /* minimum and maximum code lengths */
  9640. var root = 0; /* number of index bits for root table */
  9641. var curr = 0; /* number of index bits for current table */
  9642. var drop = 0; /* code bits to drop for sub-table */
  9643. var left = 0; /* number of prefix codes available */
  9644. var used = 0; /* code entries in table used */
  9645. var huff = 0; /* Huffman code */
  9646. var incr; /* for incrementing code, index */
  9647. var fill; /* index for replicating entries */
  9648. var low; /* low bits for current root entry */
  9649. var mask; /* mask for low root bits */
  9650. var next; /* next available space in table */
  9651. var base = null; /* base value table to use */
  9652. var base_index = 0;
  9653. // var shoextra; /* extra bits table to use */
  9654. var end; /* use base and extra for symbol > end */
  9655. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  9656. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  9657. var extra = null;
  9658. var extra_index = 0;
  9659. var here_bits, here_op, here_val;
  9660. /*
  9661. Process a set of code lengths to create a canonical Huffman code. The
  9662. code lengths are lens[0..codes-1]. Each length corresponds to the
  9663. symbols 0..codes-1. The Huffman code is generated by first sorting the
  9664. symbols by length from short to long, and retaining the symbol order
  9665. for codes with equal lengths. Then the code starts with all zero bits
  9666. for the first code of the shortest length, and the codes are integer
  9667. increments for the same length, and zeros are appended as the length
  9668. increases. For the deflate format, these bits are stored backwards
  9669. from their more natural integer increment ordering, and so when the
  9670. decoding tables are built in the large loop below, the integer codes
  9671. are incremented backwards.
  9672. This routine assumes, but does not check, that all of the entries in
  9673. lens[] are in the range 0..MAXBITS. The caller must assure this.
  9674. 1..MAXBITS is interpreted as that code length. zero means that that
  9675. symbol does not occur in this code.
  9676. The codes are sorted by computing a count of codes for each length,
  9677. creating from that a table of starting indices for each length in the
  9678. sorted table, and then entering the symbols in order in the sorted
  9679. table. The sorted table is work[], with that space being provided by
  9680. the caller.
  9681. The length counts are used for other purposes as well, i.e. finding
  9682. the minimum and maximum length codes, determining if there are any
  9683. codes at all, checking for a valid set of lengths, and looking ahead
  9684. at length counts to determine sub-table sizes when building the
  9685. decoding tables.
  9686. */
  9687. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  9688. for (len = 0; len <= MAXBITS; len++) {
  9689. count[len] = 0;
  9690. }
  9691. for (sym = 0; sym < codes; sym++) {
  9692. count[lens[lens_index + sym]]++;
  9693. }
  9694. /* bound code lengths, force root to be within code lengths */
  9695. root = bits;
  9696. for (max = MAXBITS; max >= 1; max--) {
  9697. if (count[max] !== 0) { break; }
  9698. }
  9699. if (root > max) {
  9700. root = max;
  9701. }
  9702. if (max === 0) { /* no symbols to code at all */
  9703. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  9704. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  9705. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  9706. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  9707. //table.op[opts.table_index] = 64;
  9708. //table.bits[opts.table_index] = 1;
  9709. //table.val[opts.table_index++] = 0;
  9710. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  9711. opts.bits = 1;
  9712. return 0; /* no symbols, but wait for decoding to report error */
  9713. }
  9714. for (min = 1; min < max; min++) {
  9715. if (count[min] !== 0) { break; }
  9716. }
  9717. if (root < min) {
  9718. root = min;
  9719. }
  9720. /* check for an over-subscribed or incomplete set of lengths */
  9721. left = 1;
  9722. for (len = 1; len <= MAXBITS; len++) {
  9723. left <<= 1;
  9724. left -= count[len];
  9725. if (left < 0) {
  9726. return -1;
  9727. } /* over-subscribed */
  9728. }
  9729. if (left > 0 && (type === CODES || max !== 1)) {
  9730. return -1; /* incomplete set */
  9731. }
  9732. /* generate offsets into symbol table for each length for sorting */
  9733. offs[1] = 0;
  9734. for (len = 1; len < MAXBITS; len++) {
  9735. offs[len + 1] = offs[len] + count[len];
  9736. }
  9737. /* sort symbols by length, by symbol order within each length */
  9738. for (sym = 0; sym < codes; sym++) {
  9739. if (lens[lens_index + sym] !== 0) {
  9740. work[offs[lens[lens_index + sym]]++] = sym;
  9741. }
  9742. }
  9743. /*
  9744. Create and fill in decoding tables. In this loop, the table being
  9745. filled is at next and has curr index bits. The code being used is huff
  9746. with length len. That code is converted to an index by dropping drop
  9747. bits off of the bottom. For codes where len is less than drop + curr,
  9748. those top drop + curr - len bits are incremented through all values to
  9749. fill the table with replicated entries.
  9750. root is the number of index bits for the root table. When len exceeds
  9751. root, sub-tables are created pointed to by the root entry with an index
  9752. of the low root bits of huff. This is saved in low to check for when a
  9753. new sub-table should be started. drop is zero when the root table is
  9754. being filled, and drop is root when sub-tables are being filled.
  9755. When a new sub-table is needed, it is necessary to look ahead in the
  9756. code lengths to determine what size sub-table is needed. The length
  9757. counts are used for this, and so count[] is decremented as codes are
  9758. entered in the tables.
  9759. used keeps track of how many table entries have been allocated from the
  9760. provided *table space. It is checked for LENS and DIST tables against
  9761. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  9762. the initial root table size constants. See the comments in inftrees.h
  9763. for more information.
  9764. sym increments through all symbols, and the loop terminates when
  9765. all codes of length max, i.e. all codes, have been processed. This
  9766. routine permits incomplete codes, so another loop after this one fills
  9767. in the rest of the decoding tables with invalid code markers.
  9768. */
  9769. /* set up for code type */
  9770. // poor man optimization - use if-else instead of switch,
  9771. // to avoid deopts in old v8
  9772. if (type === CODES) {
  9773. base = extra = work; /* dummy value--not used */
  9774. end = 19;
  9775. } else if (type === LENS) {
  9776. base = lbase;
  9777. base_index -= 257;
  9778. extra = lext;
  9779. extra_index -= 257;
  9780. end = 256;
  9781. } else { /* DISTS */
  9782. base = dbase;
  9783. extra = dext;
  9784. end = -1;
  9785. }
  9786. /* initialize opts for loop */
  9787. huff = 0; /* starting code */
  9788. sym = 0; /* starting code symbol */
  9789. len = min; /* starting code length */
  9790. next = table_index; /* current table to fill in */
  9791. curr = root; /* current table index bits */
  9792. drop = 0; /* current bits to drop from code for index */
  9793. low = -1; /* trigger new sub-table when len > root */
  9794. used = 1 << root; /* use root table entries */
  9795. mask = used - 1; /* mask for comparing low */
  9796. /* check available table space */
  9797. if ((type === LENS && used > ENOUGH_LENS) ||
  9798. (type === DISTS && used > ENOUGH_DISTS)) {
  9799. return 1;
  9800. }
  9801. var i=0;
  9802. /* process all codes and make table entries */
  9803. for (;;) {
  9804. i++;
  9805. /* create table entry */
  9806. here_bits = len - drop;
  9807. if (work[sym] < end) {
  9808. here_op = 0;
  9809. here_val = work[sym];
  9810. }
  9811. else if (work[sym] > end) {
  9812. here_op = extra[extra_index + work[sym]];
  9813. here_val = base[base_index + work[sym]];
  9814. }
  9815. else {
  9816. here_op = 32 + 64; /* end of block */
  9817. here_val = 0;
  9818. }
  9819. /* replicate for those indices with low len bits equal to huff */
  9820. incr = 1 << (len - drop);
  9821. fill = 1 << curr;
  9822. min = fill; /* save offset to next table */
  9823. do {
  9824. fill -= incr;
  9825. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  9826. } while (fill !== 0);
  9827. /* backwards increment the len-bit code huff */
  9828. incr = 1 << (len - 1);
  9829. while (huff & incr) {
  9830. incr >>= 1;
  9831. }
  9832. if (incr !== 0) {
  9833. huff &= incr - 1;
  9834. huff += incr;
  9835. } else {
  9836. huff = 0;
  9837. }
  9838. /* go to next symbol, update count, len */
  9839. sym++;
  9840. if (--count[len] === 0) {
  9841. if (len === max) { break; }
  9842. len = lens[lens_index + work[sym]];
  9843. }
  9844. /* create new sub-table if needed */
  9845. if (len > root && (huff & mask) !== low) {
  9846. /* if first time, transition to sub-tables */
  9847. if (drop === 0) {
  9848. drop = root;
  9849. }
  9850. /* increment past last table */
  9851. next += min; /* here min is 1 << curr */
  9852. /* determine length of next table */
  9853. curr = len - drop;
  9854. left = 1 << curr;
  9855. while (curr + drop < max) {
  9856. left -= count[curr + drop];
  9857. if (left <= 0) { break; }
  9858. curr++;
  9859. left <<= 1;
  9860. }
  9861. /* check for enough space */
  9862. used += 1 << curr;
  9863. if ((type === LENS && used > ENOUGH_LENS) ||
  9864. (type === DISTS && used > ENOUGH_DISTS)) {
  9865. return 1;
  9866. }
  9867. /* point entry in root table to sub-table */
  9868. low = huff & mask;
  9869. /*table.op[low] = curr;
  9870. table.bits[low] = root;
  9871. table.val[low] = next - opts.table_index;*/
  9872. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  9873. }
  9874. }
  9875. /* fill in remaining table entry if code is incomplete (guaranteed to have
  9876. at most one remaining entry, since if the code is incomplete, the
  9877. maximum code length that was allowed to get this far is one bit) */
  9878. if (huff !== 0) {
  9879. //table.op[next + huff] = 64; /* invalid code marker */
  9880. //table.bits[next + huff] = len - drop;
  9881. //table.val[next + huff] = 0;
  9882. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  9883. }
  9884. /* set return parameters */
  9885. //opts.table_index += used;
  9886. opts.bits = root;
  9887. return 0;
  9888. };
  9889. },{"../utils/common":27}],37:[function(require,module,exports){
  9890. 'use strict';
  9891. module.exports = {
  9892. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  9893. '1': 'stream end', /* Z_STREAM_END 1 */
  9894. '0': '', /* Z_OK 0 */
  9895. '-1': 'file error', /* Z_ERRNO (-1) */
  9896. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  9897. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  9898. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  9899. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  9900. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  9901. };
  9902. },{}],38:[function(require,module,exports){
  9903. 'use strict';
  9904. var utils = require('../utils/common');
  9905. /* Public constants ==========================================================*/
  9906. /* ===========================================================================*/
  9907. //var Z_FILTERED = 1;
  9908. //var Z_HUFFMAN_ONLY = 2;
  9909. //var Z_RLE = 3;
  9910. var Z_FIXED = 4;
  9911. //var Z_DEFAULT_STRATEGY = 0;
  9912. /* Possible values of the data_type field (though see inflate()) */
  9913. var Z_BINARY = 0;
  9914. var Z_TEXT = 1;
  9915. //var Z_ASCII = 1; // = Z_TEXT
  9916. var Z_UNKNOWN = 2;
  9917. /*============================================================================*/
  9918. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  9919. // From zutil.h
  9920. var STORED_BLOCK = 0;
  9921. var STATIC_TREES = 1;
  9922. var DYN_TREES = 2;
  9923. /* The three kinds of block type */
  9924. var MIN_MATCH = 3;
  9925. var MAX_MATCH = 258;
  9926. /* The minimum and maximum match lengths */
  9927. // From deflate.h
  9928. /* ===========================================================================
  9929. * Internal compression state.
  9930. */
  9931. var LENGTH_CODES = 29;
  9932. /* number of length codes, not counting the special END_BLOCK code */
  9933. var LITERALS = 256;
  9934. /* number of literal bytes 0..255 */
  9935. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  9936. /* number of Literal or Length codes, including the END_BLOCK code */
  9937. var D_CODES = 30;
  9938. /* number of distance codes */
  9939. var BL_CODES = 19;
  9940. /* number of codes used to transfer the bit lengths */
  9941. var HEAP_SIZE = 2*L_CODES + 1;
  9942. /* maximum heap size */
  9943. var MAX_BITS = 15;
  9944. /* All codes must not exceed MAX_BITS bits */
  9945. var Buf_size = 16;
  9946. /* size of bit buffer in bi_buf */
  9947. /* ===========================================================================
  9948. * Constants
  9949. */
  9950. var MAX_BL_BITS = 7;
  9951. /* Bit length codes must not exceed MAX_BL_BITS bits */
  9952. var END_BLOCK = 256;
  9953. /* end of block literal code */
  9954. var REP_3_6 = 16;
  9955. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  9956. var REPZ_3_10 = 17;
  9957. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  9958. var REPZ_11_138 = 18;
  9959. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  9960. var extra_lbits = /* extra bits for each length code */
  9961. [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
  9962. var extra_dbits = /* extra bits for each distance code */
  9963. [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
  9964. var extra_blbits = /* extra bits for each bit length code */
  9965. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  9966. var bl_order =
  9967. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  9968. /* The lengths of the bit length codes are sent in order of decreasing
  9969. * probability, to avoid transmitting the lengths for unused bit length codes.
  9970. */
  9971. /* ===========================================================================
  9972. * Local data. These are initialized only once.
  9973. */
  9974. // We pre-fill arrays with 0 to avoid uninitialized gaps
  9975. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  9976. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  9977. var static_ltree = new Array((L_CODES+2) * 2);
  9978. zero(static_ltree);
  9979. /* The static literal tree. Since the bit lengths are imposed, there is no
  9980. * need for the L_CODES extra codes used during heap construction. However
  9981. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  9982. * below).
  9983. */
  9984. var static_dtree = new Array(D_CODES * 2);
  9985. zero(static_dtree);
  9986. /* The static distance tree. (Actually a trivial tree since all codes use
  9987. * 5 bits.)
  9988. */
  9989. var _dist_code = new Array(DIST_CODE_LEN);
  9990. zero(_dist_code);
  9991. /* Distance codes. The first 256 values correspond to the distances
  9992. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  9993. * the 15 bit distances.
  9994. */
  9995. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  9996. zero(_length_code);
  9997. /* length code for each normalized match length (0 == MIN_MATCH) */
  9998. var base_length = new Array(LENGTH_CODES);
  9999. zero(base_length);
  10000. /* First normalized length for each code (0 = MIN_MATCH) */
  10001. var base_dist = new Array(D_CODES);
  10002. zero(base_dist);
  10003. /* First normalized distance for each code (0 = distance of 1) */
  10004. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  10005. this.static_tree = static_tree; /* static tree or NULL */
  10006. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  10007. this.extra_base = extra_base; /* base index for extra_bits */
  10008. this.elems = elems; /* max number of elements in the tree */
  10009. this.max_length = max_length; /* max bit length for the codes */
  10010. // show if `static_tree` has data or dummy - needed for monomorphic objects
  10011. this.has_stree = static_tree && static_tree.length;
  10012. };
  10013. var static_l_desc;
  10014. var static_d_desc;
  10015. var static_bl_desc;
  10016. var TreeDesc = function(dyn_tree, stat_desc) {
  10017. this.dyn_tree = dyn_tree; /* the dynamic tree */
  10018. this.max_code = 0; /* largest code with non zero frequency */
  10019. this.stat_desc = stat_desc; /* the corresponding static tree */
  10020. };
  10021. function d_code(dist) {
  10022. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  10023. }
  10024. /* ===========================================================================
  10025. * Output a short LSB first on the stream.
  10026. * IN assertion: there is enough room in pendingBuf.
  10027. */
  10028. function put_short (s, w) {
  10029. // put_byte(s, (uch)((w) & 0xff));
  10030. // put_byte(s, (uch)((ush)(w) >> 8));
  10031. s.pending_buf[s.pending++] = (w) & 0xff;
  10032. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  10033. }
  10034. /* ===========================================================================
  10035. * Send a value on a given number of bits.
  10036. * IN assertion: length <= 16 and value fits in length bits.
  10037. */
  10038. function send_bits(s, value, length) {
  10039. if (s.bi_valid > (Buf_size - length)) {
  10040. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  10041. put_short(s, s.bi_buf);
  10042. s.bi_buf = value >> (Buf_size - s.bi_valid);
  10043. s.bi_valid += length - Buf_size;
  10044. } else {
  10045. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  10046. s.bi_valid += length;
  10047. }
  10048. }
  10049. function send_code(s, c, tree) {
  10050. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  10051. }
  10052. /* ===========================================================================
  10053. * Reverse the first len bits of a code, using straightforward code (a faster
  10054. * method would use a table)
  10055. * IN assertion: 1 <= len <= 15
  10056. */
  10057. function bi_reverse(code, len) {
  10058. var res = 0;
  10059. do {
  10060. res |= code & 1;
  10061. code >>>= 1;
  10062. res <<= 1;
  10063. } while (--len > 0);
  10064. return res >>> 1;
  10065. }
  10066. /* ===========================================================================
  10067. * Flush the bit buffer, keeping at most 7 bits in it.
  10068. */
  10069. function bi_flush(s) {
  10070. if (s.bi_valid === 16) {
  10071. put_short(s, s.bi_buf);
  10072. s.bi_buf = 0;
  10073. s.bi_valid = 0;
  10074. } else if (s.bi_valid >= 8) {
  10075. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  10076. s.bi_buf >>= 8;
  10077. s.bi_valid -= 8;
  10078. }
  10079. }
  10080. /* ===========================================================================
  10081. * Compute the optimal bit lengths for a tree and update the total bit length
  10082. * for the current block.
  10083. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  10084. * above are the tree nodes sorted by increasing frequency.
  10085. * OUT assertions: the field len is set to the optimal bit length, the
  10086. * array bl_count contains the frequencies for each bit length.
  10087. * The length opt_len is updated; static_len is also updated if stree is
  10088. * not null.
  10089. */
  10090. function gen_bitlen(s, desc)
  10091. // deflate_state *s;
  10092. // tree_desc *desc; /* the tree descriptor */
  10093. {
  10094. var tree = desc.dyn_tree;
  10095. var max_code = desc.max_code;
  10096. var stree = desc.stat_desc.static_tree;
  10097. var has_stree = desc.stat_desc.has_stree;
  10098. var extra = desc.stat_desc.extra_bits;
  10099. var base = desc.stat_desc.extra_base;
  10100. var max_length = desc.stat_desc.max_length;
  10101. var h; /* heap index */
  10102. var n, m; /* iterate over the tree elements */
  10103. var bits; /* bit length */
  10104. var xbits; /* extra bits */
  10105. var f; /* frequency */
  10106. var overflow = 0; /* number of elements with bit length too large */
  10107. for (bits = 0; bits <= MAX_BITS; bits++) {
  10108. s.bl_count[bits] = 0;
  10109. }
  10110. /* In a first pass, compute the optimal bit lengths (which may
  10111. * overflow in the case of the bit length tree).
  10112. */
  10113. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  10114. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  10115. n = s.heap[h];
  10116. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  10117. if (bits > max_length) {
  10118. bits = max_length;
  10119. overflow++;
  10120. }
  10121. tree[n*2 + 1]/*.Len*/ = bits;
  10122. /* We overwrite tree[n].Dad which is no longer needed */
  10123. if (n > max_code) { continue; } /* not a leaf node */
  10124. s.bl_count[bits]++;
  10125. xbits = 0;
  10126. if (n >= base) {
  10127. xbits = extra[n-base];
  10128. }
  10129. f = tree[n * 2]/*.Freq*/;
  10130. s.opt_len += f * (bits + xbits);
  10131. if (has_stree) {
  10132. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  10133. }
  10134. }
  10135. if (overflow === 0) { return; }
  10136. // Trace((stderr,"\nbit length overflow\n"));
  10137. /* This happens for example on obj2 and pic of the Calgary corpus */
  10138. /* Find the first bit length which could increase: */
  10139. do {
  10140. bits = max_length-1;
  10141. while (s.bl_count[bits] === 0) { bits--; }
  10142. s.bl_count[bits]--; /* move one leaf down the tree */
  10143. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  10144. s.bl_count[max_length]--;
  10145. /* The brother of the overflow item also moves one step up,
  10146. * but this does not affect bl_count[max_length]
  10147. */
  10148. overflow -= 2;
  10149. } while (overflow > 0);
  10150. /* Now recompute all bit lengths, scanning in increasing frequency.
  10151. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  10152. * lengths instead of fixing only the wrong ones. This idea is taken
  10153. * from 'ar' written by Haruhiko Okumura.)
  10154. */
  10155. for (bits = max_length; bits !== 0; bits--) {
  10156. n = s.bl_count[bits];
  10157. while (n !== 0) {
  10158. m = s.heap[--h];
  10159. if (m > max_code) { continue; }
  10160. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  10161. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  10162. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  10163. tree[m*2 + 1]/*.Len*/ = bits;
  10164. }
  10165. n--;
  10166. }
  10167. }
  10168. }
  10169. /* ===========================================================================
  10170. * Generate the codes for a given tree and bit counts (which need not be
  10171. * optimal).
  10172. * IN assertion: the array bl_count contains the bit length statistics for
  10173. * the given tree and the field len is set for all tree elements.
  10174. * OUT assertion: the field code is set for all tree elements of non
  10175. * zero code length.
  10176. */
  10177. function gen_codes(tree, max_code, bl_count)
  10178. // ct_data *tree; /* the tree to decorate */
  10179. // int max_code; /* largest code with non zero frequency */
  10180. // ushf *bl_count; /* number of codes at each bit length */
  10181. {
  10182. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  10183. var code = 0; /* running code value */
  10184. var bits; /* bit index */
  10185. var n; /* code index */
  10186. /* The distribution counts are first used to generate the code values
  10187. * without bit reversal.
  10188. */
  10189. for (bits = 1; bits <= MAX_BITS; bits++) {
  10190. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  10191. }
  10192. /* Check that the bit counts in bl_count are consistent. The last code
  10193. * must be all ones.
  10194. */
  10195. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  10196. // "inconsistent bit counts");
  10197. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  10198. for (n = 0; n <= max_code; n++) {
  10199. var len = tree[n*2 + 1]/*.Len*/;
  10200. if (len === 0) { continue; }
  10201. /* Now reverse the bits */
  10202. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  10203. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  10204. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  10205. }
  10206. }
  10207. /* ===========================================================================
  10208. * Initialize the various 'constant' tables.
  10209. */
  10210. function tr_static_init() {
  10211. var n; /* iterates over tree elements */
  10212. var bits; /* bit counter */
  10213. var length; /* length value */
  10214. var code; /* code value */
  10215. var dist; /* distance index */
  10216. var bl_count = new Array(MAX_BITS+1);
  10217. /* number of codes at each bit length for an optimal tree */
  10218. // do check in _tr_init()
  10219. //if (static_init_done) return;
  10220. /* For some embedded targets, global variables are not initialized: */
  10221. /*#ifdef NO_INIT_GLOBAL_POINTERS
  10222. static_l_desc.static_tree = static_ltree;
  10223. static_l_desc.extra_bits = extra_lbits;
  10224. static_d_desc.static_tree = static_dtree;
  10225. static_d_desc.extra_bits = extra_dbits;
  10226. static_bl_desc.extra_bits = extra_blbits;
  10227. #endif*/
  10228. /* Initialize the mapping length (0..255) -> length code (0..28) */
  10229. length = 0;
  10230. for (code = 0; code < LENGTH_CODES-1; code++) {
  10231. base_length[code] = length;
  10232. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  10233. _length_code[length++] = code;
  10234. }
  10235. }
  10236. //Assert (length == 256, "tr_static_init: length != 256");
  10237. /* Note that the length 255 (match length 258) can be represented
  10238. * in two different ways: code 284 + 5 bits or code 285, so we
  10239. * overwrite length_code[255] to use the best encoding:
  10240. */
  10241. _length_code[length-1] = code;
  10242. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  10243. dist = 0;
  10244. for (code = 0 ; code < 16; code++) {
  10245. base_dist[code] = dist;
  10246. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  10247. _dist_code[dist++] = code;
  10248. }
  10249. }
  10250. //Assert (dist == 256, "tr_static_init: dist != 256");
  10251. dist >>= 7; /* from now on, all distances are divided by 128 */
  10252. for (; code < D_CODES; code++) {
  10253. base_dist[code] = dist << 7;
  10254. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  10255. _dist_code[256 + dist++] = code;
  10256. }
  10257. }
  10258. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  10259. /* Construct the codes of the static literal tree */
  10260. for (bits = 0; bits <= MAX_BITS; bits++) {
  10261. bl_count[bits] = 0;
  10262. }
  10263. n = 0;
  10264. while (n <= 143) {
  10265. static_ltree[n*2 + 1]/*.Len*/ = 8;
  10266. n++;
  10267. bl_count[8]++;
  10268. }
  10269. while (n <= 255) {
  10270. static_ltree[n*2 + 1]/*.Len*/ = 9;
  10271. n++;
  10272. bl_count[9]++;
  10273. }
  10274. while (n <= 279) {
  10275. static_ltree[n*2 + 1]/*.Len*/ = 7;
  10276. n++;
  10277. bl_count[7]++;
  10278. }
  10279. while (n <= 287) {
  10280. static_ltree[n*2 + 1]/*.Len*/ = 8;
  10281. n++;
  10282. bl_count[8]++;
  10283. }
  10284. /* Codes 286 and 287 do not exist, but we must include them in the
  10285. * tree construction to get a canonical Huffman tree (longest code
  10286. * all ones)
  10287. */
  10288. gen_codes(static_ltree, L_CODES+1, bl_count);
  10289. /* The static distance tree is trivial: */
  10290. for (n = 0; n < D_CODES; n++) {
  10291. static_dtree[n*2 + 1]/*.Len*/ = 5;
  10292. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  10293. }
  10294. // Now data ready and we can init static trees
  10295. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  10296. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  10297. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  10298. //static_init_done = true;
  10299. }
  10300. /* ===========================================================================
  10301. * Initialize a new block.
  10302. */
  10303. function init_block(s) {
  10304. var n; /* iterates over tree elements */
  10305. /* Initialize the trees. */
  10306. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  10307. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  10308. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  10309. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  10310. s.opt_len = s.static_len = 0;
  10311. s.last_lit = s.matches = 0;
  10312. }
  10313. /* ===========================================================================
  10314. * Flush the bit buffer and align the output on a byte boundary
  10315. */
  10316. function bi_windup(s)
  10317. {
  10318. if (s.bi_valid > 8) {
  10319. put_short(s, s.bi_buf);
  10320. } else if (s.bi_valid > 0) {
  10321. //put_byte(s, (Byte)s->bi_buf);
  10322. s.pending_buf[s.pending++] = s.bi_buf;
  10323. }
  10324. s.bi_buf = 0;
  10325. s.bi_valid = 0;
  10326. }
  10327. /* ===========================================================================
  10328. * Copy a stored block, storing first the length and its
  10329. * one's complement if requested.
  10330. */
  10331. function copy_block(s, buf, len, header)
  10332. //DeflateState *s;
  10333. //charf *buf; /* the input data */
  10334. //unsigned len; /* its length */
  10335. //int header; /* true if block header must be written */
  10336. {
  10337. bi_windup(s); /* align on byte boundary */
  10338. if (header) {
  10339. put_short(s, len);
  10340. put_short(s, ~len);
  10341. }
  10342. // while (len--) {
  10343. // put_byte(s, *buf++);
  10344. // }
  10345. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  10346. s.pending += len;
  10347. }
  10348. /* ===========================================================================
  10349. * Compares to subtrees, using the tree depth as tie breaker when
  10350. * the subtrees have equal frequency. This minimizes the worst case length.
  10351. */
  10352. function smaller(tree, n, m, depth) {
  10353. var _n2 = n*2;
  10354. var _m2 = m*2;
  10355. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  10356. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  10357. }
  10358. /* ===========================================================================
  10359. * Restore the heap property by moving down the tree starting at node k,
  10360. * exchanging a node with the smallest of its two sons if necessary, stopping
  10361. * when the heap property is re-established (each father smaller than its
  10362. * two sons).
  10363. */
  10364. function pqdownheap(s, tree, k)
  10365. // deflate_state *s;
  10366. // ct_data *tree; /* the tree to restore */
  10367. // int k; /* node to move down */
  10368. {
  10369. var v = s.heap[k];
  10370. var j = k << 1; /* left son of k */
  10371. while (j <= s.heap_len) {
  10372. /* Set j to the smallest of the two sons: */
  10373. if (j < s.heap_len &&
  10374. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  10375. j++;
  10376. }
  10377. /* Exit if v is smaller than both sons */
  10378. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  10379. /* Exchange v with the smallest son */
  10380. s.heap[k] = s.heap[j];
  10381. k = j;
  10382. /* And continue down the tree, setting j to the left son of k */
  10383. j <<= 1;
  10384. }
  10385. s.heap[k] = v;
  10386. }
  10387. // inlined manually
  10388. // var SMALLEST = 1;
  10389. /* ===========================================================================
  10390. * Send the block data compressed using the given Huffman trees
  10391. */
  10392. function compress_block(s, ltree, dtree)
  10393. // deflate_state *s;
  10394. // const ct_data *ltree; /* literal tree */
  10395. // const ct_data *dtree; /* distance tree */
  10396. {
  10397. var dist; /* distance of matched string */
  10398. var lc; /* match length or unmatched char (if dist == 0) */
  10399. var lx = 0; /* running index in l_buf */
  10400. var code; /* the code to send */
  10401. var extra; /* number of extra bits to send */
  10402. if (s.last_lit !== 0) {
  10403. do {
  10404. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  10405. lc = s.pending_buf[s.l_buf + lx];
  10406. lx++;
  10407. if (dist === 0) {
  10408. send_code(s, lc, ltree); /* send a literal byte */
  10409. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  10410. } else {
  10411. /* Here, lc is the match length - MIN_MATCH */
  10412. code = _length_code[lc];
  10413. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  10414. extra = extra_lbits[code];
  10415. if (extra !== 0) {
  10416. lc -= base_length[code];
  10417. send_bits(s, lc, extra); /* send the extra length bits */
  10418. }
  10419. dist--; /* dist is now the match distance - 1 */
  10420. code = d_code(dist);
  10421. //Assert (code < D_CODES, "bad d_code");
  10422. send_code(s, code, dtree); /* send the distance code */
  10423. extra = extra_dbits[code];
  10424. if (extra !== 0) {
  10425. dist -= base_dist[code];
  10426. send_bits(s, dist, extra); /* send the extra distance bits */
  10427. }
  10428. } /* literal or match pair ? */
  10429. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  10430. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  10431. // "pendingBuf overflow");
  10432. } while (lx < s.last_lit);
  10433. }
  10434. send_code(s, END_BLOCK, ltree);
  10435. }
  10436. /* ===========================================================================
  10437. * Construct one Huffman tree and assigns the code bit strings and lengths.
  10438. * Update the total bit length for the current block.
  10439. * IN assertion: the field freq is set for all tree elements.
  10440. * OUT assertions: the fields len and code are set to the optimal bit length
  10441. * and corresponding code. The length opt_len is updated; static_len is
  10442. * also updated if stree is not null. The field max_code is set.
  10443. */
  10444. function build_tree(s, desc)
  10445. // deflate_state *s;
  10446. // tree_desc *desc; /* the tree descriptor */
  10447. {
  10448. var tree = desc.dyn_tree;
  10449. var stree = desc.stat_desc.static_tree;
  10450. var has_stree = desc.stat_desc.has_stree;
  10451. var elems = desc.stat_desc.elems;
  10452. var n, m; /* iterate over heap elements */
  10453. var max_code = -1; /* largest code with non zero frequency */
  10454. var node; /* new node being created */
  10455. /* Construct the initial heap, with least frequent element in
  10456. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  10457. * heap[0] is not used.
  10458. */
  10459. s.heap_len = 0;
  10460. s.heap_max = HEAP_SIZE;
  10461. for (n = 0; n < elems; n++) {
  10462. if (tree[n * 2]/*.Freq*/ !== 0) {
  10463. s.heap[++s.heap_len] = max_code = n;
  10464. s.depth[n] = 0;
  10465. } else {
  10466. tree[n*2 + 1]/*.Len*/ = 0;
  10467. }
  10468. }
  10469. /* The pkzip format requires that at least one distance code exists,
  10470. * and that at least one bit should be sent even if there is only one
  10471. * possible code. So to avoid special checks later on we force at least
  10472. * two codes of non zero frequency.
  10473. */
  10474. while (s.heap_len < 2) {
  10475. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  10476. tree[node * 2]/*.Freq*/ = 1;
  10477. s.depth[node] = 0;
  10478. s.opt_len--;
  10479. if (has_stree) {
  10480. s.static_len -= stree[node*2 + 1]/*.Len*/;
  10481. }
  10482. /* node is 0 or 1 so it does not have extra bits */
  10483. }
  10484. desc.max_code = max_code;
  10485. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  10486. * establish sub-heaps of increasing lengths:
  10487. */
  10488. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  10489. /* Construct the Huffman tree by repeatedly combining the least two
  10490. * frequent nodes.
  10491. */
  10492. node = elems; /* next internal node of the tree */
  10493. do {
  10494. //pqremove(s, tree, n); /* n = node of least frequency */
  10495. /*** pqremove ***/
  10496. n = s.heap[1/*SMALLEST*/];
  10497. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  10498. pqdownheap(s, tree, 1/*SMALLEST*/);
  10499. /***/
  10500. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  10501. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  10502. s.heap[--s.heap_max] = m;
  10503. /* Create a new node father of n and m */
  10504. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  10505. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  10506. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  10507. /* and insert the new node in the heap */
  10508. s.heap[1/*SMALLEST*/] = node++;
  10509. pqdownheap(s, tree, 1/*SMALLEST*/);
  10510. } while (s.heap_len >= 2);
  10511. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  10512. /* At this point, the fields freq and dad are set. We can now
  10513. * generate the bit lengths.
  10514. */
  10515. gen_bitlen(s, desc);
  10516. /* The field len is now set, we can generate the bit codes */
  10517. gen_codes(tree, max_code, s.bl_count);
  10518. }
  10519. /* ===========================================================================
  10520. * Scan a literal or distance tree to determine the frequencies of the codes
  10521. * in the bit length tree.
  10522. */
  10523. function scan_tree(s, tree, max_code)
  10524. // deflate_state *s;
  10525. // ct_data *tree; /* the tree to be scanned */
  10526. // int max_code; /* and its largest code of non zero frequency */
  10527. {
  10528. var n; /* iterates over all tree elements */
  10529. var prevlen = -1; /* last emitted length */
  10530. var curlen; /* length of current code */
  10531. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  10532. var count = 0; /* repeat count of the current code */
  10533. var max_count = 7; /* max repeat count */
  10534. var min_count = 4; /* min repeat count */
  10535. if (nextlen === 0) {
  10536. max_count = 138;
  10537. min_count = 3;
  10538. }
  10539. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  10540. for (n = 0; n <= max_code; n++) {
  10541. curlen = nextlen;
  10542. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  10543. if (++count < max_count && curlen === nextlen) {
  10544. continue;
  10545. } else if (count < min_count) {
  10546. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  10547. } else if (curlen !== 0) {
  10548. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  10549. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  10550. } else if (count <= 10) {
  10551. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  10552. } else {
  10553. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  10554. }
  10555. count = 0;
  10556. prevlen = curlen;
  10557. if (nextlen === 0) {
  10558. max_count = 138;
  10559. min_count = 3;
  10560. } else if (curlen === nextlen) {
  10561. max_count = 6;
  10562. min_count = 3;
  10563. } else {
  10564. max_count = 7;
  10565. min_count = 4;
  10566. }
  10567. }
  10568. }
  10569. /* ===========================================================================
  10570. * Send a literal or distance tree in compressed form, using the codes in
  10571. * bl_tree.
  10572. */
  10573. function send_tree(s, tree, max_code)
  10574. // deflate_state *s;
  10575. // ct_data *tree; /* the tree to be scanned */
  10576. // int max_code; /* and its largest code of non zero frequency */
  10577. {
  10578. var n; /* iterates over all tree elements */
  10579. var prevlen = -1; /* last emitted length */
  10580. var curlen; /* length of current code */
  10581. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  10582. var count = 0; /* repeat count of the current code */
  10583. var max_count = 7; /* max repeat count */
  10584. var min_count = 4; /* min repeat count */
  10585. /* tree[max_code+1].Len = -1; */ /* guard already set */
  10586. if (nextlen === 0) {
  10587. max_count = 138;
  10588. min_count = 3;
  10589. }
  10590. for (n = 0; n <= max_code; n++) {
  10591. curlen = nextlen;
  10592. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  10593. if (++count < max_count && curlen === nextlen) {
  10594. continue;
  10595. } else if (count < min_count) {
  10596. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  10597. } else if (curlen !== 0) {
  10598. if (curlen !== prevlen) {
  10599. send_code(s, curlen, s.bl_tree);
  10600. count--;
  10601. }
  10602. //Assert(count >= 3 && count <= 6, " 3_6?");
  10603. send_code(s, REP_3_6, s.bl_tree);
  10604. send_bits(s, count-3, 2);
  10605. } else if (count <= 10) {
  10606. send_code(s, REPZ_3_10, s.bl_tree);
  10607. send_bits(s, count-3, 3);
  10608. } else {
  10609. send_code(s, REPZ_11_138, s.bl_tree);
  10610. send_bits(s, count-11, 7);
  10611. }
  10612. count = 0;
  10613. prevlen = curlen;
  10614. if (nextlen === 0) {
  10615. max_count = 138;
  10616. min_count = 3;
  10617. } else if (curlen === nextlen) {
  10618. max_count = 6;
  10619. min_count = 3;
  10620. } else {
  10621. max_count = 7;
  10622. min_count = 4;
  10623. }
  10624. }
  10625. }
  10626. /* ===========================================================================
  10627. * Construct the Huffman tree for the bit lengths and return the index in
  10628. * bl_order of the last bit length code to send.
  10629. */
  10630. function build_bl_tree(s) {
  10631. var max_blindex; /* index of last bit length code of non zero freq */
  10632. /* Determine the bit length frequencies for literal and distance trees */
  10633. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  10634. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  10635. /* Build the bit length tree: */
  10636. build_tree(s, s.bl_desc);
  10637. /* opt_len now includes the length of the tree representations, except
  10638. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  10639. */
  10640. /* Determine the number of bit length codes to send. The pkzip format
  10641. * requires that at least 4 bit length codes be sent. (appnote.txt says
  10642. * 3 but the actual value used is 4.)
  10643. */
  10644. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  10645. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  10646. break;
  10647. }
  10648. }
  10649. /* Update opt_len to include the bit length tree and counts */
  10650. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  10651. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  10652. // s->opt_len, s->static_len));
  10653. return max_blindex;
  10654. }
  10655. /* ===========================================================================
  10656. * Send the header for a block using dynamic Huffman trees: the counts, the
  10657. * lengths of the bit length codes, the literal tree and the distance tree.
  10658. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  10659. */
  10660. function send_all_trees(s, lcodes, dcodes, blcodes)
  10661. // deflate_state *s;
  10662. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  10663. {
  10664. var rank; /* index in bl_order */
  10665. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  10666. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  10667. // "too many codes");
  10668. //Tracev((stderr, "\nbl counts: "));
  10669. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  10670. send_bits(s, dcodes-1, 5);
  10671. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  10672. for (rank = 0; rank < blcodes; rank++) {
  10673. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  10674. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  10675. }
  10676. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  10677. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  10678. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  10679. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  10680. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  10681. }
  10682. /* ===========================================================================
  10683. * Check if the data type is TEXT or BINARY, using the following algorithm:
  10684. * - TEXT if the two conditions below are satisfied:
  10685. * a) There are no non-portable control characters belonging to the
  10686. * "black list" (0..6, 14..25, 28..31).
  10687. * b) There is at least one printable character belonging to the
  10688. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  10689. * - BINARY otherwise.
  10690. * - The following partially-portable control characters form a
  10691. * "gray list" that is ignored in this detection algorithm:
  10692. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  10693. * IN assertion: the fields Freq of dyn_ltree are set.
  10694. */
  10695. function detect_data_type(s) {
  10696. /* black_mask is the bit mask of black-listed bytes
  10697. * set bits 0..6, 14..25, and 28..31
  10698. * 0xf3ffc07f = binary 11110011111111111100000001111111
  10699. */
  10700. var black_mask = 0xf3ffc07f;
  10701. var n;
  10702. /* Check for non-textual ("black-listed") bytes. */
  10703. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  10704. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  10705. return Z_BINARY;
  10706. }
  10707. }
  10708. /* Check for textual ("white-listed") bytes. */
  10709. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  10710. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  10711. return Z_TEXT;
  10712. }
  10713. for (n = 32; n < LITERALS; n++) {
  10714. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  10715. return Z_TEXT;
  10716. }
  10717. }
  10718. /* There are no "black-listed" or "white-listed" bytes:
  10719. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  10720. */
  10721. return Z_BINARY;
  10722. }
  10723. var static_init_done = false;
  10724. /* ===========================================================================
  10725. * Initialize the tree data structures for a new zlib stream.
  10726. */
  10727. function _tr_init(s)
  10728. {
  10729. if (!static_init_done) {
  10730. tr_static_init();
  10731. static_init_done = true;
  10732. }
  10733. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  10734. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  10735. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  10736. s.bi_buf = 0;
  10737. s.bi_valid = 0;
  10738. /* Initialize the first block of the first file: */
  10739. init_block(s);
  10740. }
  10741. /* ===========================================================================
  10742. * Send a stored block
  10743. */
  10744. function _tr_stored_block(s, buf, stored_len, last)
  10745. //DeflateState *s;
  10746. //charf *buf; /* input block */
  10747. //ulg stored_len; /* length of input block */
  10748. //int last; /* one if this is the last block for a file */
  10749. {
  10750. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  10751. copy_block(s, buf, stored_len, true); /* with header */
  10752. }
  10753. /* ===========================================================================
  10754. * Send one empty static block to give enough lookahead for inflate.
  10755. * This takes 10 bits, of which 7 may remain in the bit buffer.
  10756. */
  10757. function _tr_align(s) {
  10758. send_bits(s, STATIC_TREES<<1, 3);
  10759. send_code(s, END_BLOCK, static_ltree);
  10760. bi_flush(s);
  10761. }
  10762. /* ===========================================================================
  10763. * Determine the best encoding for the current block: dynamic trees, static
  10764. * trees or store, and output the encoded block to the zip file.
  10765. */
  10766. function _tr_flush_block(s, buf, stored_len, last)
  10767. //DeflateState *s;
  10768. //charf *buf; /* input block, or NULL if too old */
  10769. //ulg stored_len; /* length of input block */
  10770. //int last; /* one if this is the last block for a file */
  10771. {
  10772. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  10773. var max_blindex = 0; /* index of last bit length code of non zero freq */
  10774. /* Build the Huffman trees unless a stored block is forced */
  10775. if (s.level > 0) {
  10776. /* Check if the file is binary or text */
  10777. if (s.strm.data_type === Z_UNKNOWN) {
  10778. s.strm.data_type = detect_data_type(s);
  10779. }
  10780. /* Construct the literal and distance trees */
  10781. build_tree(s, s.l_desc);
  10782. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  10783. // s->static_len));
  10784. build_tree(s, s.d_desc);
  10785. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  10786. // s->static_len));
  10787. /* At this point, opt_len and static_len are the total bit lengths of
  10788. * the compressed block data, excluding the tree representations.
  10789. */
  10790. /* Build the bit length tree for the above two trees, and get the index
  10791. * in bl_order of the last bit length code to send.
  10792. */
  10793. max_blindex = build_bl_tree(s);
  10794. /* Determine the best encoding. Compute the block lengths in bytes. */
  10795. opt_lenb = (s.opt_len+3+7) >>> 3;
  10796. static_lenb = (s.static_len+3+7) >>> 3;
  10797. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  10798. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  10799. // s->last_lit));
  10800. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  10801. } else {
  10802. // Assert(buf != (char*)0, "lost buf");
  10803. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  10804. }
  10805. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  10806. /* 4: two words for the lengths */
  10807. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  10808. * Otherwise we can't have processed more than WSIZE input bytes since
  10809. * the last block flush, because compression would have been
  10810. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  10811. * transform a block into a stored block.
  10812. */
  10813. _tr_stored_block(s, buf, stored_len, last);
  10814. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  10815. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  10816. compress_block(s, static_ltree, static_dtree);
  10817. } else {
  10818. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  10819. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  10820. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  10821. }
  10822. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  10823. /* The above check is made mod 2^32, for files larger than 512 MB
  10824. * and uLong implemented on 32 bits.
  10825. */
  10826. init_block(s);
  10827. if (last) {
  10828. bi_windup(s);
  10829. }
  10830. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  10831. // s->compressed_len-7*last));
  10832. }
  10833. /* ===========================================================================
  10834. * Save the match info and tally the frequency counts. Return true if
  10835. * the current block must be flushed.
  10836. */
  10837. function _tr_tally(s, dist, lc)
  10838. // deflate_state *s;
  10839. // unsigned dist; /* distance of matched string */
  10840. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  10841. {
  10842. //var out_length, in_length, dcode;
  10843. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  10844. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  10845. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  10846. s.last_lit++;
  10847. if (dist === 0) {
  10848. /* lc is the unmatched char */
  10849. s.dyn_ltree[lc*2]/*.Freq*/++;
  10850. } else {
  10851. s.matches++;
  10852. /* Here, lc is the match length - MIN_MATCH */
  10853. dist--; /* dist = match distance - 1 */
  10854. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  10855. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  10856. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  10857. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  10858. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  10859. }
  10860. // (!) This block is disabled in zlib defailts,
  10861. // don't enable it for binary compatibility
  10862. //#ifdef TRUNCATE_BLOCK
  10863. // /* Try to guess if it is profitable to stop the current block here */
  10864. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  10865. // /* Compute an upper bound for the compressed length */
  10866. // out_length = s.last_lit*8;
  10867. // in_length = s.strstart - s.block_start;
  10868. //
  10869. // for (dcode = 0; dcode < D_CODES; dcode++) {
  10870. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  10871. // }
  10872. // out_length >>>= 3;
  10873. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  10874. // // s->last_lit, in_length, out_length,
  10875. // // 100L - out_length*100L/in_length));
  10876. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  10877. // return true;
  10878. // }
  10879. // }
  10880. //#endif
  10881. return (s.last_lit === s.lit_bufsize-1);
  10882. /* We avoid equality with lit_bufsize because of wraparound at 64K
  10883. * on 16 bit machines and because stored blocks are restricted to
  10884. * 64K-1 bytes.
  10885. */
  10886. }
  10887. exports._tr_init = _tr_init;
  10888. exports._tr_stored_block = _tr_stored_block;
  10889. exports._tr_flush_block = _tr_flush_block;
  10890. exports._tr_tally = _tr_tally;
  10891. exports._tr_align = _tr_align;
  10892. },{"../utils/common":27}],39:[function(require,module,exports){
  10893. 'use strict';
  10894. function ZStream() {
  10895. /* next input byte */
  10896. this.input = null; // JS specific, because we have no pointers
  10897. this.next_in = 0;
  10898. /* number of bytes available at input */
  10899. this.avail_in = 0;
  10900. /* total number of input bytes read so far */
  10901. this.total_in = 0;
  10902. /* next output byte should be put there */
  10903. this.output = null; // JS specific, because we have no pointers
  10904. this.next_out = 0;
  10905. /* remaining free space at output */
  10906. this.avail_out = 0;
  10907. /* total number of bytes output so far */
  10908. this.total_out = 0;
  10909. /* last error message, NULL if no error */
  10910. this.msg = ''/*Z_NULL*/;
  10911. /* not visible by applications */
  10912. this.state = null;
  10913. /* best guess about the data type: binary or text */
  10914. this.data_type = 2/*Z_UNKNOWN*/;
  10915. /* adler32 value of the uncompressed data */
  10916. this.adler = 0;
  10917. }
  10918. module.exports = ZStream;
  10919. },{}],40:[function(require,module,exports){
  10920. var MediaStreamType = {
  10921. VIDEO_TYPE: "Video",
  10922. AUDIO_TYPE: "Audio"
  10923. };
  10924. module.exports = MediaStreamType;
  10925. },{}],41:[function(require,module,exports){
  10926. var RTCEvents = {
  10927. RTC_READY: "rtc.ready",
  10928. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  10929. LASTN_CHANGED: "rtc.lastn_changed",
  10930. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  10931. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  10932. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  10933. AUDIO_MUTE: "rtc.audio_mute",
  10934. VIDEO_MUTE: "rtc.video_mute"
  10935. };
  10936. module.exports = RTCEvents;
  10937. },{}],42:[function(require,module,exports){
  10938. var Resolutions = {
  10939. "1080": {
  10940. width: 1920,
  10941. height: 1080,
  10942. order: 7
  10943. },
  10944. "fullhd": {
  10945. width: 1920,
  10946. height: 1080,
  10947. order: 7
  10948. },
  10949. "720": {
  10950. width: 1280,
  10951. height: 720,
  10952. order: 6
  10953. },
  10954. "hd": {
  10955. width: 1280,
  10956. height: 720,
  10957. order: 6
  10958. },
  10959. "960": {
  10960. width: 960,
  10961. height: 720,
  10962. order: 5
  10963. },
  10964. "640": {
  10965. width: 640,
  10966. height: 480,
  10967. order: 4
  10968. },
  10969. "vga": {
  10970. width: 640,
  10971. height: 480,
  10972. order: 4
  10973. },
  10974. "360": {
  10975. width: 640,
  10976. height: 360,
  10977. order: 3
  10978. },
  10979. "320": {
  10980. width: 320,
  10981. height: 240,
  10982. order: 2
  10983. },
  10984. "180": {
  10985. width: 320,
  10986. height: 180,
  10987. order: 1
  10988. }
  10989. };
  10990. module.exports = Resolutions;
  10991. },{}],43:[function(require,module,exports){
  10992. var StreamEventTypes = {
  10993. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  10994. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  10995. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  10996. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  10997. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  10998. };
  10999. module.exports = StreamEventTypes;
  11000. },{}],44:[function(require,module,exports){
  11001. var UIEvents = {
  11002. NICKNAME_CHANGED: "UI.nickname_changed",
  11003. SELECTED_ENDPOINT: "UI.selected_endpoint",
  11004. PINNED_ENDPOINT: "UI.pinned_endpoint",
  11005. LARGEVIDEO_INIT: "UI.largevideo_init"
  11006. };
  11007. module.exports = UIEvents;
  11008. },{}],45:[function(require,module,exports){
  11009. var AuthenticationEvents = {
  11010. /**
  11011. * Event callback arguments:
  11012. * function(authenticationEnabled, userIdentity)
  11013. * authenticationEnabled - indicates whether authentication has been enabled
  11014. * in this session
  11015. * userIdentity - if user has been logged in then it contains user name. If
  11016. * contains 'null' or 'undefined' then user is not logged in.
  11017. */
  11018. IDENTITY_UPDATED: "authentication.identity_updated"
  11019. };
  11020. module.exports = AuthenticationEvents;
  11021. },{}],46:[function(require,module,exports){
  11022. var DesktopSharingEventTypes = {
  11023. INIT: "ds.init",
  11024. SWITCHING_DONE: "ds.switching_done",
  11025. NEW_STREAM_CREATED: "ds.new_stream_created"
  11026. };
  11027. module.exports = DesktopSharingEventTypes;
  11028. },{}],47:[function(require,module,exports){
  11029. var XMPPEvents = {
  11030. CONNECTION_FAILED: "xmpp.connection.failed",
  11031. // Indicates an interrupted connection event.
  11032. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  11033. // Indicates a restored connection event.
  11034. CONNECTION_RESTORED: "xmpp.connection.restored",
  11035. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  11036. CALL_INCOMING: "xmpp.callincoming.jingle",
  11037. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  11038. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  11039. KICKED: "xmpp.kicked",
  11040. BRIDGE_DOWN: "xmpp.bridge_down",
  11041. USER_ID_CHANGED: "xmpp.user_id_changed",
  11042. // We joined the MUC
  11043. MUC_JOINED: "xmpp.muc_joined",
  11044. // A member joined the MUC
  11045. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  11046. // A member left the MUC
  11047. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  11048. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  11049. MUC_DESTROYED: "xmpp.muc_destroyed",
  11050. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  11051. REMOTE_STATS: "xmpp.remote_stats",
  11052. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  11053. PRESENCE_STATUS: "xmpp.presence_status",
  11054. RESERVATION_ERROR: "xmpp.room_reservation_error",
  11055. SUBJECT_CHANGED: "xmpp.subject_changed",
  11056. MESSAGE_RECEIVED: "xmpp.message_received",
  11057. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  11058. PASSWORD_REQUIRED: "xmpp.password_required",
  11059. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  11060. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  11061. ETHERPAD: "xmpp.etherpad",
  11062. DEVICE_AVAILABLE: "xmpp.device_available",
  11063. VIDEO_TYPE: "xmpp.video_type",
  11064. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  11065. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  11066. AUDIO_MUTED: "xmpp.audio_muted",
  11067. VIDEO_MUTED: "xmpp.video_muted",
  11068. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  11069. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  11070. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  11071. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  11072. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  11073. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  11074. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  11075. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  11076. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  11077. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  11078. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  11079. // xmpp is connected and obtained user media
  11080. READY_TO_JOIN: 'xmpp.ready_to_join'
  11081. };
  11082. module.exports = XMPPEvents;
  11083. },{}],48:[function(require,module,exports){
  11084. // Copyright Joyent, Inc. and other Node contributors.
  11085. //
  11086. // Permission is hereby granted, free of charge, to any person obtaining a
  11087. // copy of this software and associated documentation files (the
  11088. // "Software"), to deal in the Software without restriction, including
  11089. // without limitation the rights to use, copy, modify, merge, publish,
  11090. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11091. // persons to whom the Software is furnished to do so, subject to the
  11092. // following conditions:
  11093. //
  11094. // The above copyright notice and this permission notice shall be included
  11095. // in all copies or substantial portions of the Software.
  11096. //
  11097. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11098. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11099. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11100. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11101. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11102. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11103. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11104. function EventEmitter() {
  11105. this._events = this._events || {};
  11106. this._maxListeners = this._maxListeners || undefined;
  11107. }
  11108. module.exports = EventEmitter;
  11109. // Backwards-compat with node 0.10.x
  11110. EventEmitter.EventEmitter = EventEmitter;
  11111. EventEmitter.prototype._events = undefined;
  11112. EventEmitter.prototype._maxListeners = undefined;
  11113. // By default EventEmitters will print a warning if more than 10 listeners are
  11114. // added to it. This is a useful default which helps finding memory leaks.
  11115. EventEmitter.defaultMaxListeners = 10;
  11116. // Obviously not all Emitters should be limited to 10. This function allows
  11117. // that to be increased. Set to zero for unlimited.
  11118. EventEmitter.prototype.setMaxListeners = function(n) {
  11119. if (!isNumber(n) || n < 0 || isNaN(n))
  11120. throw TypeError('n must be a positive number');
  11121. this._maxListeners = n;
  11122. return this;
  11123. };
  11124. EventEmitter.prototype.emit = function(type) {
  11125. var er, handler, len, args, i, listeners;
  11126. if (!this._events)
  11127. this._events = {};
  11128. // If there is no 'error' event listener then throw.
  11129. if (type === 'error') {
  11130. if (!this._events.error ||
  11131. (isObject(this._events.error) && !this._events.error.length)) {
  11132. er = arguments[1];
  11133. if (er instanceof Error) {
  11134. throw er; // Unhandled 'error' event
  11135. }
  11136. throw TypeError('Uncaught, unspecified "error" event.');
  11137. }
  11138. }
  11139. handler = this._events[type];
  11140. if (isUndefined(handler))
  11141. return false;
  11142. if (isFunction(handler)) {
  11143. switch (arguments.length) {
  11144. // fast cases
  11145. case 1:
  11146. handler.call(this);
  11147. break;
  11148. case 2:
  11149. handler.call(this, arguments[1]);
  11150. break;
  11151. case 3:
  11152. handler.call(this, arguments[1], arguments[2]);
  11153. break;
  11154. // slower
  11155. default:
  11156. len = arguments.length;
  11157. args = new Array(len - 1);
  11158. for (i = 1; i < len; i++)
  11159. args[i - 1] = arguments[i];
  11160. handler.apply(this, args);
  11161. }
  11162. } else if (isObject(handler)) {
  11163. len = arguments.length;
  11164. args = new Array(len - 1);
  11165. for (i = 1; i < len; i++)
  11166. args[i - 1] = arguments[i];
  11167. listeners = handler.slice();
  11168. len = listeners.length;
  11169. for (i = 0; i < len; i++)
  11170. listeners[i].apply(this, args);
  11171. }
  11172. return true;
  11173. };
  11174. EventEmitter.prototype.addListener = function(type, listener) {
  11175. var m;
  11176. if (!isFunction(listener))
  11177. throw TypeError('listener must be a function');
  11178. if (!this._events)
  11179. this._events = {};
  11180. // To avoid recursion in the case that type === "newListener"! Before
  11181. // adding it to the listeners, first emit "newListener".
  11182. if (this._events.newListener)
  11183. this.emit('newListener', type,
  11184. isFunction(listener.listener) ?
  11185. listener.listener : listener);
  11186. if (!this._events[type])
  11187. // Optimize the case of one listener. Don't need the extra array object.
  11188. this._events[type] = listener;
  11189. else if (isObject(this._events[type]))
  11190. // If we've already got an array, just append.
  11191. this._events[type].push(listener);
  11192. else
  11193. // Adding the second element, need to change to array.
  11194. this._events[type] = [this._events[type], listener];
  11195. // Check for listener leak
  11196. if (isObject(this._events[type]) && !this._events[type].warned) {
  11197. var m;
  11198. if (!isUndefined(this._maxListeners)) {
  11199. m = this._maxListeners;
  11200. } else {
  11201. m = EventEmitter.defaultMaxListeners;
  11202. }
  11203. if (m && m > 0 && this._events[type].length > m) {
  11204. this._events[type].warned = true;
  11205. console.error('(node) warning: possible EventEmitter memory ' +
  11206. 'leak detected. %d listeners added. ' +
  11207. 'Use emitter.setMaxListeners() to increase limit.',
  11208. this._events[type].length);
  11209. if (typeof console.trace === 'function') {
  11210. // not supported in IE 10
  11211. console.trace();
  11212. }
  11213. }
  11214. }
  11215. return this;
  11216. };
  11217. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  11218. EventEmitter.prototype.once = function(type, listener) {
  11219. if (!isFunction(listener))
  11220. throw TypeError('listener must be a function');
  11221. var fired = false;
  11222. function g() {
  11223. this.removeListener(type, g);
  11224. if (!fired) {
  11225. fired = true;
  11226. listener.apply(this, arguments);
  11227. }
  11228. }
  11229. g.listener = listener;
  11230. this.on(type, g);
  11231. return this;
  11232. };
  11233. // emits a 'removeListener' event iff the listener was removed
  11234. EventEmitter.prototype.removeListener = function(type, listener) {
  11235. var list, position, length, i;
  11236. if (!isFunction(listener))
  11237. throw TypeError('listener must be a function');
  11238. if (!this._events || !this._events[type])
  11239. return this;
  11240. list = this._events[type];
  11241. length = list.length;
  11242. position = -1;
  11243. if (list === listener ||
  11244. (isFunction(list.listener) && list.listener === listener)) {
  11245. delete this._events[type];
  11246. if (this._events.removeListener)
  11247. this.emit('removeListener', type, listener);
  11248. } else if (isObject(list)) {
  11249. for (i = length; i-- > 0;) {
  11250. if (list[i] === listener ||
  11251. (list[i].listener && list[i].listener === listener)) {
  11252. position = i;
  11253. break;
  11254. }
  11255. }
  11256. if (position < 0)
  11257. return this;
  11258. if (list.length === 1) {
  11259. list.length = 0;
  11260. delete this._events[type];
  11261. } else {
  11262. list.splice(position, 1);
  11263. }
  11264. if (this._events.removeListener)
  11265. this.emit('removeListener', type, listener);
  11266. }
  11267. return this;
  11268. };
  11269. EventEmitter.prototype.removeAllListeners = function(type) {
  11270. var key, listeners;
  11271. if (!this._events)
  11272. return this;
  11273. // not listening for removeListener, no need to emit
  11274. if (!this._events.removeListener) {
  11275. if (arguments.length === 0)
  11276. this._events = {};
  11277. else if (this._events[type])
  11278. delete this._events[type];
  11279. return this;
  11280. }
  11281. // emit removeListener for all listeners on all events
  11282. if (arguments.length === 0) {
  11283. for (key in this._events) {
  11284. if (key === 'removeListener') continue;
  11285. this.removeAllListeners(key);
  11286. }
  11287. this.removeAllListeners('removeListener');
  11288. this._events = {};
  11289. return this;
  11290. }
  11291. listeners = this._events[type];
  11292. if (isFunction(listeners)) {
  11293. this.removeListener(type, listeners);
  11294. } else {
  11295. // LIFO order
  11296. while (listeners.length)
  11297. this.removeListener(type, listeners[listeners.length - 1]);
  11298. }
  11299. delete this._events[type];
  11300. return this;
  11301. };
  11302. EventEmitter.prototype.listeners = function(type) {
  11303. var ret;
  11304. if (!this._events || !this._events[type])
  11305. ret = [];
  11306. else if (isFunction(this._events[type]))
  11307. ret = [this._events[type]];
  11308. else
  11309. ret = this._events[type].slice();
  11310. return ret;
  11311. };
  11312. EventEmitter.listenerCount = function(emitter, type) {
  11313. var ret;
  11314. if (!emitter._events || !emitter._events[type])
  11315. ret = 0;
  11316. else if (isFunction(emitter._events[type]))
  11317. ret = 1;
  11318. else
  11319. ret = emitter._events[type].length;
  11320. return ret;
  11321. };
  11322. function isFunction(arg) {
  11323. return typeof arg === 'function';
  11324. }
  11325. function isNumber(arg) {
  11326. return typeof arg === 'number';
  11327. }
  11328. function isObject(arg) {
  11329. return typeof arg === 'object' && arg !== null;
  11330. }
  11331. function isUndefined(arg) {
  11332. return arg === void 0;
  11333. }
  11334. },{}],49:[function(require,module,exports){
  11335. // shim for using process in browser
  11336. var process = module.exports = {};
  11337. var queue = [];
  11338. var draining = false;
  11339. function drainQueue() {
  11340. if (draining) {
  11341. return;
  11342. }
  11343. draining = true;
  11344. var currentQueue;
  11345. var len = queue.length;
  11346. while(len) {
  11347. currentQueue = queue;
  11348. queue = [];
  11349. var i = -1;
  11350. while (++i < len) {
  11351. currentQueue[i]();
  11352. }
  11353. len = queue.length;
  11354. }
  11355. draining = false;
  11356. }
  11357. process.nextTick = function (fun) {
  11358. queue.push(fun);
  11359. if (!draining) {
  11360. setTimeout(drainQueue, 0);
  11361. }
  11362. };
  11363. process.title = 'browser';
  11364. process.browser = true;
  11365. process.env = {};
  11366. process.argv = [];
  11367. process.version = ''; // empty string to avoid regexp issues
  11368. function noop() {}
  11369. process.on = noop;
  11370. process.addListener = noop;
  11371. process.once = noop;
  11372. process.off = noop;
  11373. process.removeListener = noop;
  11374. process.removeAllListeners = noop;
  11375. process.emit = noop;
  11376. process.binding = function (name) {
  11377. throw new Error('process.binding is not supported');
  11378. };
  11379. // TODO(shtylman)
  11380. process.cwd = function () { return '/' };
  11381. process.chdir = function (dir) {
  11382. throw new Error('process.chdir is not supported');
  11383. };
  11384. process.umask = function() { return 0; };
  11385. },{}]},{},[7])(7)
  11386. });