kurento-client.js 1002 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513
  1. require=(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. /*
  3. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. var EventEmitter = require('events').EventEmitter;
  18. var url = require('url');
  19. var async = require('async');
  20. var extend = require('extend');
  21. var inherits = require('inherits');
  22. var reconnect = require('reconnect-ws');
  23. var checkType = require('./checkType');
  24. var RpcBuilder = require('kurento-jsonrpc');
  25. var JsonRPC = RpcBuilder.packers.JsonRPC;
  26. var promiseCallback = require('promisecallback');
  27. var disguise = require('./disguise')
  28. var createPromise = require('./createPromise');
  29. var MediaObjectCreator = require('./MediaObjectCreator');
  30. var TransactionsManager = require('./TransactionsManager');
  31. var TransactionNotCommitedException = TransactionsManager
  32. .TransactionNotCommitedException;
  33. var transactionOperation = TransactionsManager.transactionOperation;
  34. var MediaObject = require('kurento-client-core').abstracts.MediaObject;
  35. const MEDIA_OBJECT_TYPE_NOT_FOUND = 40100
  36. const MEDIA_OBJECT_NOT_FOUND = 40101
  37. const MEDIA_OBJECT_METHOD_NOT_FOUND = 40105
  38. const INVALID_SESSION = 40007
  39. const BASE_TIMEOUT = 20000;
  40. var PING_INTERVAL = 5000;
  41. var HEARTBEAT = 60000;
  42. var pingNextNum = 0;
  43. var enabledPings = true;
  44. var pingPongStarted = false;
  45. var pingInterval;
  46. var notReconnectIfNumLessThan = -1;
  47. /**
  48. * @function module:kurentoClient.KurentoClient~findIndex
  49. *
  50. * @param {external:Array} list
  51. * @param {external:Function} predicate
  52. *
  53. * @return {external:Integer}
  54. */
  55. function findIndex(list, predicate) {
  56. for (var i = 0, item; item = list[i]; i++)
  57. if (predicate(item)) return i;
  58. return -1;
  59. };
  60. /**
  61. * Serialize objects using their id
  62. *
  63. * @function module:kurentoClient.KurentoClient~serializeParams
  64. *
  65. * @param {external:Object} params
  66. *
  67. * @return {external:Object}
  68. */
  69. function serializeParams(params) {
  70. for (var key in params) {
  71. var param = params[key];
  72. if (param instanceof MediaObject || (param && (params.object !==
  73. undefined ||
  74. params.hub !== undefined || params.sink !== undefined))) {
  75. if (param && param.id != null) {
  76. params[key] = param.id;
  77. }
  78. }
  79. };
  80. return params;
  81. };
  82. /**
  83. * @function module:kurentoClient.KurentoClient~serializeOperation
  84. *
  85. * @param {external:Object} operation
  86. * @param {external:Integer} index
  87. */
  88. function serializeOperation(operation, index) {
  89. var params = operation.params;
  90. switch (operation.method) {
  91. case 'create':
  92. params.constructorParams = serializeParams(params.constructorParams);
  93. break;
  94. default:
  95. params = serializeParams(params);
  96. params.operationParams = serializeParams(params.operationParams);
  97. };
  98. operation.jsonrpc = "2.0";
  99. operation.id = index;
  100. };
  101. /**
  102. * @function module:kurentoClient.KurentoClient~deferred
  103. *
  104. * @param {module:core/abstracts.MediaObject} mediaObject
  105. * @param {external:Object} params
  106. * @param {external:Promise} prevRpc
  107. * @param {external:Function} callback
  108. *
  109. * @return {external:Promise}
  110. */
  111. function deferred(mediaObject, params, prevRpc, callback) {
  112. var promises = [];
  113. if (mediaObject != undefined)
  114. promises.push(mediaObject);
  115. for (var key in params) {
  116. var param = params[key];
  117. if (param !== undefined)
  118. promises.push(param);
  119. };
  120. if (prevRpc != undefined)
  121. promises.push(prevRpc);
  122. return promiseCallback(Promise.all(promises), callback);
  123. };
  124. /**
  125. * @function module:kurentoClient.KurentoClient~noop
  126. *
  127. * @param error
  128. * @param result
  129. *
  130. * @return result
  131. */
  132. function noop(error, result) {
  133. if (error) console.trace(error);
  134. return result
  135. };
  136. /**
  137. * @typedef {Object} module:kurentoClient.KurentoClient~KurentoClientDict
  138. * @property {external:Number} [failAfter=Infinity]
  139. * Fail after N reconnection attempts
  140. * @property {external:Boolean} [enableTransactions=true]
  141. * Enable transactions functionality
  142. * @property {external:Boolean} [strict=true]
  143. * Throw an error when creating an object of unknown type
  144. * @property {external:String} [access_token]
  145. * Set access token for the WebSocket connection
  146. * @property {external:Number} [max_retries=0]
  147. * Number of tries to send the requests
  148. * @property {external:Number} [request_timeout=20000]
  149. * Timeout between requests retries
  150. * @property {external:Number} [response_timeout=20000]
  151. * Timeout while a response is being stored
  152. * @property {external:Number} [duplicates_timeout=20000]
  153. * Timeout to ignore duplicated responses
  154. * @property {Object} [socket]
  155. * Websocket connection options
  156. */
  157. /**
  158. * Creates a connection with the Kurento Media Server
  159. *
  160. * @class module:kurentoClient.KurentoClient
  161. *
  162. * @param {external:String} ws_uri - Address of the Kurento Media Server
  163. * @param {module:kurentoClient.KurentoClient~KurentoClientDict} [options]
  164. * @param {module:kurentoClient.KurentoClient~constructorCallback} [callback]
  165. */
  166. function KurentoClient(ws_uri, options, callback) {
  167. if (!(this instanceof KurentoClient))
  168. return new KurentoClient(ws_uri, options, callback);
  169. var self = this;
  170. EventEmitter.call(this);
  171. // Promises to check previous RPC calls
  172. var prevRpc = Promise.resolve(); // request has been send
  173. var prevRpc_result = Promise.resolve(); // response has been received
  174. // Fix optional parameters
  175. if (options instanceof Function) {
  176. callback = options;
  177. options = undefined;
  178. };
  179. options = options || {};
  180. var failAfter = options.failAfter
  181. if (failAfter == undefined) failAfter = Infinity
  182. if (options.enableTransactions === undefined) options.enableTransactions =
  183. true
  184. if (options.strict === undefined) options.strict = true
  185. options.request_timeout = options.request_timeout || BASE_TIMEOUT;
  186. options.response_timeout = options.response_timeout || BASE_TIMEOUT;
  187. options.duplicates_timeout = options.duplicates_timeout || BASE_TIMEOUT;
  188. var objects = {};
  189. function onNotification(message) {
  190. var method = message.method;
  191. var params = message.params.value;
  192. var id = params.object;
  193. var object = objects[id];
  194. if (!object)
  195. return console.warn("Unknown object id '" + id + "'", message);
  196. switch (method) {
  197. case 'onEvent':
  198. object.emit(params.type, params.data);
  199. break;
  200. // case 'onError':
  201. // object.emit('error', params.error);
  202. // break;
  203. default:
  204. console.warn("Unknown message type '" + method + "'");
  205. };
  206. };
  207. //
  208. // JsonRPC
  209. //
  210. if (typeof ws_uri == 'string') {
  211. var access_token = options.access_token;
  212. if (access_token != undefined) {
  213. ws_uri = url.parse(ws_uri, true);
  214. ws_uri.query.access_token = access_token;
  215. ws_uri = url.format(ws_uri);
  216. delete options.access_token;
  217. };
  218. }
  219. var rpc = new RpcBuilder(JsonRPC, options, function (request) {
  220. if (request instanceof RpcBuilder.RpcNotification) {
  221. // Message is an unexpected request, notify error
  222. if (request.duplicated != undefined)
  223. return console.warn('Unexpected request:', request);
  224. // Message is a notification, process it
  225. return onNotification(request);
  226. };
  227. // Invalid message, notify error
  228. console.error('Invalid request instance', request);
  229. });
  230. // Select what transactions mechanism to use
  231. var encodeTransaction = options.enableTransactions ? commitTransactional :
  232. commitSerial;
  233. // Transactional API
  234. var transactionsManager = new TransactionsManager(this,
  235. function (operations, callback) {
  236. var params = {
  237. object: self,
  238. operations: operations
  239. };
  240. encodeTransaction(params, callback)
  241. });
  242. this.beginTransaction = transactionsManager.beginTransaction.bind(
  243. transactionsManager);
  244. this.endTransaction = transactionsManager.endTransaction.bind(
  245. transactionsManager);
  246. this.transaction = transactionsManager.transaction.bind(transactionsManager);
  247. Object.defineProperty(this, 'sessionId', {
  248. configurable: true
  249. })
  250. this.on('disconnect', function () {
  251. onDisconnected();
  252. Object.defineProperty(this, 'sessionId', {
  253. configurable: false,
  254. get: function () {
  255. throw new SyntaxError('Client has been disconnected')
  256. }
  257. })
  258. for (var id in objects)
  259. objects[id].emit('release')
  260. })
  261. // Emit events
  262. function onReconnected(sameSession) {
  263. self.emit('reconnected', sameSession);
  264. }
  265. function onDisconnected() {
  266. self.emit('disconnected');
  267. }
  268. function onConnectionFailed() {
  269. self.emit('connectionFailed');
  270. }
  271. function onConnected() {
  272. self.emit('connected');
  273. }
  274. // Encode commands
  275. function send(request) {
  276. var method = request.method
  277. var params = request.params
  278. var callback = request.callback
  279. var stack = request.stack
  280. var requestTimestamp = Date.now()
  281. rpc.encode(method, params, function (error, result) {
  282. if (error) {
  283. var responseTimestamp = Date.now()
  284. var constructor = Error
  285. switch (error.code) {
  286. case MEDIA_OBJECT_TYPE_NOT_FOUND:
  287. constructor = TypeError
  288. break
  289. case MEDIA_OBJECT_NOT_FOUND:
  290. constructor = ReferenceError
  291. break
  292. case MEDIA_OBJECT_METHOD_NOT_FOUND:
  293. constructor = SyntaxError
  294. break
  295. }
  296. error = extend(new constructor(error.message || error), error);
  297. Object.defineProperties(error, {
  298. 'requestTimestamp': {
  299. value: requestTimestamp
  300. },
  301. 'responseTimestamp': {
  302. value: responseTimestamp
  303. },
  304. 'stack': {
  305. value: [error.toString()].concat(
  306. error.stack.split('\n')[1],
  307. error.stack.split('\n').slice(2)
  308. ).join('\n')
  309. }
  310. })
  311. } else if ((self.sessionId !== result.sessionId) && (result.value !==
  312. 'pong'))
  313. Object.defineProperty(self, 'sessionId', {
  314. configurable: true,
  315. value: result.sessionId
  316. })
  317. callback(error, result);
  318. });
  319. }
  320. function operationResponse(operation, index) {
  321. var callback = operation.callback || noop;
  322. var operation_response = this.value[index];
  323. if (operation_response == undefined)
  324. return callback(new Error(
  325. 'Command not executed in the server'));
  326. var error = operation_response.error;
  327. var result = operation_response.result;
  328. var id;
  329. if (result) id = result.value;
  330. switch (operation.method) {
  331. case 'create':
  332. var mediaObject = operation.params.object;
  333. if (error) {
  334. mediaObject.emit('_id', error);
  335. return callback(error)
  336. }
  337. callback(null, registerObject(mediaObject, id));
  338. break;
  339. default:
  340. callback(error, result);
  341. }
  342. }
  343. function sendImplicitTransaction(operations) {
  344. function callback(error, result) {
  345. if (error) return console.error('Implicit transaction failed')
  346. operations.forEach(operationResponse, result)
  347. }
  348. operations.forEach(serializeOperation)
  349. var request = {
  350. method: 'transaction',
  351. params: {
  352. operations: operations
  353. },
  354. callback: callback
  355. }
  356. send(request)
  357. }
  358. var queueEncode = []
  359. function sendQueueEncode() {
  360. var request = queueEncode.shift()
  361. // We have several pending requests, create an "implicit" transaction
  362. if (queueEncode.length) {
  363. // Send (implicit) transactions from previous iteration
  364. while (request && request.method === 'transaction') {
  365. send(request)
  366. request = queueEncode.shift()
  367. }
  368. // Encode and queue transactions from current iteration to exec on next one
  369. var operations = []
  370. while (request) {
  371. if (request.method === 'transaction') {
  372. if (operations.length) {
  373. sendImplicitTransaction(operations)
  374. operations = []
  375. }
  376. send(request)
  377. } else
  378. operations.push(request)
  379. request = queueEncode.shift()
  380. }
  381. // Encode and queue remaining operations for next iteration
  382. if (operations.length) sendImplicitTransaction(operations)
  383. }
  384. // We have only one pending request, send it directly
  385. else
  386. send(request)
  387. }
  388. function encode(method, params, callback) {
  389. var stack = (new Error).stack
  390. params.sessionId = self.sessionId
  391. self.then(function () {
  392. if (options.useImplicitTransactions && !queueEncode.length)
  393. async.setImmediate(sendQueueEncode)
  394. var request = {
  395. method: method,
  396. params: params,
  397. callback: callback
  398. }
  399. Object.defineProperty(request, 'stack', {
  400. value: stack
  401. })
  402. if (options.useImplicitTransactions)
  403. queueEncode.push(request)
  404. else
  405. send(request)
  406. },
  407. callback)
  408. }
  409. function encodeCreate(transaction, params, callback) {
  410. if (transaction)
  411. return transactionOperation.call(transaction, 'create', params, callback)
  412. if (transactionsManager.length)
  413. return transactionOperation.call(transactionsManager, 'create',
  414. params, callback);
  415. callback = callback || noop;
  416. function callback2(error, result) {
  417. var mediaObject = params.object;
  418. // Implicit transaction has already register the MediaObject
  419. if (mediaObject === result) return callback(null, mediaObject);
  420. if (error) {
  421. mediaObject.emit('_id', error);
  422. return callback(error);
  423. }
  424. var id = result.value;
  425. callback(null, registerObject(mediaObject, id));
  426. }
  427. return deferred(null, params.constructorParams, null, function (error) {
  428. if (error) throw error;
  429. params.constructorParams = serializeParams(params.constructorParams);
  430. return encode('create', params, callback2);
  431. })
  432. .catch(callback)
  433. };
  434. /**
  435. * Request a generic functionality to be procesed by the server
  436. */
  437. function encodeRpc(transaction, method, params, callback) {
  438. if (transaction)
  439. return transactionOperation.call(transaction, method, params,
  440. callback);
  441. var object = params.object;
  442. if (object && object.transactions && object.transactions.length) {
  443. var error = new TransactionNotCommitedException();
  444. error.method = method;
  445. error.params = params;
  446. return setTimeout(callback, 0, error)
  447. };
  448. for (var key in params.operationParams) {
  449. var object = params.operationParams[key];
  450. if (object && object.transactions && object.transactions.length) {
  451. var error = new TransactionNotCommitedException();
  452. error.method = method;
  453. error.params = params;
  454. return setTimeout(callback, 0, error)
  455. };
  456. }
  457. if (transactionsManager.length)
  458. return transactionOperation.call(transactionsManager, method, params,
  459. callback);
  460. var promise = new Promise(function (resolve, reject) {
  461. function callback2(error, result) {
  462. if (error) return reject(error);
  463. resolve(result);
  464. };
  465. prevRpc = deferred(params.object, params.operationParams, prevRpc,
  466. function (error) {
  467. if (error) throw error
  468. params = serializeParams(params);
  469. params.operationParams = serializeParams(params
  470. .operationParams);
  471. return encode(method, params, callback2);
  472. })
  473. .catch(reject)
  474. });
  475. prevRpc_result = promiseCallback(promise, callback);
  476. if (method == 'release') prevRpc = prevRpc_result;
  477. }
  478. // Commit mechanisms
  479. /**
  480. * @function module:kurentoClient.KurentoClient~commitTransactional
  481. *
  482. * @param {external:Object} params
  483. * @param {external:Function} callback
  484. */
  485. function commitTransactional(params, callback) {
  486. if (transactionsManager.length)
  487. return transactionOperation.call(transactionsManager, 'transaction',
  488. params, callback);
  489. callback = callback || noop;
  490. var operations = params.operations;
  491. var promises = [];
  492. function checkId(operation, param) {
  493. if (param instanceof MediaObject && param.id === undefined) {
  494. var index = findIndex(operations, function (element) {
  495. return operation != element && element.params.object === param;
  496. });
  497. // MediaObject dependency is created in this transaction,
  498. // set a new reference ID
  499. if (index >= 0)
  500. return 'newref:' + index;
  501. // MediaObject dependency is created outside this transaction,
  502. // wait until it's ready
  503. promises.push(param);
  504. }
  505. return param
  506. }
  507. // Fix references to uninitialized MediaObjects
  508. operations.forEach(function (operation) {
  509. var params = operation.params;
  510. switch (operation.method) {
  511. case 'create':
  512. var constructorParams = params.constructorParams;
  513. for (var key in constructorParams)
  514. constructorParams[key] = checkId(operation, constructorParams[
  515. key]);
  516. break;
  517. default:
  518. params.object = checkId(operation, params.object);
  519. var operationParams = params.operationParams;
  520. for (var key in operationParams)
  521. operationParams[key] = checkId(operation, operationParams[key]);
  522. };
  523. });
  524. function callback2(error, result) {
  525. if (error) return callback(error);
  526. operations.forEach(operationResponse, result)
  527. callback(null, result);
  528. };
  529. Promise.all(promises).then(function () {
  530. operations.forEach(serializeOperation)
  531. encode('transaction', params, callback2);
  532. },
  533. callback);
  534. }
  535. /**
  536. * @function module:kurentoClient.KurentoClient~commitSerial
  537. *
  538. * @param {external:Object} params
  539. * @param {external:Function} callback
  540. */
  541. function commitSerial(params, callback) {
  542. if (transactionsManager.length)
  543. return transactionOperation.call(transactionsManager, 'transaction',
  544. params, callback);
  545. var operations = params.operations;
  546. async.each(operations, function (operation) {
  547. switch (operation.method) {
  548. case 'create':
  549. encodeCreate(undefined, operation.params, operation.callback);
  550. break;
  551. case 'transaction':
  552. commitSerial(operation.params.operations, operation.callback);
  553. break;
  554. default:
  555. encodeRpc(undefined, operation.method, operation.params,
  556. operation.callback);
  557. }
  558. },
  559. callback)
  560. }
  561. /**
  562. * @function module:kurentoClient.KurentoClient~registerObject
  563. *
  564. * @param {module:core/abstracts.MediaObject} mediaObject
  565. * @param {external:string} id
  566. */
  567. function registerObject(mediaObject, id) {
  568. var object = objects[id];
  569. if (object) return object;
  570. mediaObject.emit('_id', null, id);
  571. objects[id] = mediaObject;
  572. /**
  573. * Remove the object from cache
  574. */
  575. mediaObject.once('release', function () {
  576. delete objects[id];
  577. });
  578. return mediaObject;
  579. }
  580. // Creation of objects
  581. /**
  582. * Get a MediaObject from its ID
  583. *
  584. * @function module:kurentoClient.KurentoClient#getMediaobjectById
  585. *
  586. * @param {(external:String|external:string[])} id - ID of the MediaElement
  587. * @param {module:kurentoClient.KurentoClient~getMediaobjectByIdCallback} callback
  588. *
  589. * @return {external:Promise}
  590. */
  591. this.getMediaobjectById = function (id, callback) {
  592. return disguise(createPromise(id, describe, callback), this)
  593. };
  594. /**
  595. * @callback module:kurentoClient.KurentoClient~getMediaobjectByIdCallback
  596. * @param {external:Error} error
  597. * @param {(module:core/abstracts.MediaElement|module:core/abstracts.MediaElement[])} result
  598. * The requested MediaElement
  599. */
  600. var mediaObjectCreator = new MediaObjectCreator(this, encodeCreate,
  601. encodeRpc, encodeTransaction, this.getMediaobjectById.bind(this),
  602. options.strict);
  603. /**
  604. * @function module:kurentoClient.KurentoClient~describe
  605. *
  606. * @param {external:string} id
  607. * @param {external:Function} callback
  608. */
  609. function describe(id, callback) {
  610. if (id == undefined)
  611. return callback(new TypeError("'id' can't be null or undefined"))
  612. var mediaObject = objects[id];
  613. if (mediaObject) return callback(null, mediaObject);
  614. var params = {
  615. object: id
  616. };
  617. function callback2(error, result) {
  618. if (error) return callback(error);
  619. var mediaObject = mediaObjectCreator.createInmediate(result);
  620. return callback(null, registerObject(mediaObject, id));
  621. }
  622. encode('describe', params, callback2);
  623. };
  624. /**
  625. * @function module:kurentoClient.KurentoClient#_resetCache
  626. * @private
  627. */
  628. Object.defineProperty(this, '_resetCache', {
  629. value: function () {
  630. objects = {}
  631. }
  632. })
  633. /**
  634. * Create a new instance of a MediaObject
  635. *
  636. * @function module:kurentoClient.KurentoClient#create
  637. *
  638. * @param {external:String} type - Type of the element
  639. * @param {external:string[]} [params]
  640. * @param {module:kurentoClient.KurentoClient~createCallback} callback
  641. *
  642. * @return {(module:core/abstracts.MediaObject|module:core/abstracts.MediaObject[])}
  643. */
  644. this.create = mediaObjectCreator.create.bind(mediaObjectCreator);
  645. /**
  646. * @callback module:kurentoClient.KurentoClient~createCallback
  647. * @param {external:Error} error
  648. * @param {module:core/abstracts.MediaElement} result
  649. * The created MediaElement
  650. */
  651. function connect(callback) {
  652. callback = (callback || noop).bind(this)
  653. //
  654. // Ping
  655. //
  656. function enablePing() {
  657. enabledPings = true;
  658. if (!pingPongStarted) {
  659. pingPongStarted = true;
  660. pingInterval = setInterval(sendPing, HEARTBEAT);
  661. sendPing();
  662. }
  663. }
  664. function updateNotReconnectIfLessThan() {
  665. notReconnectIfNumLessThan = pingNextNum;
  666. console.log("notReconnectIfNumLessThan = " + notReconnectIfNumLessThan);
  667. }
  668. function sendPing() {
  669. if (enabledPings) {
  670. var params = null;
  671. if (pingNextNum == 0 || pingNextNum == notReconnectIfNumLessThan) {
  672. params = {
  673. interval: PING_INTERVAL
  674. };
  675. }
  676. pingNextNum++;
  677. var request = {
  678. method: 'ping',
  679. params: params,
  680. callback: (function (pingNum) {
  681. return function (error, result) {
  682. if (error) {
  683. if (pingNum > notReconnectIfNumLessThan) {
  684. enabledPings = false;
  685. updateNotReconnectIfLessThan();
  686. console.log(
  687. "Server did not respond to ping message " +
  688. pingNum + ".");
  689. clearInterval(pingInterval);
  690. pingPongStarted = false;
  691. }
  692. }
  693. }
  694. }(pingNextNum))
  695. }
  696. send(request);
  697. } else {
  698. console.log("Trying to send ping, but ping is not enabled");
  699. }
  700. }
  701. //
  702. // Reconnect websockets
  703. //
  704. var closed = false;
  705. var reconnected = false;
  706. var re = reconnect({
  707. // all options are optional
  708. // initialDelay: 1e3,
  709. // maxDelay: 30e3,
  710. // type: 'fibonacci', // available: fibonacci, exponential
  711. // randomisationFactor: 0,
  712. // immediate: false
  713. failAfter: failAfter
  714. }, function (ws_stream) {
  715. if (closed)
  716. ws_stream.writable = false;
  717. rpc.transport = ws_stream;
  718. enablePing();
  719. if (reconnected) {
  720. var params = {
  721. sessionId: self.sessionId
  722. };
  723. var request = {
  724. method: 'connect',
  725. params: params,
  726. callback: function (error, response) {
  727. if (error) {
  728. if (error.code === INVALID_SESSION) {
  729. console.log("Invalid Session")
  730. objects = {}
  731. onReconnected(false);
  732. }
  733. } else {
  734. onReconnected(true);
  735. }
  736. }
  737. }
  738. send(request);
  739. } else {
  740. onConnected();
  741. }
  742. })
  743. .connect(ws_uri, options.socket);
  744. Object.defineProperty(this, '_re', {
  745. get: function () {
  746. return re
  747. }
  748. })
  749. /**
  750. * @function module:kurentoClient.KurentoClient#close
  751. */
  752. this.close = function () {
  753. closed = true;
  754. prevRpc_result.then(re.disconnect.bind(re));
  755. };
  756. re.on('fail', this.emit.bind(this, 'disconnect'));
  757. re.on('reconnect', function (n, delay) {
  758. console.log('reconnect to server', n, delay, self.sessionId);
  759. if (pingInterval != undefined) {
  760. clearInterval(pingInterval);
  761. pingPongStarted = false;
  762. }
  763. reconnected = true;
  764. })
  765. //
  766. // Promise interface ("thenable")
  767. //
  768. /**
  769. * @function module:kurentoClient.KurentoClient#then
  770. *
  771. * @param {external:Function} onFulfilled
  772. * @param {external:Function} [onRejected]
  773. *
  774. * @return {external:Promise}
  775. */
  776. this.then = function (onFulfilled, onRejected) {
  777. if (re.connected)
  778. var promise = Promise.resolve(disguise.unthenable(this))
  779. else if (!re.reconnect)
  780. var promise = Promise.reject(new Error('Connection error'))
  781. else {
  782. var self = this
  783. var promise = new Promise(function (resolve, reject) {
  784. function success() {
  785. re.removeListener('fail', failure);
  786. resolve(disguise.unthenable(self));
  787. };
  788. function failure() {
  789. re.removeListener('connection', success);
  790. reject(new Error('Connection error'));
  791. };
  792. re.once('connection', success);
  793. re.once('fail', failure);
  794. });
  795. }
  796. promise = promise.then(onFulfilled ? onFulfilled.bind(this) :
  797. function (result) {
  798. return Promise.resolve(result)
  799. },
  800. onRejected ? onRejected.bind(this) :
  801. function (error) {
  802. return Promise.reject(error)
  803. });
  804. return disguise(promise, this)
  805. };
  806. /**
  807. * @function module:kurentoClient.KurentoClient#catch
  808. *
  809. * @param {external:Function} [onRejected]
  810. *
  811. * @return {external:Promise}
  812. */
  813. this.catch = this.then.bind(this, null);
  814. // Check for available modules in the Kurento Media Server
  815. var thenable = this
  816. if (options.strict)
  817. thenable = this.getServerManager()
  818. .then(function (serverManager) {
  819. return serverManager.getInfo()
  820. })
  821. .then(function (info) {
  822. var serverModules = info.modules.map(function (module) {
  823. return module.name
  824. })
  825. var notInstalled = KurentoClient.register.modules.filter(
  826. function (module) {
  827. return serverModules.indexOf(module) < 0
  828. })
  829. var length = notInstalled.length
  830. if (length) {
  831. if (length === 1)
  832. var message = "Module '" + notInstalled[0] +
  833. "' is not installed in the Kurento Media Server"
  834. else
  835. var message = "Modules '" + notInstalled.slice(0, -1).join(
  836. "', '") +
  837. "' and '" + notInstalled[length - 1] +
  838. "' are not installed in the Kurento Media Server"
  839. var error = new SyntaxError(message)
  840. error.modules = notInstalled
  841. return Promise.reject(error)
  842. }
  843. return Promise.resolve(self)
  844. })
  845. promiseCallback(thenable, callback);
  846. };
  847. connect.call(self, callback);
  848. };
  849. inherits(KurentoClient, EventEmitter);
  850. /**
  851. * @callback module:kurentoClient.KurentoClient~constructorCallback
  852. * @param {external:Error} error
  853. * @param {module:kurentoClient.KurentoClient} client
  854. * The created KurentoClient
  855. */
  856. /**
  857. * Connect the source of a media to the sink of the next one
  858. *
  859. * @function module:kurentoClient.KurentoClient#connect
  860. *
  861. * @param {...module:core/abstracts.MediaObject} media - A media to be connected
  862. * @param {module:kurentoClient.KurentoClient~connectCallback} [callback]
  863. *
  864. * @return {external:Promise}
  865. *
  866. * @throws {SyntaxError}
  867. */
  868. KurentoClient.prototype.connect = function (media, callback) {
  869. if (!(media instanceof Array)) {
  870. media = Array.prototype.slice.call(arguments, 0);
  871. callback = (typeof media[media.length - 1] === 'function') ? media.pop() :
  872. undefined;
  873. }
  874. callback = (callback || noop).bind(this)
  875. // Check if we have enought media components
  876. if (media.length < 2)
  877. throw new SyntaxError("Need at least two media elements to connect");
  878. return media[0].connect(media.slice(1), callback)
  879. };
  880. /**
  881. * @callback module:kurentoClient.KurentoClient~connectCallback
  882. * @param {external:Error} error
  883. */
  884. /**
  885. * Get a reference to the current Kurento Media Server we are connected
  886. *
  887. * @function module:kurentoClient.KurentoClient#getServerManager
  888. *
  889. * @param {module:kurentoClient.KurentoClient~getServerManagerCallback} callback
  890. *
  891. * @return {external:Promise}
  892. */
  893. KurentoClient.prototype.getServerManager = function (callback) {
  894. return this.getMediaobjectById('manager_ServerManager', callback)
  895. };
  896. /**
  897. * @callback module:kurentoClient.KurentoClient~getServerManagerCallback
  898. * @param {external:Error} error
  899. * @param {module:core/abstracts.ServerManager} server
  900. * Info of the MediaServer instance
  901. */
  902. //
  903. // Helper function to return a singleton client for a particular ws_uri
  904. //
  905. var singletons = {};
  906. /**
  907. * Creates a unique connection with the Kurento Media Server
  908. *
  909. * @function module:kurentoClient.KurentoClient.getSingleton
  910. * @see module:kurentoClient.KurentoClient
  911. *
  912. * @param {external:String} ws_uri - Address of the Kurento Media Server
  913. * @param {module:kurentoClient.KurentoClient~KurentoClientDict} [options]
  914. * @param {module:kurentoClient.KurentoClient~constructorCallback} [callback]
  915. *
  916. * @return {external:Promise}
  917. */
  918. KurentoClient.getSingleton = function (ws_uri, options, callback) {
  919. var client = singletons[ws_uri]
  920. if (!client) {
  921. // Fix optional parameters
  922. if (options instanceof Function) {
  923. callback = options;
  924. options = undefined;
  925. };
  926. client = KurentoClient(ws_uri, options, function (error, client) {
  927. if (error) return callback(error);
  928. singletons[ws_uri] = client
  929. client.on('disconnect', function () {
  930. delete singletons[ws_uri]
  931. })
  932. });
  933. }
  934. return disguise(promiseCallback(client, callback), client)
  935. }
  936. /**
  937. * Get a complexType across the qualified name
  938. *
  939. * @function module:kurentoClient.KurentoClient#getComplexType
  940. *
  941. * @param {external:String} complexType - ComplexType's name
  942. *
  943. * @return {module:core/complexType}
  944. */
  945. KurentoClient.getComplexType = function (complexType) {
  946. return KurentoClient.register.complexTypes[complexType]
  947. };
  948. // Export KurentoClient
  949. module.exports = KurentoClient;
  950. },{"./MediaObjectCreator":2,"./TransactionsManager":3,"./checkType":5,"./createPromise":6,"./disguise":7,"async":"async","events":21,"extend":22,"inherits":"inherits","kurento-client-core":"kurento-client-core","kurento-jsonrpc":117,"promisecallback":"promisecallback","reconnect-ws":143,"url":147}],2:[function(require,module,exports){
  951. /*
  952. * (C) Copyright 2014-2015 Kurento (http://kurento.org/)
  953. *
  954. * Licensed under the Apache License, Version 2.0 (the "License");
  955. * you may not use this file except in compliance with the License.
  956. * You may obtain a copy of the License at
  957. *
  958. * http://www.apache.org/licenses/LICENSE-2.0
  959. *
  960. * Unless required by applicable law or agreed to in writing, software
  961. * distributed under the License is distributed on an "AS IS" BASIS,
  962. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  963. * See the License for the specific language governing permissions and
  964. * limitations under the License.
  965. */
  966. var async = require('async');
  967. var checkType = require('./checkType');
  968. var checkParams = checkType.checkParams;
  969. var extend = require('extend');
  970. var createPromise = require('./createPromise');
  971. var register = require('./register');
  972. var Transaction = require('./TransactionsManager').Transaction;
  973. /**
  974. * Get the constructor for a type
  975. *
  976. * If the type is not registered, use generic {module:core/abstracts.MediaObject}
  977. *
  978. * @function module:kurentoClient~MediaObjectCreator~getConstructor
  979. *
  980. * @param {external:string} type
  981. * @param {external:Boolean} strict
  982. *
  983. * @return {module:core/abstracts.MediaObject}
  984. */
  985. function getConstructor(type, strict) {
  986. var result = register.classes[type.qualifiedType] || register.abstracts[type
  987. .qualifiedType] ||
  988. register.classes[type.type] || register.abstracts[type.type] ||
  989. register.classes[type] || register.abstracts[type];
  990. if (result) return result;
  991. if (type.hierarchy != undefined) {
  992. for (var i = 0; i <= type.hierarchy.length - 1; i++) {
  993. var result = register.classes[type.hierarchy[i]] || register.abstracts[
  994. type.hierarchy[i]];
  995. if (result) return result;
  996. };
  997. }
  998. if (strict) {
  999. var error = new SyntaxError("Unknown type '" + type + "'")
  1000. error.type = type
  1001. throw error
  1002. }
  1003. console.warn("Unknown type '", type, "', using MediaObject instead");
  1004. return register.abstracts.MediaObject;
  1005. };
  1006. /**
  1007. * @function module:kurentoClient~MediaObjectCreator~createConstructor
  1008. *
  1009. * @param item
  1010. * @param {external:Boolean} strict
  1011. *
  1012. * @return {module:core/abstracts.MediaObject}
  1013. */
  1014. function createConstructor(item, strict) {
  1015. var constructor = getConstructor(item, strict);
  1016. if (constructor.create) {
  1017. item = constructor.create(item.params);
  1018. // Apply inheritance
  1019. var prototype = constructor.prototype;
  1020. inherits(constructor, getConstructor(item, strict));
  1021. extend(constructor.prototype, prototype);
  1022. };
  1023. constructor.item = item;
  1024. return constructor;
  1025. }
  1026. var checkMediaElement = checkType.bind(null, 'MediaElement', 'media');
  1027. /**
  1028. * @class module:kurentoClient~MediaObjectCreator
  1029. *
  1030. * @param host
  1031. * @param encodeCreate
  1032. * @param encodeRpc
  1033. * @param encodeTransaction
  1034. * @param describe
  1035. * @param-[strict]
  1036. */
  1037. function MediaObjectCreator(host, encodeCreate, encodeRpc, encodeTransaction,
  1038. describe, strict) {
  1039. if (!(this instanceof MediaObjectCreator))
  1040. return new MediaObjectCreator(host, encodeCreate, encodeRpc,
  1041. encodeTransaction, describe)
  1042. /**
  1043. * @param constructor
  1044. *
  1045. * @return {module:core/abstracts.MediaObject}
  1046. */
  1047. function createObject(constructor) {
  1048. var mediaObject = new constructor(strict)
  1049. mediaObject.on('_describe', describe);
  1050. mediaObject.on('_rpc', encodeRpc);
  1051. if (mediaObject instanceof register.abstracts['kurento.Hub'] ||
  1052. mediaObject instanceof register
  1053. .classes['kurento.MediaPipeline'])
  1054. mediaObject.on('_create', encodeCreate);
  1055. if (mediaObject instanceof register.classes['kurento.MediaPipeline'])
  1056. mediaObject.on('_transaction', encodeTransaction);
  1057. return mediaObject;
  1058. };
  1059. /**
  1060. * Request to the server to create a new MediaElement
  1061. *
  1062. * @param item
  1063. * @param {module:kurentoClient~MediaObjectCreator~createMediaObjectCallback} [callback]
  1064. */
  1065. function createMediaObject(item, callback) {
  1066. var transaction = item.transaction;
  1067. delete item.transaction;
  1068. var constructor = createConstructor(item, strict);
  1069. item = constructor.item;
  1070. delete constructor.item;
  1071. var params = item.params || {};
  1072. delete item.params;
  1073. if (params.mediaPipeline == undefined && host instanceof register.classes
  1074. .MediaPipeline)
  1075. params.mediaPipeline = host;
  1076. var params_ = extend({}, params)
  1077. item.constructorParams = checkParams(params_, constructor.constructorParams,
  1078. item.type);
  1079. if (Object.keys(params_)) {
  1080. item.properties = params_;
  1081. }
  1082. if (!Object.keys(item.constructorParams).length)
  1083. delete item.constructorParams;
  1084. try {
  1085. var mediaObject = createObject(constructor)
  1086. } catch (error) {
  1087. return callback(error)
  1088. };
  1089. Object.defineProperty(item, 'object', {
  1090. value: mediaObject
  1091. });
  1092. encodeCreate(transaction, item, callback);
  1093. return mediaObject
  1094. };
  1095. /**
  1096. * @callback module:kurentoClient~MediaObjectCreator~createMediaObjectCallback
  1097. * @param {external:Error} error
  1098. */
  1099. /**
  1100. * @method module:kurentoClient~MediaObjectCreator#create
  1101. *
  1102. * @param type
  1103. * @param params
  1104. * @param {module:kurentoClient~MediaObjectCreator~createCallback} [callback]
  1105. */
  1106. this.create = function (type, params, callback) {
  1107. var transaction = (arguments[0] instanceof Transaction) ? Array.prototype
  1108. .shift.apply(arguments) : undefined;
  1109. switch (arguments.length) {
  1110. case 1:
  1111. params = undefined;
  1112. case 2:
  1113. callback = undefined;
  1114. };
  1115. // Fix optional parameters
  1116. if (params instanceof Function) {
  1117. if (callback)
  1118. throw new SyntaxError("Nothing can be defined after the callback");
  1119. callback = params;
  1120. params = undefined;
  1121. };
  1122. if (type instanceof Array) {
  1123. var createPipeline = false
  1124. type.forEach(function (request) {
  1125. var params = request.params || {}
  1126. if (typeof params.mediaPipeline === 'number')
  1127. createPipeline = true
  1128. })
  1129. function connectElements(error, elements) {
  1130. if (error) return callback(error)
  1131. if (params === true && host.connect)
  1132. return host.connect(elements.filter(function (element) {
  1133. try {
  1134. checkMediaElement(element)
  1135. return true
  1136. } catch (e) {}
  1137. }),
  1138. function (error) {
  1139. if (error) return callback(error)
  1140. callback(null, elements)
  1141. })
  1142. callback(null, elements)
  1143. }
  1144. if (createPipeline)
  1145. return host.transaction(function () {
  1146. var mediaObjects = []
  1147. async.map(type, function (request, callback) {
  1148. var params = request.params || {}
  1149. if (typeof params.mediaPipeline === 'number')
  1150. params.mediaPipeline = mediaObjects[params
  1151. .mediaPipeline]
  1152. mediaObjects.push(createMediaObject(request, callback))
  1153. },
  1154. connectElements)
  1155. })
  1156. return createPromise(type, createMediaObject, connectElements)
  1157. }
  1158. type = {
  1159. params: params,
  1160. transaction: transaction,
  1161. type: type
  1162. };
  1163. return createMediaObject(type, callback)
  1164. };
  1165. /**
  1166. * @callback module:kurentoClient~MediaObjectCreator~createCallback
  1167. *
  1168. * @param {external:Error} error
  1169. * @param {module:core/abstracts.MediaObject} mediaObject
  1170. * The created MediaObject
  1171. */
  1172. /**
  1173. * @method module:kurentoClient~MediaObjectCreator#createInmediate
  1174. *
  1175. * @param item
  1176. */
  1177. this.createInmediate = function (item) {
  1178. var constructor = createConstructor(item, strict);
  1179. delete constructor.item;
  1180. return createObject(constructor);
  1181. }
  1182. }
  1183. module.exports = MediaObjectCreator;
  1184. },{"./TransactionsManager":3,"./checkType":5,"./createPromise":6,"./register":8,"async":"async","extend":22}],3:[function(require,module,exports){
  1185. /*
  1186. * (C) Copyright 2013-2014 Kurento (http://kurento.org/)
  1187. *
  1188. * Licensed under the Apache License, Version 2.0 (the "License");
  1189. * you may not use this file except in compliance with the License.
  1190. * You may obtain a copy of the License at
  1191. *
  1192. * http://www.apache.org/licenses/LICENSE-2.0
  1193. *
  1194. * Unless required by applicable law or agreed to in writing, software
  1195. * distributed under the License is distributed on an "AS IS" BASIS,
  1196. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1197. * See the License for the specific language governing permissions and
  1198. * limitations under the License.
  1199. *
  1200. */
  1201. var inherits = require('inherits');
  1202. var Domain = require('domain').Domain || (function () {
  1203. function FakeDomain() {};
  1204. inherits(FakeDomain, require('events').EventEmitter);
  1205. FakeDomain.prototype.run = function (fn) {
  1206. try {
  1207. fn()
  1208. } catch (err) {
  1209. this.emit('error', err)
  1210. };
  1211. return this;
  1212. };
  1213. return FakeDomain;
  1214. })();
  1215. var promiseCallback = require('promisecallback');
  1216. function onerror(error) {
  1217. this._transactionError = error;
  1218. }
  1219. function TransactionNotExecutedException(message) {
  1220. TransactionNotExecutedException.super_.call(this, message);
  1221. };
  1222. inherits(TransactionNotExecutedException, Error);
  1223. function TransactionNotCommitedException(message) {
  1224. TransactionNotCommitedException.super_.call(this, message);
  1225. };
  1226. inherits(TransactionNotCommitedException, TransactionNotExecutedException);
  1227. function TransactionRollbackException(message) {
  1228. TransactionRollbackException.super_.call(this, message);
  1229. };
  1230. inherits(TransactionRollbackException, TransactionNotExecutedException);
  1231. function Transaction(commit) {
  1232. Transaction.super_.call(this);
  1233. var operations = [];
  1234. Object.defineProperty(this, 'length', {
  1235. get: function () {
  1236. return operations.length
  1237. }
  1238. });
  1239. this.push = operations.push.bind(operations);
  1240. Object.defineProperty(this, 'commited', {
  1241. configurable: true,
  1242. value: false
  1243. });
  1244. this.commit = function (callback) {
  1245. if (this.exit) this.exit();
  1246. this.removeListener('error', onerror);
  1247. var promise;
  1248. if (this._transactionError)
  1249. promise = Promise.reject(this._transactionError)
  1250. else {
  1251. operations.forEach(function (operation) {
  1252. var object = operation.params.object;
  1253. if (object && object.transactions) {
  1254. object.transactions.shift();
  1255. if (!object.transactions)
  1256. delete object.transactions;
  1257. }
  1258. });
  1259. var self = this;
  1260. promise = new Promise(function (resolve, reject) {
  1261. function callback(error, result) {
  1262. Object.defineProperty(self, 'commited', {
  1263. value: error == undefined
  1264. });
  1265. if (error) return reject(error);
  1266. resolve(result)
  1267. }
  1268. commit(operations, callback);
  1269. })
  1270. }
  1271. promise = promiseCallback(promise, callback)
  1272. this.catch = promise.catch.bind(promise);
  1273. this.then = promise.then.bind(promise);
  1274. delete this.push;
  1275. delete this.commit;
  1276. delete this.endTransaction;
  1277. return this;
  1278. }
  1279. this.rollback = function (callback) {
  1280. Object.defineProperty(this, 'commited', {
  1281. value: false
  1282. });
  1283. var error = new TransactionRollbackException(
  1284. 'Transaction rollback by user');
  1285. // Notify error to all the operations in the transaction
  1286. operations.forEach(function (operation) {
  1287. if (operation.method == 'create')
  1288. operation.params.object.emit('_id', error);
  1289. var callback = operation.callback;
  1290. if (callback instanceof Function)
  1291. callback(error);
  1292. });
  1293. if (callback instanceof Function)
  1294. callback(error);
  1295. return this;
  1296. };
  1297. // Errors during transaction execution go to the callback,
  1298. // user will register 'error' event for async errors later
  1299. this.once('error', onerror);
  1300. if (this.enter) this.enter();
  1301. }
  1302. inherits(Transaction, Domain);
  1303. function TransactionsManager(host, commit) {
  1304. var transactions = [];
  1305. Object.defineProperty(this, 'length', {
  1306. get: function () {
  1307. return transactions.length
  1308. }
  1309. });
  1310. this.beginTransaction = function () {
  1311. var transaction = new Transaction(commit);
  1312. // transactions.unshift(transaction);
  1313. return transaction;
  1314. };
  1315. this.endTransaction = function (callback) {
  1316. // return transactions.shift().commit(callback);
  1317. };
  1318. this.transaction = function (func, callback) {
  1319. var transaction = this.beginTransaction();
  1320. transactions.unshift(transaction);
  1321. transaction.run(func.bind(host));
  1322. return transactions.shift().commit(callback);
  1323. // return this.endTransaction(callback)
  1324. };
  1325. this.push = function (data) {
  1326. transactions[0].push(data);
  1327. }
  1328. };
  1329. function transactionOperation(method, params, callback) {
  1330. var operation = {
  1331. method: method,
  1332. params: params,
  1333. callback: callback
  1334. }
  1335. var object = params.object;
  1336. if (object) {
  1337. if (object.transactions) {
  1338. object.transactions.unshift(this)
  1339. } else {
  1340. Object.defineProperty(object, 'transactions', {
  1341. configurable: true,
  1342. value: [this]
  1343. });
  1344. }
  1345. }
  1346. this.push(operation);
  1347. };
  1348. module.exports = TransactionsManager;
  1349. TransactionsManager.Transaction = Transaction;
  1350. TransactionsManager.transactionOperation = transactionOperation;
  1351. TransactionsManager.TransactionNotExecutedException =
  1352. TransactionNotExecutedException;
  1353. TransactionsManager.TransactionNotCommitedException =
  1354. TransactionNotCommitedException;
  1355. TransactionsManager.TransactionRollbackException = TransactionRollbackException;
  1356. },{"domain":19,"events":21,"inherits":"inherits","promisecallback":"promisecallback"}],4:[function(require,module,exports){
  1357. /**
  1358. * Loader for the kurento-client package on the browser
  1359. */
  1360. if (typeof kurentoClient == 'undefined')
  1361. window.kurentoClient = require('.');
  1362. },{".":"kurento-client"}],5:[function(require,module,exports){
  1363. /*
  1364. * (C) Copyright 2014 Kurento (http://kurento.org/)
  1365. *
  1366. * Licensed under the Apache License, Version 2.0 (the "License");
  1367. * you may not use this file except in compliance with the License.
  1368. * You may obtain a copy of the License at
  1369. *
  1370. * http://www.apache.org/licenses/LICENSE-2.0
  1371. *
  1372. * Unless required by applicable law or agreed to in writing, software
  1373. * distributed under the License is distributed on an "AS IS" BASIS,
  1374. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1375. * See the License for the specific language governing permissions and
  1376. * limitations under the License.
  1377. *
  1378. */
  1379. /**
  1380. * Number.isInteger() polyfill
  1381. * @function external:Number#isInteger
  1382. * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger Number.isInteger}
  1383. */
  1384. if (!Number.isInteger) {
  1385. Number.isInteger = function isInteger(nVal) {
  1386. return typeof nVal === "number" && isFinite(nVal) && nVal > -
  1387. 9007199254740992 && nVal < 9007199254740992 && Math.floor(nVal) ===
  1388. nVal;
  1389. };
  1390. }
  1391. function ChecktypeError(key, type, value) {
  1392. return SyntaxError(key + ' param should be a ' + (type.name || type) +
  1393. ', not ' + value.constructor.name);
  1394. }
  1395. //
  1396. // Basic types
  1397. //
  1398. function checkArray(type, key, value) {
  1399. if (!(value instanceof Array))
  1400. throw ChecktypeError(key, 'Array of ' + type, value);
  1401. value.forEach(function (item, i) {
  1402. checkType(type, key + '[' + i + ']', item);
  1403. })
  1404. };
  1405. function checkBoolean(key, value) {
  1406. if (typeof value != 'boolean')
  1407. throw ChecktypeError(key, Boolean, value);
  1408. };
  1409. function checkNumber(key, value) {
  1410. if (typeof value != 'number')
  1411. throw ChecktypeError(key, Number, value);
  1412. };
  1413. function checkInteger(key, value) {
  1414. if (!Number.isInteger(value))
  1415. throw ChecktypeError(key, 'Integer', value);
  1416. };
  1417. function checkObject(key, value) {
  1418. if (typeof value != 'object')
  1419. throw ChecktypeError(key, Object, value);
  1420. };
  1421. function checkString(key, value) {
  1422. if (typeof value != 'string')
  1423. throw ChecktypeError(key, String, value);
  1424. };
  1425. // Checker functions
  1426. function checkType(type, key, value, options) {
  1427. options = options || {};
  1428. if (value != undefined) {
  1429. if (options.isArray)
  1430. return checkArray(type, key, value);
  1431. var checker = checkType[type];
  1432. if (checker) return checker(key, value);
  1433. console.warn("Could not check " + key + ", unknown type " + type);
  1434. // throw TypeError("Could not check "+key+", unknown type "+type);
  1435. } else if (options.required)
  1436. throw SyntaxError(key + " param is required");
  1437. };
  1438. function checkParams(params, scheme, class_name) {
  1439. var result = {};
  1440. // check MediaObject params
  1441. for (var key in scheme) {
  1442. var value = params[key];
  1443. var s = scheme[key];
  1444. checkType(s.type, key, value, s);
  1445. if (value == undefined) continue;
  1446. result[key] = value;
  1447. delete params[key];
  1448. };
  1449. return result;
  1450. };
  1451. function checkMethodParams(callparams, method_params) {
  1452. var result = {};
  1453. var index = 0,
  1454. param;
  1455. for (; param = method_params[index]; index++) {
  1456. var key = param.name;
  1457. var value = callparams[index];
  1458. checkType(param.type, key, value, param);
  1459. result[key] = value;
  1460. }
  1461. var params = callparams.slice(index);
  1462. if (params.length)
  1463. console.warning('Unused params:', params);
  1464. return result;
  1465. };
  1466. module.exports = checkType;
  1467. checkType.checkArray = checkArray;
  1468. checkType.checkParams = checkParams;
  1469. checkType.ChecktypeError = ChecktypeError;
  1470. // Basic types
  1471. checkType.boolean = checkBoolean;
  1472. checkType.double = checkNumber;
  1473. checkType.float = checkNumber;
  1474. checkType.int = checkInteger;
  1475. checkType.Object = checkObject;
  1476. checkType.String = checkString;
  1477. },{}],6:[function(require,module,exports){
  1478. /*
  1479. * (C) Copyright 2014 Kurento (http://kurento.org/)
  1480. *
  1481. * Licensed under the Apache License, Version 2.0 (the "License");
  1482. * you may not use this file except in compliance with the License.
  1483. * You may obtain a copy of the License at
  1484. *
  1485. * http://www.apache.org/licenses/LICENSE-2.0
  1486. *
  1487. * Unless required by applicable law or agreed to in writing, software
  1488. * distributed under the License is distributed on an "AS IS" BASIS,
  1489. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1490. * See the License for the specific language governing permissions and
  1491. * limitations under the License.
  1492. *
  1493. */
  1494. var async = require('async');
  1495. var disguise = require('./disguise')
  1496. var promiseCallback = require('promisecallback');
  1497. function createPromise(data, func, callback) {
  1498. var promise = new Promise(function (resolve, reject) {
  1499. function callback2(error, result) {
  1500. if (error) return reject(error);
  1501. //resolve(result)
  1502. resolve(disguise.unthenable(result));
  1503. };
  1504. if (data instanceof Array)
  1505. async.map(data, func, callback2);
  1506. else
  1507. func(data, callback2);
  1508. });
  1509. return promiseCallback(promise, callback);
  1510. };
  1511. module.exports = createPromise;
  1512. },{"./disguise":7,"async":"async","promisecallback":"promisecallback"}],7:[function(require,module,exports){
  1513. /**
  1514. * Generic `Promise.catch()` method
  1515. *
  1516. * It delegate its functionality on the `then()` of the object where it's
  1517. * applied, both directly or on its class definition prototype
  1518. *
  1519. * @param {Function} [onRejected]
  1520. *
  1521. * @return {Promise}
  1522. */
  1523. function promiseCatch(onRejected) {
  1524. return this.then(null, onRejected)
  1525. }
  1526. //
  1527. // Public API
  1528. //
  1529. /**
  1530. * Disguise an object giving it the appearance of another
  1531. *
  1532. * Add bind'ed functions and properties to a `target` object delegating the
  1533. * actions and attributes updates to the `source` one while retaining its
  1534. * original personality (i.e. duplicates and `instanceof` are preserved)
  1535. *
  1536. * @param {Object} target - the object to be disguised
  1537. * @param {Object} source - the object where to fetch its methods and attributes
  1538. * @param {Object} [unthenable] - the returned object should not be a thenable
  1539. *
  1540. * @return {Object} `target` disguised
  1541. */
  1542. function disguise(target, source, unthenable) {
  1543. if (source == null || target === source) return target
  1544. for (var key in source) {
  1545. if (target[key] !== undefined) continue
  1546. if (unthenable && (key === 'then' || key === 'catch')) continue
  1547. if (typeof source[key] === 'function')
  1548. var descriptor = {
  1549. value: source[key]
  1550. }
  1551. else
  1552. var descriptor = {
  1553. get: function () {
  1554. return source[key]
  1555. },
  1556. set: function (value) {
  1557. source[key] = value
  1558. }
  1559. }
  1560. descriptor.enumerable = true
  1561. Object.defineProperty(target, key, descriptor)
  1562. }
  1563. return target
  1564. }
  1565. /**
  1566. * Disguise a thenable object
  1567. *
  1568. * If available, `target.then()` gets replaced by a method that exec the
  1569. * `onFulfilled` and `onRejected` callbacks using `source` as `this` object, and
  1570. * return the Promise returned by the original `target.then()` method already
  1571. * disguised. It also add a `target.catch()` method pointing to the newly added
  1572. * `target.then()`, being it previously available or not.
  1573. *
  1574. * @param {thenable} target - the object to be disguised
  1575. * @param {Object} source - the object where to fetch its methods and attributes
  1576. *
  1577. * @return {thenable} `target` disguised
  1578. */
  1579. function disguiseThenable(target, source) {
  1580. if (target === source) return target
  1581. if (target.then instanceof Function) {
  1582. var target_then = target.then
  1583. function then(onFulfilled, onRejected) {
  1584. if (onFulfilled != null) onFulfilled = onFulfilled.bind(target)
  1585. if (onRejected != null) onRejected = onRejected.bind(target)
  1586. var promise = target_then.call(target, onFulfilled, onRejected)
  1587. return disguiseThenable(promise, source)
  1588. }
  1589. Object.defineProperties(target, {
  1590. then: {
  1591. value: then
  1592. },
  1593. catch: {
  1594. value: promiseCatch
  1595. }
  1596. })
  1597. }
  1598. return disguise(target, source)
  1599. }
  1600. /**
  1601. * Return a copy of the input object without `.then()` and `.catch()`
  1602. *
  1603. * @param {thenable} input
  1604. *
  1605. * @return {Object} unthenabled input object
  1606. */
  1607. function unthenable(input) {
  1608. var output = Object.assign({}, input)
  1609. delete output.then
  1610. if (input !== undefined)
  1611. output.constructor = input.constructor
  1612. if (input && input.then instanceof Function) return disguise(output, input,
  1613. true)
  1614. // `input` is not thenable
  1615. return input
  1616. }
  1617. disguiseThenable.disguise = disguise
  1618. disguiseThenable.disguiseThenable = disguiseThenable
  1619. disguiseThenable.unthenable = unthenable
  1620. module.exports = disguiseThenable
  1621. },{}],8:[function(require,module,exports){
  1622. var checkType = require('./checkType');
  1623. var abstracts = {};
  1624. var classes = {};
  1625. var complexTypes = {};
  1626. var modules = [];
  1627. function registerAbstracts(classes, hierarchy) {
  1628. for (var name in classes) {
  1629. var constructor = classes[name]
  1630. // Register constructor checker
  1631. var check = constructor.check;
  1632. if (check) checkType[name] = check;
  1633. // Register constructor
  1634. abstracts[name] = constructor;
  1635. abstracts[hierarchy + "." + name] = constructor;
  1636. }
  1637. }
  1638. function registerClass(name, constructor) {
  1639. // Register constructor checker
  1640. var check = constructor.check;
  1641. if (check) checkType[name] = check;
  1642. // Register constructor
  1643. classes[name] = constructor;
  1644. }
  1645. function registerComplexTypes(types, hierarchy) {
  1646. for (var name in types) {
  1647. var constructor = types[name]
  1648. // Register constructor checker
  1649. var check = constructor.check;
  1650. if (check) {
  1651. checkType[name] = check;
  1652. checkType[hierarchy + "." + name] = check;
  1653. // Register constructor
  1654. complexTypes[name] = constructor;
  1655. complexTypes[hierarchy + "." + name] = constructor;
  1656. } else {
  1657. checkType[name] = constructor;
  1658. checkType[hierarchy + "." + name] = constructor;
  1659. }
  1660. }
  1661. }
  1662. function registerModule(name) {
  1663. modules.push(name)
  1664. modules.sort()
  1665. }
  1666. function register(name, constructor) {
  1667. // Adjust parameters
  1668. if (!name)
  1669. throw SyntaxError('Need to define an object, a module or a function')
  1670. if (typeof name != 'string') {
  1671. constructor = name
  1672. name = undefined
  1673. }
  1674. // Execute require if we only have a name
  1675. if (constructor == undefined)
  1676. return register(require(name));
  1677. // Execute require if the constructor is set as a string
  1678. if (typeof constructor === 'string')
  1679. return register(name, require(constructor));
  1680. // Registering a function
  1681. if (constructor instanceof Function) {
  1682. // Registration name
  1683. if (!name) name = constructor.name
  1684. if (name == undefined)
  1685. throw new SyntaxError("Can't register an anonymous module");
  1686. return registerClass(name, constructor)
  1687. }
  1688. // Registering a plugin
  1689. if (!name) name = constructor.name
  1690. if (name) registerModule(name)
  1691. for (var key in constructor) {
  1692. var value = constructor[key]
  1693. if (name === 'core' || name === 'elements' || name === 'filters')
  1694. name = 'kurento'
  1695. var hierarchy = name + "." + key;
  1696. if (typeof value !== 'string')
  1697. switch (key) {
  1698. case 'abstracts':
  1699. registerAbstracts(value, name)
  1700. break
  1701. case 'complexTypes':
  1702. registerComplexTypes(value, name)
  1703. break
  1704. default:
  1705. registerClass(hierarchy, value)
  1706. registerClass(key, value)
  1707. }
  1708. }
  1709. };
  1710. module.exports = register;
  1711. register.abstracts = abstracts;
  1712. register.classes = classes;
  1713. register.complexTypes = complexTypes;
  1714. register.modules = modules;
  1715. },{"./checkType":5}],9:[function(require,module,exports){
  1716. /*
  1717. * Copyright (c) 2012 Mathieu Turcotte
  1718. * Licensed under the MIT license.
  1719. */
  1720. var Backoff = require('./lib/backoff');
  1721. var ExponentialBackoffStrategy = require('./lib/strategy/exponential');
  1722. var FibonacciBackoffStrategy = require('./lib/strategy/fibonacci');
  1723. var FunctionCall = require('./lib/function_call.js');
  1724. module.exports.Backoff = Backoff;
  1725. module.exports.FunctionCall = FunctionCall;
  1726. module.exports.FibonacciStrategy = FibonacciBackoffStrategy;
  1727. module.exports.ExponentialStrategy = ExponentialBackoffStrategy;
  1728. /**
  1729. * Constructs a Fibonacci backoff.
  1730. * @param options Fibonacci backoff strategy arguments.
  1731. * @return The fibonacci backoff.
  1732. * @see FibonacciBackoffStrategy
  1733. */
  1734. module.exports.fibonacci = function(options) {
  1735. return new Backoff(new FibonacciBackoffStrategy(options));
  1736. };
  1737. /**
  1738. * Constructs an exponential backoff.
  1739. * @param options Exponential strategy arguments.
  1740. * @return The exponential backoff.
  1741. * @see ExponentialBackoffStrategy
  1742. */
  1743. module.exports.exponential = function(options) {
  1744. return new Backoff(new ExponentialBackoffStrategy(options));
  1745. };
  1746. /**
  1747. * Constructs a FunctionCall for the given function and arguments.
  1748. * @param fn The function to wrap in a backoff handler.
  1749. * @param vargs The function's arguments (var args).
  1750. * @param callback The function's callback.
  1751. * @return The FunctionCall instance.
  1752. */
  1753. module.exports.call = function(fn, vargs, callback) {
  1754. var args = Array.prototype.slice.call(arguments);
  1755. fn = args[0];
  1756. vargs = args.slice(1, args.length - 1);
  1757. callback = args[args.length - 1];
  1758. return new FunctionCall(fn, vargs, callback);
  1759. };
  1760. },{"./lib/backoff":10,"./lib/function_call.js":11,"./lib/strategy/exponential":12,"./lib/strategy/fibonacci":13}],10:[function(require,module,exports){
  1761. /*
  1762. * Copyright (c) 2012 Mathieu Turcotte
  1763. * Licensed under the MIT license.
  1764. */
  1765. var events = require('events');
  1766. var util = require('util');
  1767. /**
  1768. * Backoff driver.
  1769. * @param backoffStrategy Backoff delay generator/strategy.
  1770. * @constructor
  1771. */
  1772. function Backoff(backoffStrategy) {
  1773. events.EventEmitter.call(this);
  1774. this.backoffStrategy_ = backoffStrategy;
  1775. this.maxNumberOfRetry_ = -1;
  1776. this.backoffNumber_ = 0;
  1777. this.backoffDelay_ = 0;
  1778. this.timeoutID_ = -1;
  1779. this.handlers = {
  1780. backoff: this.onBackoff_.bind(this)
  1781. };
  1782. }
  1783. util.inherits(Backoff, events.EventEmitter);
  1784. /**
  1785. * Sets a limit, greater than 0, on the maximum number of backoffs. A 'fail'
  1786. * event will be emitted when the limit is reached.
  1787. * @param maxNumberOfRetry The maximum number of backoffs.
  1788. */
  1789. Backoff.prototype.failAfter = function(maxNumberOfRetry) {
  1790. if (maxNumberOfRetry < 1) {
  1791. throw new Error('Maximum number of retry must be greater than 0. ' +
  1792. 'Actual: ' + maxNumberOfRetry);
  1793. }
  1794. this.maxNumberOfRetry_ = maxNumberOfRetry;
  1795. };
  1796. /**
  1797. * Starts a backoff operation.
  1798. * @param err Optional paramater to let the listeners know why the backoff
  1799. * operation was started.
  1800. */
  1801. Backoff.prototype.backoff = function(err) {
  1802. if (this.timeoutID_ !== -1) {
  1803. throw new Error('Backoff in progress.');
  1804. }
  1805. if (this.backoffNumber_ === this.maxNumberOfRetry_) {
  1806. this.emit('fail', err);
  1807. this.reset();
  1808. } else {
  1809. this.backoffDelay_ = this.backoffStrategy_.next();
  1810. this.timeoutID_ = setTimeout(this.handlers.backoff, this.backoffDelay_);
  1811. this.emit('backoff', this.backoffNumber_, this.backoffDelay_, err);
  1812. }
  1813. };
  1814. /**
  1815. * Handles the backoff timeout completion.
  1816. * @private
  1817. */
  1818. Backoff.prototype.onBackoff_ = function() {
  1819. this.timeoutID_ = -1;
  1820. this.emit('ready', this.backoffNumber_, this.backoffDelay_);
  1821. this.backoffNumber_++;
  1822. };
  1823. /**
  1824. * Stops any backoff operation and resets the backoff delay to its inital
  1825. * value.
  1826. */
  1827. Backoff.prototype.reset = function() {
  1828. this.backoffNumber_ = 0;
  1829. this.backoffStrategy_.reset();
  1830. clearTimeout(this.timeoutID_);
  1831. this.timeoutID_ = -1;
  1832. };
  1833. module.exports = Backoff;
  1834. },{"events":21,"util":151}],11:[function(require,module,exports){
  1835. /*
  1836. * Copyright (c) 2012 Mathieu Turcotte
  1837. * Licensed under the MIT license.
  1838. */
  1839. var events = require('events');
  1840. var util = require('util');
  1841. var Backoff = require('./backoff');
  1842. var FibonacciBackoffStrategy = require('./strategy/fibonacci');
  1843. /**
  1844. * Returns true if the specified value is a function
  1845. * @param val Variable to test.
  1846. * @return Whether variable is a function.
  1847. */
  1848. function isFunction(val) {
  1849. return typeof val == 'function';
  1850. }
  1851. /**
  1852. * Manages the calling of a function in a backoff loop.
  1853. * @param fn Function to wrap in a backoff handler.
  1854. * @param args Array of function's arguments.
  1855. * @param callback Function's callback.
  1856. * @constructor
  1857. */
  1858. function FunctionCall(fn, args, callback) {
  1859. events.EventEmitter.call(this);
  1860. if (!isFunction(fn)) {
  1861. throw new Error('fn should be a function.' +
  1862. 'Actual: ' + typeof fn);
  1863. }
  1864. if (!isFunction(callback)) {
  1865. throw new Error('callback should be a function.' +
  1866. 'Actual: ' + typeof fn);
  1867. }
  1868. this.function_ = fn;
  1869. this.arguments_ = args;
  1870. this.callback_ = callback;
  1871. this.results_ = [];
  1872. this.backoff_ = null;
  1873. this.strategy_ = null;
  1874. this.failAfter_ = -1;
  1875. this.state_ = FunctionCall.State_.PENDING;
  1876. }
  1877. util.inherits(FunctionCall, events.EventEmitter);
  1878. /**
  1879. * Enum of states in which the FunctionCall can be.
  1880. * @private
  1881. */
  1882. FunctionCall.State_ = {
  1883. PENDING: 0,
  1884. RUNNING: 1,
  1885. COMPLETED: 2,
  1886. ABORTED: 3
  1887. };
  1888. /**
  1889. * @return Whether the call is pending.
  1890. */
  1891. FunctionCall.prototype.isPending = function() {
  1892. return this.state_ == FunctionCall.State_.PENDING;
  1893. };
  1894. /**
  1895. * @return Whether the call is in progress.
  1896. */
  1897. FunctionCall.prototype.isRunning = function() {
  1898. return this.state_ == FunctionCall.State_.RUNNING;
  1899. };
  1900. /**
  1901. * @return Whether the call is completed.
  1902. */
  1903. FunctionCall.prototype.isCompleted = function() {
  1904. return this.state_ == FunctionCall.State_.COMPLETED;
  1905. };
  1906. /**
  1907. * @return Whether the call is aborted.
  1908. */
  1909. FunctionCall.prototype.isAborted = function() {
  1910. return this.state_ == FunctionCall.State_.ABORTED;
  1911. };
  1912. /**
  1913. * Sets the backoff strategy.
  1914. * @param strategy The backoff strategy to use.
  1915. * @return Itself for chaining.
  1916. */
  1917. FunctionCall.prototype.setStrategy = function(strategy) {
  1918. if (!this.isPending()) {
  1919. throw new Error('FunctionCall in progress.');
  1920. }
  1921. this.strategy_ = strategy;
  1922. return this;
  1923. };
  1924. /**
  1925. * Returns all intermediary results returned by the wrapped function since
  1926. * the initial call.
  1927. * @return An array of intermediary results.
  1928. */
  1929. FunctionCall.prototype.getResults = function() {
  1930. return this.results_.concat();
  1931. };
  1932. /**
  1933. * Sets the backoff limit.
  1934. * @param maxNumberOfRetry The maximum number of backoffs.
  1935. * @return Itself for chaining.
  1936. */
  1937. FunctionCall.prototype.failAfter = function(maxNumberOfRetry) {
  1938. if (!this.isPending()) {
  1939. throw new Error('FunctionCall in progress.');
  1940. }
  1941. this.failAfter_ = maxNumberOfRetry;
  1942. return this;
  1943. };
  1944. /**
  1945. * Aborts the call.
  1946. */
  1947. FunctionCall.prototype.abort = function() {
  1948. if (this.isCompleted()) {
  1949. throw new Error('FunctionCall already completed.');
  1950. }
  1951. if (this.isRunning()) {
  1952. this.backoff_.reset();
  1953. }
  1954. this.state_ = FunctionCall.State_.ABORTED;
  1955. };
  1956. /**
  1957. * Initiates the call to the wrapped function.
  1958. * @param backoffFactory Optional factory function used to create the backoff
  1959. * instance.
  1960. */
  1961. FunctionCall.prototype.start = function(backoffFactory) {
  1962. if (this.isAborted()) {
  1963. throw new Error('FunctionCall aborted.');
  1964. } else if (!this.isPending()) {
  1965. throw new Error('FunctionCall already started.');
  1966. }
  1967. var strategy = this.strategy_ || new FibonacciBackoffStrategy();
  1968. this.backoff_ = backoffFactory ?
  1969. backoffFactory(strategy) :
  1970. new Backoff(strategy);
  1971. this.backoff_.on('ready', this.doCall_.bind(this));
  1972. this.backoff_.on('fail', this.doCallback_.bind(this));
  1973. this.backoff_.on('backoff', this.handleBackoff_.bind(this));
  1974. if (this.failAfter_ > 0) {
  1975. this.backoff_.failAfter(this.failAfter_);
  1976. }
  1977. this.state_ = FunctionCall.State_.RUNNING;
  1978. this.doCall_();
  1979. };
  1980. /**
  1981. * Calls the wrapped function.
  1982. * @private
  1983. */
  1984. FunctionCall.prototype.doCall_ = function() {
  1985. var eventArgs = ['call'].concat(this.arguments_);
  1986. events.EventEmitter.prototype.emit.apply(this, eventArgs);
  1987. var callback = this.handleFunctionCallback_.bind(this);
  1988. this.function_.apply(null, this.arguments_.concat(callback));
  1989. };
  1990. /**
  1991. * Calls the wrapped function's callback with the last result returned by the
  1992. * wrapped function.
  1993. * @private
  1994. */
  1995. FunctionCall.prototype.doCallback_ = function() {
  1996. var args = this.results_[this.results_.length - 1];
  1997. this.callback_.apply(null, args);
  1998. };
  1999. /**
  2000. * Handles wrapped function's completion. This method acts as a replacement
  2001. * for the original callback function.
  2002. * @private
  2003. */
  2004. FunctionCall.prototype.handleFunctionCallback_ = function() {
  2005. if (this.isAborted()) {
  2006. return;
  2007. }
  2008. var args = Array.prototype.slice.call(arguments);
  2009. this.results_.push(args); // Save callback arguments.
  2010. events.EventEmitter.prototype.emit.apply(this, ['callback'].concat(args));
  2011. if (args[0]) {
  2012. this.backoff_.backoff(args[0]);
  2013. } else {
  2014. this.state_ = FunctionCall.State_.COMPLETED;
  2015. this.doCallback_();
  2016. }
  2017. };
  2018. /**
  2019. * Handles backoff event.
  2020. * @param number Backoff number.
  2021. * @param delay Backoff delay.
  2022. * @param err The error that caused the backoff.
  2023. * @private
  2024. */
  2025. FunctionCall.prototype.handleBackoff_ = function(number, delay, err) {
  2026. this.emit('backoff', number, delay, err);
  2027. };
  2028. module.exports = FunctionCall;
  2029. },{"./backoff":10,"./strategy/fibonacci":13,"events":21,"util":151}],12:[function(require,module,exports){
  2030. /*
  2031. * Copyright (c) 2012 Mathieu Turcotte
  2032. * Licensed under the MIT license.
  2033. */
  2034. var util = require('util');
  2035. var BackoffStrategy = require('./strategy');
  2036. /**
  2037. * Exponential backoff strategy.
  2038. * @extends BackoffStrategy
  2039. */
  2040. function ExponentialBackoffStrategy(options) {
  2041. BackoffStrategy.call(this, options);
  2042. this.backoffDelay_ = 0;
  2043. this.nextBackoffDelay_ = this.getInitialDelay();
  2044. }
  2045. util.inherits(ExponentialBackoffStrategy, BackoffStrategy);
  2046. /** @inheritDoc */
  2047. ExponentialBackoffStrategy.prototype.next_ = function() {
  2048. this.backoffDelay_ = Math.min(this.nextBackoffDelay_, this.getMaxDelay());
  2049. this.nextBackoffDelay_ = this.backoffDelay_ * 2;
  2050. return this.backoffDelay_;
  2051. };
  2052. /** @inheritDoc */
  2053. ExponentialBackoffStrategy.prototype.reset_ = function() {
  2054. this.backoffDelay_ = 0;
  2055. this.nextBackoffDelay_ = this.getInitialDelay();
  2056. };
  2057. module.exports = ExponentialBackoffStrategy;
  2058. },{"./strategy":14,"util":151}],13:[function(require,module,exports){
  2059. /*
  2060. * Copyright (c) 2012 Mathieu Turcotte
  2061. * Licensed under the MIT license.
  2062. */
  2063. var util = require('util');
  2064. var BackoffStrategy = require('./strategy');
  2065. /**
  2066. * Fibonacci backoff strategy.
  2067. * @extends BackoffStrategy
  2068. */
  2069. function FibonacciBackoffStrategy(options) {
  2070. BackoffStrategy.call(this, options);
  2071. this.backoffDelay_ = 0;
  2072. this.nextBackoffDelay_ = this.getInitialDelay();
  2073. }
  2074. util.inherits(FibonacciBackoffStrategy, BackoffStrategy);
  2075. /** @inheritDoc */
  2076. FibonacciBackoffStrategy.prototype.next_ = function() {
  2077. var backoffDelay = Math.min(this.nextBackoffDelay_, this.getMaxDelay());
  2078. this.nextBackoffDelay_ += this.backoffDelay_;
  2079. this.backoffDelay_ = backoffDelay;
  2080. return backoffDelay;
  2081. };
  2082. /** @inheritDoc */
  2083. FibonacciBackoffStrategy.prototype.reset_ = function() {
  2084. this.nextBackoffDelay_ = this.getInitialDelay();
  2085. this.backoffDelay_ = 0;
  2086. };
  2087. module.exports = FibonacciBackoffStrategy;
  2088. },{"./strategy":14,"util":151}],14:[function(require,module,exports){
  2089. /*
  2090. * Copyright (c) 2012 Mathieu Turcotte
  2091. * Licensed under the MIT license.
  2092. */
  2093. var events = require('events');
  2094. var util = require('util');
  2095. function isDef(value) {
  2096. return value !== undefined && value !== null;
  2097. }
  2098. /**
  2099. * Abstract class defining the skeleton for all backoff strategies.
  2100. * @param options Backoff strategy options.
  2101. * @param options.randomisationFactor The randomisation factor, must be between
  2102. * 0 and 1.
  2103. * @param options.initialDelay The backoff initial delay, in milliseconds.
  2104. * @param options.maxDelay The backoff maximal delay, in milliseconds.
  2105. * @constructor
  2106. */
  2107. function BackoffStrategy(options) {
  2108. options = options || {};
  2109. if (isDef(options.initialDelay) && options.initialDelay < 1) {
  2110. throw new Error('The initial timeout must be greater than 0.');
  2111. } else if (isDef(options.maxDelay) && options.maxDelay < 1) {
  2112. throw new Error('The maximal timeout must be greater than 0.');
  2113. }
  2114. this.initialDelay_ = options.initialDelay || 100;
  2115. this.maxDelay_ = options.maxDelay || 10000;
  2116. if (this.maxDelay_ <= this.initialDelay_) {
  2117. throw new Error('The maximal backoff delay must be ' +
  2118. 'greater than the initial backoff delay.');
  2119. }
  2120. if (isDef(options.randomisationFactor) &&
  2121. (options.randomisationFactor < 0 || options.randomisationFactor > 1)) {
  2122. throw new Error('The randomisation factor must be between 0 and 1.');
  2123. }
  2124. this.randomisationFactor_ = options.randomisationFactor || 0;
  2125. }
  2126. /**
  2127. * Retrieves the maximal backoff delay.
  2128. * @return The maximal backoff delay, in milliseconds.
  2129. */
  2130. BackoffStrategy.prototype.getMaxDelay = function() {
  2131. return this.maxDelay_;
  2132. };
  2133. /**
  2134. * Retrieves the initial backoff delay.
  2135. * @return The initial backoff delay, in milliseconds.
  2136. */
  2137. BackoffStrategy.prototype.getInitialDelay = function() {
  2138. return this.initialDelay_;
  2139. };
  2140. /**
  2141. * Template method that computes the next backoff delay.
  2142. * @return The backoff delay, in milliseconds.
  2143. */
  2144. BackoffStrategy.prototype.next = function() {
  2145. var backoffDelay = this.next_();
  2146. var randomisationMultiple = 1 + Math.random() * this.randomisationFactor_;
  2147. var randomizedDelay = Math.round(backoffDelay * randomisationMultiple);
  2148. return randomizedDelay;
  2149. };
  2150. /**
  2151. * Computes the next backoff delay.
  2152. * @return The backoff delay, in milliseconds.
  2153. * @protected
  2154. */
  2155. BackoffStrategy.prototype.next_ = function() {
  2156. throw new Error('BackoffStrategy.next_() unimplemented.');
  2157. };
  2158. /**
  2159. * Template method that resets the backoff delay to its initial value.
  2160. */
  2161. BackoffStrategy.prototype.reset = function() {
  2162. this.reset_();
  2163. };
  2164. /**
  2165. * Resets the backoff delay to its initial value.
  2166. * @protected
  2167. */
  2168. BackoffStrategy.prototype.reset_ = function() {
  2169. throw new Error('BackoffStrategy.reset_() unimplemented.');
  2170. };
  2171. module.exports = BackoffStrategy;
  2172. },{"events":21,"util":151}],15:[function(require,module,exports){
  2173. 'use strict'
  2174. exports.byteLength = byteLength
  2175. exports.toByteArray = toByteArray
  2176. exports.fromByteArray = fromByteArray
  2177. var lookup = []
  2178. var revLookup = []
  2179. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  2180. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  2181. for (var i = 0, len = code.length; i < len; ++i) {
  2182. lookup[i] = code[i]
  2183. revLookup[code.charCodeAt(i)] = i
  2184. }
  2185. // Support decoding URL-safe base64 strings, as Node.js does.
  2186. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  2187. revLookup['-'.charCodeAt(0)] = 62
  2188. revLookup['_'.charCodeAt(0)] = 63
  2189. function getLens (b64) {
  2190. var len = b64.length
  2191. if (len % 4 > 0) {
  2192. throw new Error('Invalid string. Length must be a multiple of 4')
  2193. }
  2194. // Trim off extra bytes after placeholder bytes are found
  2195. // See: https://github.com/beatgammit/base64-js/issues/42
  2196. var validLen = b64.indexOf('=')
  2197. if (validLen === -1) validLen = len
  2198. var placeHoldersLen = validLen === len
  2199. ? 0
  2200. : 4 - (validLen % 4)
  2201. return [validLen, placeHoldersLen]
  2202. }
  2203. // base64 is 4/3 + up to two characters of the original data
  2204. function byteLength (b64) {
  2205. var lens = getLens(b64)
  2206. var validLen = lens[0]
  2207. var placeHoldersLen = lens[1]
  2208. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  2209. }
  2210. function _byteLength (b64, validLen, placeHoldersLen) {
  2211. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  2212. }
  2213. function toByteArray (b64) {
  2214. var tmp
  2215. var lens = getLens(b64)
  2216. var validLen = lens[0]
  2217. var placeHoldersLen = lens[1]
  2218. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
  2219. var curByte = 0
  2220. // if there are placeholders, only get up to the last complete 4 chars
  2221. var len = placeHoldersLen > 0
  2222. ? validLen - 4
  2223. : validLen
  2224. var i
  2225. for (i = 0; i < len; i += 4) {
  2226. tmp =
  2227. (revLookup[b64.charCodeAt(i)] << 18) |
  2228. (revLookup[b64.charCodeAt(i + 1)] << 12) |
  2229. (revLookup[b64.charCodeAt(i + 2)] << 6) |
  2230. revLookup[b64.charCodeAt(i + 3)]
  2231. arr[curByte++] = (tmp >> 16) & 0xFF
  2232. arr[curByte++] = (tmp >> 8) & 0xFF
  2233. arr[curByte++] = tmp & 0xFF
  2234. }
  2235. if (placeHoldersLen === 2) {
  2236. tmp =
  2237. (revLookup[b64.charCodeAt(i)] << 2) |
  2238. (revLookup[b64.charCodeAt(i + 1)] >> 4)
  2239. arr[curByte++] = tmp & 0xFF
  2240. }
  2241. if (placeHoldersLen === 1) {
  2242. tmp =
  2243. (revLookup[b64.charCodeAt(i)] << 10) |
  2244. (revLookup[b64.charCodeAt(i + 1)] << 4) |
  2245. (revLookup[b64.charCodeAt(i + 2)] >> 2)
  2246. arr[curByte++] = (tmp >> 8) & 0xFF
  2247. arr[curByte++] = tmp & 0xFF
  2248. }
  2249. return arr
  2250. }
  2251. function tripletToBase64 (num) {
  2252. return lookup[num >> 18 & 0x3F] +
  2253. lookup[num >> 12 & 0x3F] +
  2254. lookup[num >> 6 & 0x3F] +
  2255. lookup[num & 0x3F]
  2256. }
  2257. function encodeChunk (uint8, start, end) {
  2258. var tmp
  2259. var output = []
  2260. for (var i = start; i < end; i += 3) {
  2261. tmp =
  2262. ((uint8[i] << 16) & 0xFF0000) +
  2263. ((uint8[i + 1] << 8) & 0xFF00) +
  2264. (uint8[i + 2] & 0xFF)
  2265. output.push(tripletToBase64(tmp))
  2266. }
  2267. return output.join('')
  2268. }
  2269. function fromByteArray (uint8) {
  2270. var tmp
  2271. var len = uint8.length
  2272. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  2273. var parts = []
  2274. var maxChunkLength = 16383 // must be multiple of 3
  2275. // go through the array every three bytes, we'll deal with trailing stuff later
  2276. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  2277. parts.push(encodeChunk(
  2278. uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
  2279. ))
  2280. }
  2281. // pad the end with zeros, but make sure to not forget the extra bytes
  2282. if (extraBytes === 1) {
  2283. tmp = uint8[len - 1]
  2284. parts.push(
  2285. lookup[tmp >> 2] +
  2286. lookup[(tmp << 4) & 0x3F] +
  2287. '=='
  2288. )
  2289. } else if (extraBytes === 2) {
  2290. tmp = (uint8[len - 2] << 8) + uint8[len - 1]
  2291. parts.push(
  2292. lookup[tmp >> 10] +
  2293. lookup[(tmp >> 4) & 0x3F] +
  2294. lookup[(tmp << 2) & 0x3F] +
  2295. '='
  2296. )
  2297. }
  2298. return parts.join('')
  2299. }
  2300. },{}],16:[function(require,module,exports){
  2301. },{}],17:[function(require,module,exports){
  2302. (function (Buffer){
  2303. /*!
  2304. * The buffer module from node.js, for the browser.
  2305. *
  2306. * @author Feross Aboukhadijeh <https://feross.org>
  2307. * @license MIT
  2308. */
  2309. /* eslint-disable no-proto */
  2310. 'use strict'
  2311. var base64 = require('base64-js')
  2312. var ieee754 = require('ieee754')
  2313. exports.Buffer = Buffer
  2314. exports.SlowBuffer = SlowBuffer
  2315. exports.INSPECT_MAX_BYTES = 50
  2316. var K_MAX_LENGTH = 0x7fffffff
  2317. exports.kMaxLength = K_MAX_LENGTH
  2318. /**
  2319. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  2320. * === true Use Uint8Array implementation (fastest)
  2321. * === false Print warning and recommend using `buffer` v4.x which has an Object
  2322. * implementation (most compatible, even IE6)
  2323. *
  2324. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  2325. * Opera 11.6+, iOS 4.2+.
  2326. *
  2327. * We report that the browser does not support typed arrays if the are not subclassable
  2328. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  2329. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  2330. * for __proto__ and has a buggy typed array implementation.
  2331. */
  2332. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
  2333. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
  2334. typeof console.error === 'function') {
  2335. console.error(
  2336. 'This browser lacks typed array (Uint8Array) support which is required by ' +
  2337. '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  2338. )
  2339. }
  2340. function typedArraySupport () {
  2341. // Can typed array instances can be augmented?
  2342. try {
  2343. var arr = new Uint8Array(1)
  2344. arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
  2345. return arr.foo() === 42
  2346. } catch (e) {
  2347. return false
  2348. }
  2349. }
  2350. Object.defineProperty(Buffer.prototype, 'parent', {
  2351. enumerable: true,
  2352. get: function () {
  2353. if (!Buffer.isBuffer(this)) return undefined
  2354. return this.buffer
  2355. }
  2356. })
  2357. Object.defineProperty(Buffer.prototype, 'offset', {
  2358. enumerable: true,
  2359. get: function () {
  2360. if (!Buffer.isBuffer(this)) return undefined
  2361. return this.byteOffset
  2362. }
  2363. })
  2364. function createBuffer (length) {
  2365. if (length > K_MAX_LENGTH) {
  2366. throw new RangeError('The value "' + length + '" is invalid for option "size"')
  2367. }
  2368. // Return an augmented `Uint8Array` instance
  2369. var buf = new Uint8Array(length)
  2370. buf.__proto__ = Buffer.prototype
  2371. return buf
  2372. }
  2373. /**
  2374. * The Buffer constructor returns instances of `Uint8Array` that have their
  2375. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  2376. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  2377. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  2378. * returns a single octet.
  2379. *
  2380. * The `Uint8Array` prototype remains unmodified.
  2381. */
  2382. function Buffer (arg, encodingOrOffset, length) {
  2383. // Common case.
  2384. if (typeof arg === 'number') {
  2385. if (typeof encodingOrOffset === 'string') {
  2386. throw new TypeError(
  2387. 'The "string" argument must be of type string. Received type number'
  2388. )
  2389. }
  2390. return allocUnsafe(arg)
  2391. }
  2392. return from(arg, encodingOrOffset, length)
  2393. }
  2394. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  2395. if (typeof Symbol !== 'undefined' && Symbol.species != null &&
  2396. Buffer[Symbol.species] === Buffer) {
  2397. Object.defineProperty(Buffer, Symbol.species, {
  2398. value: null,
  2399. configurable: true,
  2400. enumerable: false,
  2401. writable: false
  2402. })
  2403. }
  2404. Buffer.poolSize = 8192 // not used by this implementation
  2405. function from (value, encodingOrOffset, length) {
  2406. if (typeof value === 'string') {
  2407. return fromString(value, encodingOrOffset)
  2408. }
  2409. if (ArrayBuffer.isView(value)) {
  2410. return fromArrayLike(value)
  2411. }
  2412. if (value == null) {
  2413. throw TypeError(
  2414. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  2415. 'or Array-like Object. Received type ' + (typeof value)
  2416. )
  2417. }
  2418. if (isInstance(value, ArrayBuffer) ||
  2419. (value && isInstance(value.buffer, ArrayBuffer))) {
  2420. return fromArrayBuffer(value, encodingOrOffset, length)
  2421. }
  2422. if (typeof value === 'number') {
  2423. throw new TypeError(
  2424. 'The "value" argument must not be of type number. Received type number'
  2425. )
  2426. }
  2427. var valueOf = value.valueOf && value.valueOf()
  2428. if (valueOf != null && valueOf !== value) {
  2429. return Buffer.from(valueOf, encodingOrOffset, length)
  2430. }
  2431. var b = fromObject(value)
  2432. if (b) return b
  2433. if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
  2434. typeof value[Symbol.toPrimitive] === 'function') {
  2435. return Buffer.from(
  2436. value[Symbol.toPrimitive]('string'), encodingOrOffset, length
  2437. )
  2438. }
  2439. throw new TypeError(
  2440. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  2441. 'or Array-like Object. Received type ' + (typeof value)
  2442. )
  2443. }
  2444. /**
  2445. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  2446. * if value is a number.
  2447. * Buffer.from(str[, encoding])
  2448. * Buffer.from(array)
  2449. * Buffer.from(buffer)
  2450. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  2451. **/
  2452. Buffer.from = function (value, encodingOrOffset, length) {
  2453. return from(value, encodingOrOffset, length)
  2454. }
  2455. // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  2456. // https://github.com/feross/buffer/pull/148
  2457. Buffer.prototype.__proto__ = Uint8Array.prototype
  2458. Buffer.__proto__ = Uint8Array
  2459. function assertSize (size) {
  2460. if (typeof size !== 'number') {
  2461. throw new TypeError('"size" argument must be of type number')
  2462. } else if (size < 0) {
  2463. throw new RangeError('The value "' + size + '" is invalid for option "size"')
  2464. }
  2465. }
  2466. function alloc (size, fill, encoding) {
  2467. assertSize(size)
  2468. if (size <= 0) {
  2469. return createBuffer(size)
  2470. }
  2471. if (fill !== undefined) {
  2472. // Only pay attention to encoding if it's a string. This
  2473. // prevents accidentally sending in a number that would
  2474. // be interpretted as a start offset.
  2475. return typeof encoding === 'string'
  2476. ? createBuffer(size).fill(fill, encoding)
  2477. : createBuffer(size).fill(fill)
  2478. }
  2479. return createBuffer(size)
  2480. }
  2481. /**
  2482. * Creates a new filled Buffer instance.
  2483. * alloc(size[, fill[, encoding]])
  2484. **/
  2485. Buffer.alloc = function (size, fill, encoding) {
  2486. return alloc(size, fill, encoding)
  2487. }
  2488. function allocUnsafe (size) {
  2489. assertSize(size)
  2490. return createBuffer(size < 0 ? 0 : checked(size) | 0)
  2491. }
  2492. /**
  2493. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  2494. * */
  2495. Buffer.allocUnsafe = function (size) {
  2496. return allocUnsafe(size)
  2497. }
  2498. /**
  2499. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  2500. */
  2501. Buffer.allocUnsafeSlow = function (size) {
  2502. return allocUnsafe(size)
  2503. }
  2504. function fromString (string, encoding) {
  2505. if (typeof encoding !== 'string' || encoding === '') {
  2506. encoding = 'utf8'
  2507. }
  2508. if (!Buffer.isEncoding(encoding)) {
  2509. throw new TypeError('Unknown encoding: ' + encoding)
  2510. }
  2511. var length = byteLength(string, encoding) | 0
  2512. var buf = createBuffer(length)
  2513. var actual = buf.write(string, encoding)
  2514. if (actual !== length) {
  2515. // Writing a hex string, for example, that contains invalid characters will
  2516. // cause everything after the first invalid character to be ignored. (e.g.
  2517. // 'abxxcd' will be treated as 'ab')
  2518. buf = buf.slice(0, actual)
  2519. }
  2520. return buf
  2521. }
  2522. function fromArrayLike (array) {
  2523. var length = array.length < 0 ? 0 : checked(array.length) | 0
  2524. var buf = createBuffer(length)
  2525. for (var i = 0; i < length; i += 1) {
  2526. buf[i] = array[i] & 255
  2527. }
  2528. return buf
  2529. }
  2530. function fromArrayBuffer (array, byteOffset, length) {
  2531. if (byteOffset < 0 || array.byteLength < byteOffset) {
  2532. throw new RangeError('"offset" is outside of buffer bounds')
  2533. }
  2534. if (array.byteLength < byteOffset + (length || 0)) {
  2535. throw new RangeError('"length" is outside of buffer bounds')
  2536. }
  2537. var buf
  2538. if (byteOffset === undefined && length === undefined) {
  2539. buf = new Uint8Array(array)
  2540. } else if (length === undefined) {
  2541. buf = new Uint8Array(array, byteOffset)
  2542. } else {
  2543. buf = new Uint8Array(array, byteOffset, length)
  2544. }
  2545. // Return an augmented `Uint8Array` instance
  2546. buf.__proto__ = Buffer.prototype
  2547. return buf
  2548. }
  2549. function fromObject (obj) {
  2550. if (Buffer.isBuffer(obj)) {
  2551. var len = checked(obj.length) | 0
  2552. var buf = createBuffer(len)
  2553. if (buf.length === 0) {
  2554. return buf
  2555. }
  2556. obj.copy(buf, 0, 0, len)
  2557. return buf
  2558. }
  2559. if (obj.length !== undefined) {
  2560. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  2561. return createBuffer(0)
  2562. }
  2563. return fromArrayLike(obj)
  2564. }
  2565. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  2566. return fromArrayLike(obj.data)
  2567. }
  2568. }
  2569. function checked (length) {
  2570. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  2571. // length is NaN (which is otherwise coerced to zero.)
  2572. if (length >= K_MAX_LENGTH) {
  2573. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  2574. 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  2575. }
  2576. return length | 0
  2577. }
  2578. function SlowBuffer (length) {
  2579. if (+length != length) { // eslint-disable-line eqeqeq
  2580. length = 0
  2581. }
  2582. return Buffer.alloc(+length)
  2583. }
  2584. Buffer.isBuffer = function isBuffer (b) {
  2585. return b != null && b._isBuffer === true &&
  2586. b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
  2587. }
  2588. Buffer.compare = function compare (a, b) {
  2589. if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
  2590. if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
  2591. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  2592. throw new TypeError(
  2593. 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
  2594. )
  2595. }
  2596. if (a === b) return 0
  2597. var x = a.length
  2598. var y = b.length
  2599. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  2600. if (a[i] !== b[i]) {
  2601. x = a[i]
  2602. y = b[i]
  2603. break
  2604. }
  2605. }
  2606. if (x < y) return -1
  2607. if (y < x) return 1
  2608. return 0
  2609. }
  2610. Buffer.isEncoding = function isEncoding (encoding) {
  2611. switch (String(encoding).toLowerCase()) {
  2612. case 'hex':
  2613. case 'utf8':
  2614. case 'utf-8':
  2615. case 'ascii':
  2616. case 'latin1':
  2617. case 'binary':
  2618. case 'base64':
  2619. case 'ucs2':
  2620. case 'ucs-2':
  2621. case 'utf16le':
  2622. case 'utf-16le':
  2623. return true
  2624. default:
  2625. return false
  2626. }
  2627. }
  2628. Buffer.concat = function concat (list, length) {
  2629. if (!Array.isArray(list)) {
  2630. throw new TypeError('"list" argument must be an Array of Buffers')
  2631. }
  2632. if (list.length === 0) {
  2633. return Buffer.alloc(0)
  2634. }
  2635. var i
  2636. if (length === undefined) {
  2637. length = 0
  2638. for (i = 0; i < list.length; ++i) {
  2639. length += list[i].length
  2640. }
  2641. }
  2642. var buffer = Buffer.allocUnsafe(length)
  2643. var pos = 0
  2644. for (i = 0; i < list.length; ++i) {
  2645. var buf = list[i]
  2646. if (isInstance(buf, Uint8Array)) {
  2647. buf = Buffer.from(buf)
  2648. }
  2649. if (!Buffer.isBuffer(buf)) {
  2650. throw new TypeError('"list" argument must be an Array of Buffers')
  2651. }
  2652. buf.copy(buffer, pos)
  2653. pos += buf.length
  2654. }
  2655. return buffer
  2656. }
  2657. function byteLength (string, encoding) {
  2658. if (Buffer.isBuffer(string)) {
  2659. return string.length
  2660. }
  2661. if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
  2662. return string.byteLength
  2663. }
  2664. if (typeof string !== 'string') {
  2665. throw new TypeError(
  2666. 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
  2667. 'Received type ' + typeof string
  2668. )
  2669. }
  2670. var len = string.length
  2671. var mustMatch = (arguments.length > 2 && arguments[2] === true)
  2672. if (!mustMatch && len === 0) return 0
  2673. // Use a for loop to avoid recursion
  2674. var loweredCase = false
  2675. for (;;) {
  2676. switch (encoding) {
  2677. case 'ascii':
  2678. case 'latin1':
  2679. case 'binary':
  2680. return len
  2681. case 'utf8':
  2682. case 'utf-8':
  2683. return utf8ToBytes(string).length
  2684. case 'ucs2':
  2685. case 'ucs-2':
  2686. case 'utf16le':
  2687. case 'utf-16le':
  2688. return len * 2
  2689. case 'hex':
  2690. return len >>> 1
  2691. case 'base64':
  2692. return base64ToBytes(string).length
  2693. default:
  2694. if (loweredCase) {
  2695. return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
  2696. }
  2697. encoding = ('' + encoding).toLowerCase()
  2698. loweredCase = true
  2699. }
  2700. }
  2701. }
  2702. Buffer.byteLength = byteLength
  2703. function slowToString (encoding, start, end) {
  2704. var loweredCase = false
  2705. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  2706. // property of a typed array.
  2707. // This behaves neither like String nor Uint8Array in that we set start/end
  2708. // to their upper/lower bounds if the value passed is out of range.
  2709. // undefined is handled specially as per ECMA-262 6th Edition,
  2710. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  2711. if (start === undefined || start < 0) {
  2712. start = 0
  2713. }
  2714. // Return early if start > this.length. Done here to prevent potential uint32
  2715. // coercion fail below.
  2716. if (start > this.length) {
  2717. return ''
  2718. }
  2719. if (end === undefined || end > this.length) {
  2720. end = this.length
  2721. }
  2722. if (end <= 0) {
  2723. return ''
  2724. }
  2725. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  2726. end >>>= 0
  2727. start >>>= 0
  2728. if (end <= start) {
  2729. return ''
  2730. }
  2731. if (!encoding) encoding = 'utf8'
  2732. while (true) {
  2733. switch (encoding) {
  2734. case 'hex':
  2735. return hexSlice(this, start, end)
  2736. case 'utf8':
  2737. case 'utf-8':
  2738. return utf8Slice(this, start, end)
  2739. case 'ascii':
  2740. return asciiSlice(this, start, end)
  2741. case 'latin1':
  2742. case 'binary':
  2743. return latin1Slice(this, start, end)
  2744. case 'base64':
  2745. return base64Slice(this, start, end)
  2746. case 'ucs2':
  2747. case 'ucs-2':
  2748. case 'utf16le':
  2749. case 'utf-16le':
  2750. return utf16leSlice(this, start, end)
  2751. default:
  2752. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  2753. encoding = (encoding + '').toLowerCase()
  2754. loweredCase = true
  2755. }
  2756. }
  2757. }
  2758. // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  2759. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  2760. // reliably in a browserify context because there could be multiple different
  2761. // copies of the 'buffer' package in use. This method works even for Buffer
  2762. // instances that were created from another copy of the `buffer` package.
  2763. // See: https://github.com/feross/buffer/issues/154
  2764. Buffer.prototype._isBuffer = true
  2765. function swap (b, n, m) {
  2766. var i = b[n]
  2767. b[n] = b[m]
  2768. b[m] = i
  2769. }
  2770. Buffer.prototype.swap16 = function swap16 () {
  2771. var len = this.length
  2772. if (len % 2 !== 0) {
  2773. throw new RangeError('Buffer size must be a multiple of 16-bits')
  2774. }
  2775. for (var i = 0; i < len; i += 2) {
  2776. swap(this, i, i + 1)
  2777. }
  2778. return this
  2779. }
  2780. Buffer.prototype.swap32 = function swap32 () {
  2781. var len = this.length
  2782. if (len % 4 !== 0) {
  2783. throw new RangeError('Buffer size must be a multiple of 32-bits')
  2784. }
  2785. for (var i = 0; i < len; i += 4) {
  2786. swap(this, i, i + 3)
  2787. swap(this, i + 1, i + 2)
  2788. }
  2789. return this
  2790. }
  2791. Buffer.prototype.swap64 = function swap64 () {
  2792. var len = this.length
  2793. if (len % 8 !== 0) {
  2794. throw new RangeError('Buffer size must be a multiple of 64-bits')
  2795. }
  2796. for (var i = 0; i < len; i += 8) {
  2797. swap(this, i, i + 7)
  2798. swap(this, i + 1, i + 6)
  2799. swap(this, i + 2, i + 5)
  2800. swap(this, i + 3, i + 4)
  2801. }
  2802. return this
  2803. }
  2804. Buffer.prototype.toString = function toString () {
  2805. var length = this.length
  2806. if (length === 0) return ''
  2807. if (arguments.length === 0) return utf8Slice(this, 0, length)
  2808. return slowToString.apply(this, arguments)
  2809. }
  2810. Buffer.prototype.toLocaleString = Buffer.prototype.toString
  2811. Buffer.prototype.equals = function equals (b) {
  2812. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  2813. if (this === b) return true
  2814. return Buffer.compare(this, b) === 0
  2815. }
  2816. Buffer.prototype.inspect = function inspect () {
  2817. var str = ''
  2818. var max = exports.INSPECT_MAX_BYTES
  2819. str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
  2820. if (this.length > max) str += ' ... '
  2821. return '<Buffer ' + str + '>'
  2822. }
  2823. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  2824. if (isInstance(target, Uint8Array)) {
  2825. target = Buffer.from(target, target.offset, target.byteLength)
  2826. }
  2827. if (!Buffer.isBuffer(target)) {
  2828. throw new TypeError(
  2829. 'The "target" argument must be one of type Buffer or Uint8Array. ' +
  2830. 'Received type ' + (typeof target)
  2831. )
  2832. }
  2833. if (start === undefined) {
  2834. start = 0
  2835. }
  2836. if (end === undefined) {
  2837. end = target ? target.length : 0
  2838. }
  2839. if (thisStart === undefined) {
  2840. thisStart = 0
  2841. }
  2842. if (thisEnd === undefined) {
  2843. thisEnd = this.length
  2844. }
  2845. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  2846. throw new RangeError('out of range index')
  2847. }
  2848. if (thisStart >= thisEnd && start >= end) {
  2849. return 0
  2850. }
  2851. if (thisStart >= thisEnd) {
  2852. return -1
  2853. }
  2854. if (start >= end) {
  2855. return 1
  2856. }
  2857. start >>>= 0
  2858. end >>>= 0
  2859. thisStart >>>= 0
  2860. thisEnd >>>= 0
  2861. if (this === target) return 0
  2862. var x = thisEnd - thisStart
  2863. var y = end - start
  2864. var len = Math.min(x, y)
  2865. var thisCopy = this.slice(thisStart, thisEnd)
  2866. var targetCopy = target.slice(start, end)
  2867. for (var i = 0; i < len; ++i) {
  2868. if (thisCopy[i] !== targetCopy[i]) {
  2869. x = thisCopy[i]
  2870. y = targetCopy[i]
  2871. break
  2872. }
  2873. }
  2874. if (x < y) return -1
  2875. if (y < x) return 1
  2876. return 0
  2877. }
  2878. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  2879. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  2880. //
  2881. // Arguments:
  2882. // - buffer - a Buffer to search
  2883. // - val - a string, Buffer, or number
  2884. // - byteOffset - an index into `buffer`; will be clamped to an int32
  2885. // - encoding - an optional encoding, relevant is val is a string
  2886. // - dir - true for indexOf, false for lastIndexOf
  2887. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  2888. // Empty buffer means no match
  2889. if (buffer.length === 0) return -1
  2890. // Normalize byteOffset
  2891. if (typeof byteOffset === 'string') {
  2892. encoding = byteOffset
  2893. byteOffset = 0
  2894. } else if (byteOffset > 0x7fffffff) {
  2895. byteOffset = 0x7fffffff
  2896. } else if (byteOffset < -0x80000000) {
  2897. byteOffset = -0x80000000
  2898. }
  2899. byteOffset = +byteOffset // Coerce to Number.
  2900. if (numberIsNaN(byteOffset)) {
  2901. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  2902. byteOffset = dir ? 0 : (buffer.length - 1)
  2903. }
  2904. // Normalize byteOffset: negative offsets start from the end of the buffer
  2905. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  2906. if (byteOffset >= buffer.length) {
  2907. if (dir) return -1
  2908. else byteOffset = buffer.length - 1
  2909. } else if (byteOffset < 0) {
  2910. if (dir) byteOffset = 0
  2911. else return -1
  2912. }
  2913. // Normalize val
  2914. if (typeof val === 'string') {
  2915. val = Buffer.from(val, encoding)
  2916. }
  2917. // Finally, search either indexOf (if dir is true) or lastIndexOf
  2918. if (Buffer.isBuffer(val)) {
  2919. // Special case: looking for empty string/buffer always fails
  2920. if (val.length === 0) {
  2921. return -1
  2922. }
  2923. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  2924. } else if (typeof val === 'number') {
  2925. val = val & 0xFF // Search for a byte value [0-255]
  2926. if (typeof Uint8Array.prototype.indexOf === 'function') {
  2927. if (dir) {
  2928. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  2929. } else {
  2930. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  2931. }
  2932. }
  2933. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  2934. }
  2935. throw new TypeError('val must be string, number or Buffer')
  2936. }
  2937. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  2938. var indexSize = 1
  2939. var arrLength = arr.length
  2940. var valLength = val.length
  2941. if (encoding !== undefined) {
  2942. encoding = String(encoding).toLowerCase()
  2943. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  2944. encoding === 'utf16le' || encoding === 'utf-16le') {
  2945. if (arr.length < 2 || val.length < 2) {
  2946. return -1
  2947. }
  2948. indexSize = 2
  2949. arrLength /= 2
  2950. valLength /= 2
  2951. byteOffset /= 2
  2952. }
  2953. }
  2954. function read (buf, i) {
  2955. if (indexSize === 1) {
  2956. return buf[i]
  2957. } else {
  2958. return buf.readUInt16BE(i * indexSize)
  2959. }
  2960. }
  2961. var i
  2962. if (dir) {
  2963. var foundIndex = -1
  2964. for (i = byteOffset; i < arrLength; i++) {
  2965. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  2966. if (foundIndex === -1) foundIndex = i
  2967. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  2968. } else {
  2969. if (foundIndex !== -1) i -= i - foundIndex
  2970. foundIndex = -1
  2971. }
  2972. }
  2973. } else {
  2974. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  2975. for (i = byteOffset; i >= 0; i--) {
  2976. var found = true
  2977. for (var j = 0; j < valLength; j++) {
  2978. if (read(arr, i + j) !== read(val, j)) {
  2979. found = false
  2980. break
  2981. }
  2982. }
  2983. if (found) return i
  2984. }
  2985. }
  2986. return -1
  2987. }
  2988. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  2989. return this.indexOf(val, byteOffset, encoding) !== -1
  2990. }
  2991. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  2992. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  2993. }
  2994. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  2995. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  2996. }
  2997. function hexWrite (buf, string, offset, length) {
  2998. offset = Number(offset) || 0
  2999. var remaining = buf.length - offset
  3000. if (!length) {
  3001. length = remaining
  3002. } else {
  3003. length = Number(length)
  3004. if (length > remaining) {
  3005. length = remaining
  3006. }
  3007. }
  3008. var strLen = string.length
  3009. if (length > strLen / 2) {
  3010. length = strLen / 2
  3011. }
  3012. for (var i = 0; i < length; ++i) {
  3013. var parsed = parseInt(string.substr(i * 2, 2), 16)
  3014. if (numberIsNaN(parsed)) return i
  3015. buf[offset + i] = parsed
  3016. }
  3017. return i
  3018. }
  3019. function utf8Write (buf, string, offset, length) {
  3020. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  3021. }
  3022. function asciiWrite (buf, string, offset, length) {
  3023. return blitBuffer(asciiToBytes(string), buf, offset, length)
  3024. }
  3025. function latin1Write (buf, string, offset, length) {
  3026. return asciiWrite(buf, string, offset, length)
  3027. }
  3028. function base64Write (buf, string, offset, length) {
  3029. return blitBuffer(base64ToBytes(string), buf, offset, length)
  3030. }
  3031. function ucs2Write (buf, string, offset, length) {
  3032. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  3033. }
  3034. Buffer.prototype.write = function write (string, offset, length, encoding) {
  3035. // Buffer#write(string)
  3036. if (offset === undefined) {
  3037. encoding = 'utf8'
  3038. length = this.length
  3039. offset = 0
  3040. // Buffer#write(string, encoding)
  3041. } else if (length === undefined && typeof offset === 'string') {
  3042. encoding = offset
  3043. length = this.length
  3044. offset = 0
  3045. // Buffer#write(string, offset[, length][, encoding])
  3046. } else if (isFinite(offset)) {
  3047. offset = offset >>> 0
  3048. if (isFinite(length)) {
  3049. length = length >>> 0
  3050. if (encoding === undefined) encoding = 'utf8'
  3051. } else {
  3052. encoding = length
  3053. length = undefined
  3054. }
  3055. } else {
  3056. throw new Error(
  3057. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  3058. )
  3059. }
  3060. var remaining = this.length - offset
  3061. if (length === undefined || length > remaining) length = remaining
  3062. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  3063. throw new RangeError('Attempt to write outside buffer bounds')
  3064. }
  3065. if (!encoding) encoding = 'utf8'
  3066. var loweredCase = false
  3067. for (;;) {
  3068. switch (encoding) {
  3069. case 'hex':
  3070. return hexWrite(this, string, offset, length)
  3071. case 'utf8':
  3072. case 'utf-8':
  3073. return utf8Write(this, string, offset, length)
  3074. case 'ascii':
  3075. return asciiWrite(this, string, offset, length)
  3076. case 'latin1':
  3077. case 'binary':
  3078. return latin1Write(this, string, offset, length)
  3079. case 'base64':
  3080. // Warning: maxLength not taken into account in base64Write
  3081. return base64Write(this, string, offset, length)
  3082. case 'ucs2':
  3083. case 'ucs-2':
  3084. case 'utf16le':
  3085. case 'utf-16le':
  3086. return ucs2Write(this, string, offset, length)
  3087. default:
  3088. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  3089. encoding = ('' + encoding).toLowerCase()
  3090. loweredCase = true
  3091. }
  3092. }
  3093. }
  3094. Buffer.prototype.toJSON = function toJSON () {
  3095. return {
  3096. type: 'Buffer',
  3097. data: Array.prototype.slice.call(this._arr || this, 0)
  3098. }
  3099. }
  3100. function base64Slice (buf, start, end) {
  3101. if (start === 0 && end === buf.length) {
  3102. return base64.fromByteArray(buf)
  3103. } else {
  3104. return base64.fromByteArray(buf.slice(start, end))
  3105. }
  3106. }
  3107. function utf8Slice (buf, start, end) {
  3108. end = Math.min(buf.length, end)
  3109. var res = []
  3110. var i = start
  3111. while (i < end) {
  3112. var firstByte = buf[i]
  3113. var codePoint = null
  3114. var bytesPerSequence = (firstByte > 0xEF) ? 4
  3115. : (firstByte > 0xDF) ? 3
  3116. : (firstByte > 0xBF) ? 2
  3117. : 1
  3118. if (i + bytesPerSequence <= end) {
  3119. var secondByte, thirdByte, fourthByte, tempCodePoint
  3120. switch (bytesPerSequence) {
  3121. case 1:
  3122. if (firstByte < 0x80) {
  3123. codePoint = firstByte
  3124. }
  3125. break
  3126. case 2:
  3127. secondByte = buf[i + 1]
  3128. if ((secondByte & 0xC0) === 0x80) {
  3129. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  3130. if (tempCodePoint > 0x7F) {
  3131. codePoint = tempCodePoint
  3132. }
  3133. }
  3134. break
  3135. case 3:
  3136. secondByte = buf[i + 1]
  3137. thirdByte = buf[i + 2]
  3138. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  3139. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  3140. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  3141. codePoint = tempCodePoint
  3142. }
  3143. }
  3144. break
  3145. case 4:
  3146. secondByte = buf[i + 1]
  3147. thirdByte = buf[i + 2]
  3148. fourthByte = buf[i + 3]
  3149. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  3150. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  3151. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  3152. codePoint = tempCodePoint
  3153. }
  3154. }
  3155. }
  3156. }
  3157. if (codePoint === null) {
  3158. // we did not generate a valid codePoint so insert a
  3159. // replacement char (U+FFFD) and advance only 1 byte
  3160. codePoint = 0xFFFD
  3161. bytesPerSequence = 1
  3162. } else if (codePoint > 0xFFFF) {
  3163. // encode to utf16 (surrogate pair dance)
  3164. codePoint -= 0x10000
  3165. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  3166. codePoint = 0xDC00 | codePoint & 0x3FF
  3167. }
  3168. res.push(codePoint)
  3169. i += bytesPerSequence
  3170. }
  3171. return decodeCodePointsArray(res)
  3172. }
  3173. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  3174. // the lowest limit is Chrome, with 0x10000 args.
  3175. // We go 1 magnitude less, for safety
  3176. var MAX_ARGUMENTS_LENGTH = 0x1000
  3177. function decodeCodePointsArray (codePoints) {
  3178. var len = codePoints.length
  3179. if (len <= MAX_ARGUMENTS_LENGTH) {
  3180. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  3181. }
  3182. // Decode in chunks to avoid "call stack size exceeded".
  3183. var res = ''
  3184. var i = 0
  3185. while (i < len) {
  3186. res += String.fromCharCode.apply(
  3187. String,
  3188. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  3189. )
  3190. }
  3191. return res
  3192. }
  3193. function asciiSlice (buf, start, end) {
  3194. var ret = ''
  3195. end = Math.min(buf.length, end)
  3196. for (var i = start; i < end; ++i) {
  3197. ret += String.fromCharCode(buf[i] & 0x7F)
  3198. }
  3199. return ret
  3200. }
  3201. function latin1Slice (buf, start, end) {
  3202. var ret = ''
  3203. end = Math.min(buf.length, end)
  3204. for (var i = start; i < end; ++i) {
  3205. ret += String.fromCharCode(buf[i])
  3206. }
  3207. return ret
  3208. }
  3209. function hexSlice (buf, start, end) {
  3210. var len = buf.length
  3211. if (!start || start < 0) start = 0
  3212. if (!end || end < 0 || end > len) end = len
  3213. var out = ''
  3214. for (var i = start; i < end; ++i) {
  3215. out += toHex(buf[i])
  3216. }
  3217. return out
  3218. }
  3219. function utf16leSlice (buf, start, end) {
  3220. var bytes = buf.slice(start, end)
  3221. var res = ''
  3222. for (var i = 0; i < bytes.length; i += 2) {
  3223. res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  3224. }
  3225. return res
  3226. }
  3227. Buffer.prototype.slice = function slice (start, end) {
  3228. var len = this.length
  3229. start = ~~start
  3230. end = end === undefined ? len : ~~end
  3231. if (start < 0) {
  3232. start += len
  3233. if (start < 0) start = 0
  3234. } else if (start > len) {
  3235. start = len
  3236. }
  3237. if (end < 0) {
  3238. end += len
  3239. if (end < 0) end = 0
  3240. } else if (end > len) {
  3241. end = len
  3242. }
  3243. if (end < start) end = start
  3244. var newBuf = this.subarray(start, end)
  3245. // Return an augmented `Uint8Array` instance
  3246. newBuf.__proto__ = Buffer.prototype
  3247. return newBuf
  3248. }
  3249. /*
  3250. * Need to make sure that buffer isn't trying to write out of bounds.
  3251. */
  3252. function checkOffset (offset, ext, length) {
  3253. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  3254. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  3255. }
  3256. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  3257. offset = offset >>> 0
  3258. byteLength = byteLength >>> 0
  3259. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3260. var val = this[offset]
  3261. var mul = 1
  3262. var i = 0
  3263. while (++i < byteLength && (mul *= 0x100)) {
  3264. val += this[offset + i] * mul
  3265. }
  3266. return val
  3267. }
  3268. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  3269. offset = offset >>> 0
  3270. byteLength = byteLength >>> 0
  3271. if (!noAssert) {
  3272. checkOffset(offset, byteLength, this.length)
  3273. }
  3274. var val = this[offset + --byteLength]
  3275. var mul = 1
  3276. while (byteLength > 0 && (mul *= 0x100)) {
  3277. val += this[offset + --byteLength] * mul
  3278. }
  3279. return val
  3280. }
  3281. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  3282. offset = offset >>> 0
  3283. if (!noAssert) checkOffset(offset, 1, this.length)
  3284. return this[offset]
  3285. }
  3286. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  3287. offset = offset >>> 0
  3288. if (!noAssert) checkOffset(offset, 2, this.length)
  3289. return this[offset] | (this[offset + 1] << 8)
  3290. }
  3291. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  3292. offset = offset >>> 0
  3293. if (!noAssert) checkOffset(offset, 2, this.length)
  3294. return (this[offset] << 8) | this[offset + 1]
  3295. }
  3296. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  3297. offset = offset >>> 0
  3298. if (!noAssert) checkOffset(offset, 4, this.length)
  3299. return ((this[offset]) |
  3300. (this[offset + 1] << 8) |
  3301. (this[offset + 2] << 16)) +
  3302. (this[offset + 3] * 0x1000000)
  3303. }
  3304. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  3305. offset = offset >>> 0
  3306. if (!noAssert) checkOffset(offset, 4, this.length)
  3307. return (this[offset] * 0x1000000) +
  3308. ((this[offset + 1] << 16) |
  3309. (this[offset + 2] << 8) |
  3310. this[offset + 3])
  3311. }
  3312. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  3313. offset = offset >>> 0
  3314. byteLength = byteLength >>> 0
  3315. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3316. var val = this[offset]
  3317. var mul = 1
  3318. var i = 0
  3319. while (++i < byteLength && (mul *= 0x100)) {
  3320. val += this[offset + i] * mul
  3321. }
  3322. mul *= 0x80
  3323. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  3324. return val
  3325. }
  3326. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  3327. offset = offset >>> 0
  3328. byteLength = byteLength >>> 0
  3329. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3330. var i = byteLength
  3331. var mul = 1
  3332. var val = this[offset + --i]
  3333. while (i > 0 && (mul *= 0x100)) {
  3334. val += this[offset + --i] * mul
  3335. }
  3336. mul *= 0x80
  3337. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  3338. return val
  3339. }
  3340. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  3341. offset = offset >>> 0
  3342. if (!noAssert) checkOffset(offset, 1, this.length)
  3343. if (!(this[offset] & 0x80)) return (this[offset])
  3344. return ((0xff - this[offset] + 1) * -1)
  3345. }
  3346. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  3347. offset = offset >>> 0
  3348. if (!noAssert) checkOffset(offset, 2, this.length)
  3349. var val = this[offset] | (this[offset + 1] << 8)
  3350. return (val & 0x8000) ? val | 0xFFFF0000 : val
  3351. }
  3352. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  3353. offset = offset >>> 0
  3354. if (!noAssert) checkOffset(offset, 2, this.length)
  3355. var val = this[offset + 1] | (this[offset] << 8)
  3356. return (val & 0x8000) ? val | 0xFFFF0000 : val
  3357. }
  3358. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  3359. offset = offset >>> 0
  3360. if (!noAssert) checkOffset(offset, 4, this.length)
  3361. return (this[offset]) |
  3362. (this[offset + 1] << 8) |
  3363. (this[offset + 2] << 16) |
  3364. (this[offset + 3] << 24)
  3365. }
  3366. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  3367. offset = offset >>> 0
  3368. if (!noAssert) checkOffset(offset, 4, this.length)
  3369. return (this[offset] << 24) |
  3370. (this[offset + 1] << 16) |
  3371. (this[offset + 2] << 8) |
  3372. (this[offset + 3])
  3373. }
  3374. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  3375. offset = offset >>> 0
  3376. if (!noAssert) checkOffset(offset, 4, this.length)
  3377. return ieee754.read(this, offset, true, 23, 4)
  3378. }
  3379. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  3380. offset = offset >>> 0
  3381. if (!noAssert) checkOffset(offset, 4, this.length)
  3382. return ieee754.read(this, offset, false, 23, 4)
  3383. }
  3384. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  3385. offset = offset >>> 0
  3386. if (!noAssert) checkOffset(offset, 8, this.length)
  3387. return ieee754.read(this, offset, true, 52, 8)
  3388. }
  3389. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  3390. offset = offset >>> 0
  3391. if (!noAssert) checkOffset(offset, 8, this.length)
  3392. return ieee754.read(this, offset, false, 52, 8)
  3393. }
  3394. function checkInt (buf, value, offset, ext, max, min) {
  3395. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  3396. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  3397. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  3398. }
  3399. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  3400. value = +value
  3401. offset = offset >>> 0
  3402. byteLength = byteLength >>> 0
  3403. if (!noAssert) {
  3404. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  3405. checkInt(this, value, offset, byteLength, maxBytes, 0)
  3406. }
  3407. var mul = 1
  3408. var i = 0
  3409. this[offset] = value & 0xFF
  3410. while (++i < byteLength && (mul *= 0x100)) {
  3411. this[offset + i] = (value / mul) & 0xFF
  3412. }
  3413. return offset + byteLength
  3414. }
  3415. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  3416. value = +value
  3417. offset = offset >>> 0
  3418. byteLength = byteLength >>> 0
  3419. if (!noAssert) {
  3420. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  3421. checkInt(this, value, offset, byteLength, maxBytes, 0)
  3422. }
  3423. var i = byteLength - 1
  3424. var mul = 1
  3425. this[offset + i] = value & 0xFF
  3426. while (--i >= 0 && (mul *= 0x100)) {
  3427. this[offset + i] = (value / mul) & 0xFF
  3428. }
  3429. return offset + byteLength
  3430. }
  3431. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  3432. value = +value
  3433. offset = offset >>> 0
  3434. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  3435. this[offset] = (value & 0xff)
  3436. return offset + 1
  3437. }
  3438. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  3439. value = +value
  3440. offset = offset >>> 0
  3441. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  3442. this[offset] = (value & 0xff)
  3443. this[offset + 1] = (value >>> 8)
  3444. return offset + 2
  3445. }
  3446. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  3447. value = +value
  3448. offset = offset >>> 0
  3449. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  3450. this[offset] = (value >>> 8)
  3451. this[offset + 1] = (value & 0xff)
  3452. return offset + 2
  3453. }
  3454. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  3455. value = +value
  3456. offset = offset >>> 0
  3457. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  3458. this[offset + 3] = (value >>> 24)
  3459. this[offset + 2] = (value >>> 16)
  3460. this[offset + 1] = (value >>> 8)
  3461. this[offset] = (value & 0xff)
  3462. return offset + 4
  3463. }
  3464. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  3465. value = +value
  3466. offset = offset >>> 0
  3467. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  3468. this[offset] = (value >>> 24)
  3469. this[offset + 1] = (value >>> 16)
  3470. this[offset + 2] = (value >>> 8)
  3471. this[offset + 3] = (value & 0xff)
  3472. return offset + 4
  3473. }
  3474. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  3475. value = +value
  3476. offset = offset >>> 0
  3477. if (!noAssert) {
  3478. var limit = Math.pow(2, (8 * byteLength) - 1)
  3479. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  3480. }
  3481. var i = 0
  3482. var mul = 1
  3483. var sub = 0
  3484. this[offset] = value & 0xFF
  3485. while (++i < byteLength && (mul *= 0x100)) {
  3486. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  3487. sub = 1
  3488. }
  3489. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  3490. }
  3491. return offset + byteLength
  3492. }
  3493. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  3494. value = +value
  3495. offset = offset >>> 0
  3496. if (!noAssert) {
  3497. var limit = Math.pow(2, (8 * byteLength) - 1)
  3498. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  3499. }
  3500. var i = byteLength - 1
  3501. var mul = 1
  3502. var sub = 0
  3503. this[offset + i] = value & 0xFF
  3504. while (--i >= 0 && (mul *= 0x100)) {
  3505. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  3506. sub = 1
  3507. }
  3508. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  3509. }
  3510. return offset + byteLength
  3511. }
  3512. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  3513. value = +value
  3514. offset = offset >>> 0
  3515. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  3516. if (value < 0) value = 0xff + value + 1
  3517. this[offset] = (value & 0xff)
  3518. return offset + 1
  3519. }
  3520. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  3521. value = +value
  3522. offset = offset >>> 0
  3523. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  3524. this[offset] = (value & 0xff)
  3525. this[offset + 1] = (value >>> 8)
  3526. return offset + 2
  3527. }
  3528. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  3529. value = +value
  3530. offset = offset >>> 0
  3531. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  3532. this[offset] = (value >>> 8)
  3533. this[offset + 1] = (value & 0xff)
  3534. return offset + 2
  3535. }
  3536. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  3537. value = +value
  3538. offset = offset >>> 0
  3539. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  3540. this[offset] = (value & 0xff)
  3541. this[offset + 1] = (value >>> 8)
  3542. this[offset + 2] = (value >>> 16)
  3543. this[offset + 3] = (value >>> 24)
  3544. return offset + 4
  3545. }
  3546. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  3547. value = +value
  3548. offset = offset >>> 0
  3549. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  3550. if (value < 0) value = 0xffffffff + value + 1
  3551. this[offset] = (value >>> 24)
  3552. this[offset + 1] = (value >>> 16)
  3553. this[offset + 2] = (value >>> 8)
  3554. this[offset + 3] = (value & 0xff)
  3555. return offset + 4
  3556. }
  3557. function checkIEEE754 (buf, value, offset, ext, max, min) {
  3558. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  3559. if (offset < 0) throw new RangeError('Index out of range')
  3560. }
  3561. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  3562. value = +value
  3563. offset = offset >>> 0
  3564. if (!noAssert) {
  3565. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  3566. }
  3567. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  3568. return offset + 4
  3569. }
  3570. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  3571. return writeFloat(this, value, offset, true, noAssert)
  3572. }
  3573. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  3574. return writeFloat(this, value, offset, false, noAssert)
  3575. }
  3576. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  3577. value = +value
  3578. offset = offset >>> 0
  3579. if (!noAssert) {
  3580. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  3581. }
  3582. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  3583. return offset + 8
  3584. }
  3585. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  3586. return writeDouble(this, value, offset, true, noAssert)
  3587. }
  3588. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  3589. return writeDouble(this, value, offset, false, noAssert)
  3590. }
  3591. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  3592. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  3593. if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  3594. if (!start) start = 0
  3595. if (!end && end !== 0) end = this.length
  3596. if (targetStart >= target.length) targetStart = target.length
  3597. if (!targetStart) targetStart = 0
  3598. if (end > 0 && end < start) end = start
  3599. // Copy 0 bytes; we're done
  3600. if (end === start) return 0
  3601. if (target.length === 0 || this.length === 0) return 0
  3602. // Fatal error conditions
  3603. if (targetStart < 0) {
  3604. throw new RangeError('targetStart out of bounds')
  3605. }
  3606. if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  3607. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  3608. // Are we oob?
  3609. if (end > this.length) end = this.length
  3610. if (target.length - targetStart < end - start) {
  3611. end = target.length - targetStart + start
  3612. }
  3613. var len = end - start
  3614. if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
  3615. // Use built-in when available, missing from IE11
  3616. this.copyWithin(targetStart, start, end)
  3617. } else if (this === target && start < targetStart && targetStart < end) {
  3618. // descending copy from end
  3619. for (var i = len - 1; i >= 0; --i) {
  3620. target[i + targetStart] = this[i + start]
  3621. }
  3622. } else {
  3623. Uint8Array.prototype.set.call(
  3624. target,
  3625. this.subarray(start, end),
  3626. targetStart
  3627. )
  3628. }
  3629. return len
  3630. }
  3631. // Usage:
  3632. // buffer.fill(number[, offset[, end]])
  3633. // buffer.fill(buffer[, offset[, end]])
  3634. // buffer.fill(string[, offset[, end]][, encoding])
  3635. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  3636. // Handle string cases:
  3637. if (typeof val === 'string') {
  3638. if (typeof start === 'string') {
  3639. encoding = start
  3640. start = 0
  3641. end = this.length
  3642. } else if (typeof end === 'string') {
  3643. encoding = end
  3644. end = this.length
  3645. }
  3646. if (encoding !== undefined && typeof encoding !== 'string') {
  3647. throw new TypeError('encoding must be a string')
  3648. }
  3649. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  3650. throw new TypeError('Unknown encoding: ' + encoding)
  3651. }
  3652. if (val.length === 1) {
  3653. var code = val.charCodeAt(0)
  3654. if ((encoding === 'utf8' && code < 128) ||
  3655. encoding === 'latin1') {
  3656. // Fast path: If `val` fits into a single byte, use that numeric value.
  3657. val = code
  3658. }
  3659. }
  3660. } else if (typeof val === 'number') {
  3661. val = val & 255
  3662. }
  3663. // Invalid ranges are not set to a default, so can range check early.
  3664. if (start < 0 || this.length < start || this.length < end) {
  3665. throw new RangeError('Out of range index')
  3666. }
  3667. if (end <= start) {
  3668. return this
  3669. }
  3670. start = start >>> 0
  3671. end = end === undefined ? this.length : end >>> 0
  3672. if (!val) val = 0
  3673. var i
  3674. if (typeof val === 'number') {
  3675. for (i = start; i < end; ++i) {
  3676. this[i] = val
  3677. }
  3678. } else {
  3679. var bytes = Buffer.isBuffer(val)
  3680. ? val
  3681. : Buffer.from(val, encoding)
  3682. var len = bytes.length
  3683. if (len === 0) {
  3684. throw new TypeError('The value "' + val +
  3685. '" is invalid for argument "value"')
  3686. }
  3687. for (i = 0; i < end - start; ++i) {
  3688. this[i + start] = bytes[i % len]
  3689. }
  3690. }
  3691. return this
  3692. }
  3693. // HELPER FUNCTIONS
  3694. // ================
  3695. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
  3696. function base64clean (str) {
  3697. // Node takes equal signs as end of the Base64 encoding
  3698. str = str.split('=')[0]
  3699. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  3700. str = str.trim().replace(INVALID_BASE64_RE, '')
  3701. // Node converts strings with length < 2 to ''
  3702. if (str.length < 2) return ''
  3703. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  3704. while (str.length % 4 !== 0) {
  3705. str = str + '='
  3706. }
  3707. return str
  3708. }
  3709. function toHex (n) {
  3710. if (n < 16) return '0' + n.toString(16)
  3711. return n.toString(16)
  3712. }
  3713. function utf8ToBytes (string, units) {
  3714. units = units || Infinity
  3715. var codePoint
  3716. var length = string.length
  3717. var leadSurrogate = null
  3718. var bytes = []
  3719. for (var i = 0; i < length; ++i) {
  3720. codePoint = string.charCodeAt(i)
  3721. // is surrogate component
  3722. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  3723. // last char was a lead
  3724. if (!leadSurrogate) {
  3725. // no lead yet
  3726. if (codePoint > 0xDBFF) {
  3727. // unexpected trail
  3728. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3729. continue
  3730. } else if (i + 1 === length) {
  3731. // unpaired lead
  3732. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3733. continue
  3734. }
  3735. // valid lead
  3736. leadSurrogate = codePoint
  3737. continue
  3738. }
  3739. // 2 leads in a row
  3740. if (codePoint < 0xDC00) {
  3741. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3742. leadSurrogate = codePoint
  3743. continue
  3744. }
  3745. // valid surrogate pair
  3746. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  3747. } else if (leadSurrogate) {
  3748. // valid bmp char, but last char was a lead
  3749. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3750. }
  3751. leadSurrogate = null
  3752. // encode utf8
  3753. if (codePoint < 0x80) {
  3754. if ((units -= 1) < 0) break
  3755. bytes.push(codePoint)
  3756. } else if (codePoint < 0x800) {
  3757. if ((units -= 2) < 0) break
  3758. bytes.push(
  3759. codePoint >> 0x6 | 0xC0,
  3760. codePoint & 0x3F | 0x80
  3761. )
  3762. } else if (codePoint < 0x10000) {
  3763. if ((units -= 3) < 0) break
  3764. bytes.push(
  3765. codePoint >> 0xC | 0xE0,
  3766. codePoint >> 0x6 & 0x3F | 0x80,
  3767. codePoint & 0x3F | 0x80
  3768. )
  3769. } else if (codePoint < 0x110000) {
  3770. if ((units -= 4) < 0) break
  3771. bytes.push(
  3772. codePoint >> 0x12 | 0xF0,
  3773. codePoint >> 0xC & 0x3F | 0x80,
  3774. codePoint >> 0x6 & 0x3F | 0x80,
  3775. codePoint & 0x3F | 0x80
  3776. )
  3777. } else {
  3778. throw new Error('Invalid code point')
  3779. }
  3780. }
  3781. return bytes
  3782. }
  3783. function asciiToBytes (str) {
  3784. var byteArray = []
  3785. for (var i = 0; i < str.length; ++i) {
  3786. // Node's code seems to be doing this and not & 0x7F..
  3787. byteArray.push(str.charCodeAt(i) & 0xFF)
  3788. }
  3789. return byteArray
  3790. }
  3791. function utf16leToBytes (str, units) {
  3792. var c, hi, lo
  3793. var byteArray = []
  3794. for (var i = 0; i < str.length; ++i) {
  3795. if ((units -= 2) < 0) break
  3796. c = str.charCodeAt(i)
  3797. hi = c >> 8
  3798. lo = c % 256
  3799. byteArray.push(lo)
  3800. byteArray.push(hi)
  3801. }
  3802. return byteArray
  3803. }
  3804. function base64ToBytes (str) {
  3805. return base64.toByteArray(base64clean(str))
  3806. }
  3807. function blitBuffer (src, dst, offset, length) {
  3808. for (var i = 0; i < length; ++i) {
  3809. if ((i + offset >= dst.length) || (i >= src.length)) break
  3810. dst[i + offset] = src[i]
  3811. }
  3812. return i
  3813. }
  3814. // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
  3815. // the `instanceof` check but they should be treated as of that type.
  3816. // See: https://github.com/feross/buffer/issues/166
  3817. function isInstance (obj, type) {
  3818. return obj instanceof type ||
  3819. (obj != null && obj.constructor != null && obj.constructor.name != null &&
  3820. obj.constructor.name === type.name)
  3821. }
  3822. function numberIsNaN (obj) {
  3823. // For IE11 support
  3824. return obj !== obj // eslint-disable-line no-self-compare
  3825. }
  3826. }).call(this,require("buffer").Buffer)
  3827. },{"base64-js":15,"buffer":17,"ieee754":23}],18:[function(require,module,exports){
  3828. (function (Buffer){
  3829. // Copyright Joyent, Inc. and other Node contributors.
  3830. //
  3831. // Permission is hereby granted, free of charge, to any person obtaining a
  3832. // copy of this software and associated documentation files (the
  3833. // "Software"), to deal in the Software without restriction, including
  3834. // without limitation the rights to use, copy, modify, merge, publish,
  3835. // distribute, sublicense, and/or sell copies of the Software, and to permit
  3836. // persons to whom the Software is furnished to do so, subject to the
  3837. // following conditions:
  3838. //
  3839. // The above copyright notice and this permission notice shall be included
  3840. // in all copies or substantial portions of the Software.
  3841. //
  3842. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  3843. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  3844. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  3845. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  3846. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  3847. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  3848. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  3849. // NOTE: These type checking functions intentionally don't use `instanceof`
  3850. // because it is fragile and can be easily faked with `Object.create()`.
  3851. function isArray(arg) {
  3852. if (Array.isArray) {
  3853. return Array.isArray(arg);
  3854. }
  3855. return objectToString(arg) === '[object Array]';
  3856. }
  3857. exports.isArray = isArray;
  3858. function isBoolean(arg) {
  3859. return typeof arg === 'boolean';
  3860. }
  3861. exports.isBoolean = isBoolean;
  3862. function isNull(arg) {
  3863. return arg === null;
  3864. }
  3865. exports.isNull = isNull;
  3866. function isNullOrUndefined(arg) {
  3867. return arg == null;
  3868. }
  3869. exports.isNullOrUndefined = isNullOrUndefined;
  3870. function isNumber(arg) {
  3871. return typeof arg === 'number';
  3872. }
  3873. exports.isNumber = isNumber;
  3874. function isString(arg) {
  3875. return typeof arg === 'string';
  3876. }
  3877. exports.isString = isString;
  3878. function isSymbol(arg) {
  3879. return typeof arg === 'symbol';
  3880. }
  3881. exports.isSymbol = isSymbol;
  3882. function isUndefined(arg) {
  3883. return arg === void 0;
  3884. }
  3885. exports.isUndefined = isUndefined;
  3886. function isRegExp(re) {
  3887. return objectToString(re) === '[object RegExp]';
  3888. }
  3889. exports.isRegExp = isRegExp;
  3890. function isObject(arg) {
  3891. return typeof arg === 'object' && arg !== null;
  3892. }
  3893. exports.isObject = isObject;
  3894. function isDate(d) {
  3895. return objectToString(d) === '[object Date]';
  3896. }
  3897. exports.isDate = isDate;
  3898. function isError(e) {
  3899. return (objectToString(e) === '[object Error]' || e instanceof Error);
  3900. }
  3901. exports.isError = isError;
  3902. function isFunction(arg) {
  3903. return typeof arg === 'function';
  3904. }
  3905. exports.isFunction = isFunction;
  3906. function isPrimitive(arg) {
  3907. return arg === null ||
  3908. typeof arg === 'boolean' ||
  3909. typeof arg === 'number' ||
  3910. typeof arg === 'string' ||
  3911. typeof arg === 'symbol' || // ES6 symbol
  3912. typeof arg === 'undefined';
  3913. }
  3914. exports.isPrimitive = isPrimitive;
  3915. exports.isBuffer = Buffer.isBuffer;
  3916. function objectToString(o) {
  3917. return Object.prototype.toString.call(o);
  3918. }
  3919. }).call(this,{"isBuffer":require("../../is-buffer/index.js")})
  3920. },{"../../is-buffer/index.js":24}],19:[function(require,module,exports){
  3921. // This file should be ES5 compatible
  3922. /* eslint prefer-spread:0, no-var:0, prefer-reflect:0, no-magic-numbers:0 */
  3923. 'use strict'
  3924. module.exports = (function () {
  3925. // Import Events
  3926. var events = require('events')
  3927. // Export Domain
  3928. var domain = {}
  3929. domain.createDomain = domain.create = function () {
  3930. var d = new events.EventEmitter()
  3931. function emitError (e) {
  3932. d.emit('error', e)
  3933. }
  3934. d.add = function (emitter) {
  3935. emitter.on('error', emitError)
  3936. }
  3937. d.remove = function (emitter) {
  3938. emitter.removeListener('error', emitError)
  3939. }
  3940. d.bind = function (fn) {
  3941. return function () {
  3942. var args = Array.prototype.slice.call(arguments)
  3943. try {
  3944. fn.apply(null, args)
  3945. }
  3946. catch (err) {
  3947. emitError(err)
  3948. }
  3949. }
  3950. }
  3951. d.intercept = function (fn) {
  3952. return function (err) {
  3953. if ( err ) {
  3954. emitError(err)
  3955. }
  3956. else {
  3957. var args = Array.prototype.slice.call(arguments, 1)
  3958. try {
  3959. fn.apply(null, args)
  3960. }
  3961. catch (err) {
  3962. emitError(err)
  3963. }
  3964. }
  3965. }
  3966. }
  3967. d.run = function (fn) {
  3968. try {
  3969. fn()
  3970. }
  3971. catch (err) {
  3972. emitError(err)
  3973. }
  3974. return this
  3975. }
  3976. d.dispose = function () {
  3977. this.removeAllListeners()
  3978. return this
  3979. }
  3980. d.enter = d.exit = function () {
  3981. return this
  3982. }
  3983. return d
  3984. }
  3985. return domain
  3986. }).call(this)
  3987. },{"events":21}],20:[function(require,module,exports){
  3988. Object.defineProperty(Error.prototype, 'toJSON', {
  3989. value: function () {
  3990. var alt = {};
  3991. Object.getOwnPropertyNames(this).forEach(function (key) {
  3992. alt[key] = this[key];
  3993. }, this);
  3994. return alt;
  3995. },
  3996. configurable: true
  3997. });
  3998. },{}],21:[function(require,module,exports){
  3999. // Copyright Joyent, Inc. and other Node contributors.
  4000. //
  4001. // Permission is hereby granted, free of charge, to any person obtaining a
  4002. // copy of this software and associated documentation files (the
  4003. // "Software"), to deal in the Software without restriction, including
  4004. // without limitation the rights to use, copy, modify, merge, publish,
  4005. // distribute, sublicense, and/or sell copies of the Software, and to permit
  4006. // persons to whom the Software is furnished to do so, subject to the
  4007. // following conditions:
  4008. //
  4009. // The above copyright notice and this permission notice shall be included
  4010. // in all copies or substantial portions of the Software.
  4011. //
  4012. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  4013. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  4014. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  4015. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  4016. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  4017. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  4018. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  4019. var objectCreate = Object.create || objectCreatePolyfill
  4020. var objectKeys = Object.keys || objectKeysPolyfill
  4021. var bind = Function.prototype.bind || functionBindPolyfill
  4022. function EventEmitter() {
  4023. if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
  4024. this._events = objectCreate(null);
  4025. this._eventsCount = 0;
  4026. }
  4027. this._maxListeners = this._maxListeners || undefined;
  4028. }
  4029. module.exports = EventEmitter;
  4030. // Backwards-compat with node 0.10.x
  4031. EventEmitter.EventEmitter = EventEmitter;
  4032. EventEmitter.prototype._events = undefined;
  4033. EventEmitter.prototype._maxListeners = undefined;
  4034. // By default EventEmitters will print a warning if more than 10 listeners are
  4035. // added to it. This is a useful default which helps finding memory leaks.
  4036. var defaultMaxListeners = 10;
  4037. var hasDefineProperty;
  4038. try {
  4039. var o = {};
  4040. if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
  4041. hasDefineProperty = o.x === 0;
  4042. } catch (err) { hasDefineProperty = false }
  4043. if (hasDefineProperty) {
  4044. Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  4045. enumerable: true,
  4046. get: function() {
  4047. return defaultMaxListeners;
  4048. },
  4049. set: function(arg) {
  4050. // check whether the input is a positive number (whose value is zero or
  4051. // greater and not a NaN).
  4052. if (typeof arg !== 'number' || arg < 0 || arg !== arg)
  4053. throw new TypeError('"defaultMaxListeners" must be a positive number');
  4054. defaultMaxListeners = arg;
  4055. }
  4056. });
  4057. } else {
  4058. EventEmitter.defaultMaxListeners = defaultMaxListeners;
  4059. }
  4060. // Obviously not all Emitters should be limited to 10. This function allows
  4061. // that to be increased. Set to zero for unlimited.
  4062. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  4063. if (typeof n !== 'number' || n < 0 || isNaN(n))
  4064. throw new TypeError('"n" argument must be a positive number');
  4065. this._maxListeners = n;
  4066. return this;
  4067. };
  4068. function $getMaxListeners(that) {
  4069. if (that._maxListeners === undefined)
  4070. return EventEmitter.defaultMaxListeners;
  4071. return that._maxListeners;
  4072. }
  4073. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  4074. return $getMaxListeners(this);
  4075. };
  4076. // These standalone emit* functions are used to optimize calling of event
  4077. // handlers for fast cases because emit() itself often has a variable number of
  4078. // arguments and can be deoptimized because of that. These functions always have
  4079. // the same number of arguments and thus do not get deoptimized, so the code
  4080. // inside them can execute faster.
  4081. function emitNone(handler, isFn, self) {
  4082. if (isFn)
  4083. handler.call(self);
  4084. else {
  4085. var len = handler.length;
  4086. var listeners = arrayClone(handler, len);
  4087. for (var i = 0; i < len; ++i)
  4088. listeners[i].call(self);
  4089. }
  4090. }
  4091. function emitOne(handler, isFn, self, arg1) {
  4092. if (isFn)
  4093. handler.call(self, arg1);
  4094. else {
  4095. var len = handler.length;
  4096. var listeners = arrayClone(handler, len);
  4097. for (var i = 0; i < len; ++i)
  4098. listeners[i].call(self, arg1);
  4099. }
  4100. }
  4101. function emitTwo(handler, isFn, self, arg1, arg2) {
  4102. if (isFn)
  4103. handler.call(self, arg1, arg2);
  4104. else {
  4105. var len = handler.length;
  4106. var listeners = arrayClone(handler, len);
  4107. for (var i = 0; i < len; ++i)
  4108. listeners[i].call(self, arg1, arg2);
  4109. }
  4110. }
  4111. function emitThree(handler, isFn, self, arg1, arg2, arg3) {
  4112. if (isFn)
  4113. handler.call(self, arg1, arg2, arg3);
  4114. else {
  4115. var len = handler.length;
  4116. var listeners = arrayClone(handler, len);
  4117. for (var i = 0; i < len; ++i)
  4118. listeners[i].call(self, arg1, arg2, arg3);
  4119. }
  4120. }
  4121. function emitMany(handler, isFn, self, args) {
  4122. if (isFn)
  4123. handler.apply(self, args);
  4124. else {
  4125. var len = handler.length;
  4126. var listeners = arrayClone(handler, len);
  4127. for (var i = 0; i < len; ++i)
  4128. listeners[i].apply(self, args);
  4129. }
  4130. }
  4131. EventEmitter.prototype.emit = function emit(type) {
  4132. var er, handler, len, args, i, events;
  4133. var doError = (type === 'error');
  4134. events = this._events;
  4135. if (events)
  4136. doError = (doError && events.error == null);
  4137. else if (!doError)
  4138. return false;
  4139. // If there is no 'error' event listener then throw.
  4140. if (doError) {
  4141. if (arguments.length > 1)
  4142. er = arguments[1];
  4143. if (er instanceof Error) {
  4144. throw er; // Unhandled 'error' event
  4145. } else {
  4146. // At least give some kind of context to the user
  4147. var err = new Error('Unhandled "error" event. (' + er + ')');
  4148. err.context = er;
  4149. throw err;
  4150. }
  4151. return false;
  4152. }
  4153. handler = events[type];
  4154. if (!handler)
  4155. return false;
  4156. var isFn = typeof handler === 'function';
  4157. len = arguments.length;
  4158. switch (len) {
  4159. // fast cases
  4160. case 1:
  4161. emitNone(handler, isFn, this);
  4162. break;
  4163. case 2:
  4164. emitOne(handler, isFn, this, arguments[1]);
  4165. break;
  4166. case 3:
  4167. emitTwo(handler, isFn, this, arguments[1], arguments[2]);
  4168. break;
  4169. case 4:
  4170. emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
  4171. break;
  4172. // slower
  4173. default:
  4174. args = new Array(len - 1);
  4175. for (i = 1; i < len; i++)
  4176. args[i - 1] = arguments[i];
  4177. emitMany(handler, isFn, this, args);
  4178. }
  4179. return true;
  4180. };
  4181. function _addListener(target, type, listener, prepend) {
  4182. var m;
  4183. var events;
  4184. var existing;
  4185. if (typeof listener !== 'function')
  4186. throw new TypeError('"listener" argument must be a function');
  4187. events = target._events;
  4188. if (!events) {
  4189. events = target._events = objectCreate(null);
  4190. target._eventsCount = 0;
  4191. } else {
  4192. // To avoid recursion in the case that type === "newListener"! Before
  4193. // adding it to the listeners, first emit "newListener".
  4194. if (events.newListener) {
  4195. target.emit('newListener', type,
  4196. listener.listener ? listener.listener : listener);
  4197. // Re-assign `events` because a newListener handler could have caused the
  4198. // this._events to be assigned to a new object
  4199. events = target._events;
  4200. }
  4201. existing = events[type];
  4202. }
  4203. if (!existing) {
  4204. // Optimize the case of one listener. Don't need the extra array object.
  4205. existing = events[type] = listener;
  4206. ++target._eventsCount;
  4207. } else {
  4208. if (typeof existing === 'function') {
  4209. // Adding the second element, need to change to array.
  4210. existing = events[type] =
  4211. prepend ? [listener, existing] : [existing, listener];
  4212. } else {
  4213. // If we've already got an array, just append.
  4214. if (prepend) {
  4215. existing.unshift(listener);
  4216. } else {
  4217. existing.push(listener);
  4218. }
  4219. }
  4220. // Check for listener leak
  4221. if (!existing.warned) {
  4222. m = $getMaxListeners(target);
  4223. if (m && m > 0 && existing.length > m) {
  4224. existing.warned = true;
  4225. var w = new Error('Possible EventEmitter memory leak detected. ' +
  4226. existing.length + ' "' + String(type) + '" listeners ' +
  4227. 'added. Use emitter.setMaxListeners() to ' +
  4228. 'increase limit.');
  4229. w.name = 'MaxListenersExceededWarning';
  4230. w.emitter = target;
  4231. w.type = type;
  4232. w.count = existing.length;
  4233. if (typeof console === 'object' && console.warn) {
  4234. console.warn('%s: %s', w.name, w.message);
  4235. }
  4236. }
  4237. }
  4238. }
  4239. return target;
  4240. }
  4241. EventEmitter.prototype.addListener = function addListener(type, listener) {
  4242. return _addListener(this, type, listener, false);
  4243. };
  4244. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  4245. EventEmitter.prototype.prependListener =
  4246. function prependListener(type, listener) {
  4247. return _addListener(this, type, listener, true);
  4248. };
  4249. function onceWrapper() {
  4250. if (!this.fired) {
  4251. this.target.removeListener(this.type, this.wrapFn);
  4252. this.fired = true;
  4253. switch (arguments.length) {
  4254. case 0:
  4255. return this.listener.call(this.target);
  4256. case 1:
  4257. return this.listener.call(this.target, arguments[0]);
  4258. case 2:
  4259. return this.listener.call(this.target, arguments[0], arguments[1]);
  4260. case 3:
  4261. return this.listener.call(this.target, arguments[0], arguments[1],
  4262. arguments[2]);
  4263. default:
  4264. var args = new Array(arguments.length);
  4265. for (var i = 0; i < args.length; ++i)
  4266. args[i] = arguments[i];
  4267. this.listener.apply(this.target, args);
  4268. }
  4269. }
  4270. }
  4271. function _onceWrap(target, type, listener) {
  4272. var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  4273. var wrapped = bind.call(onceWrapper, state);
  4274. wrapped.listener = listener;
  4275. state.wrapFn = wrapped;
  4276. return wrapped;
  4277. }
  4278. EventEmitter.prototype.once = function once(type, listener) {
  4279. if (typeof listener !== 'function')
  4280. throw new TypeError('"listener" argument must be a function');
  4281. this.on(type, _onceWrap(this, type, listener));
  4282. return this;
  4283. };
  4284. EventEmitter.prototype.prependOnceListener =
  4285. function prependOnceListener(type, listener) {
  4286. if (typeof listener !== 'function')
  4287. throw new TypeError('"listener" argument must be a function');
  4288. this.prependListener(type, _onceWrap(this, type, listener));
  4289. return this;
  4290. };
  4291. // Emits a 'removeListener' event if and only if the listener was removed.
  4292. EventEmitter.prototype.removeListener =
  4293. function removeListener(type, listener) {
  4294. var list, events, position, i, originalListener;
  4295. if (typeof listener !== 'function')
  4296. throw new TypeError('"listener" argument must be a function');
  4297. events = this._events;
  4298. if (!events)
  4299. return this;
  4300. list = events[type];
  4301. if (!list)
  4302. return this;
  4303. if (list === listener || list.listener === listener) {
  4304. if (--this._eventsCount === 0)
  4305. this._events = objectCreate(null);
  4306. else {
  4307. delete events[type];
  4308. if (events.removeListener)
  4309. this.emit('removeListener', type, list.listener || listener);
  4310. }
  4311. } else if (typeof list !== 'function') {
  4312. position = -1;
  4313. for (i = list.length - 1; i >= 0; i--) {
  4314. if (list[i] === listener || list[i].listener === listener) {
  4315. originalListener = list[i].listener;
  4316. position = i;
  4317. break;
  4318. }
  4319. }
  4320. if (position < 0)
  4321. return this;
  4322. if (position === 0)
  4323. list.shift();
  4324. else
  4325. spliceOne(list, position);
  4326. if (list.length === 1)
  4327. events[type] = list[0];
  4328. if (events.removeListener)
  4329. this.emit('removeListener', type, originalListener || listener);
  4330. }
  4331. return this;
  4332. };
  4333. EventEmitter.prototype.removeAllListeners =
  4334. function removeAllListeners(type) {
  4335. var listeners, events, i;
  4336. events = this._events;
  4337. if (!events)
  4338. return this;
  4339. // not listening for removeListener, no need to emit
  4340. if (!events.removeListener) {
  4341. if (arguments.length === 0) {
  4342. this._events = objectCreate(null);
  4343. this._eventsCount = 0;
  4344. } else if (events[type]) {
  4345. if (--this._eventsCount === 0)
  4346. this._events = objectCreate(null);
  4347. else
  4348. delete events[type];
  4349. }
  4350. return this;
  4351. }
  4352. // emit removeListener for all listeners on all events
  4353. if (arguments.length === 0) {
  4354. var keys = objectKeys(events);
  4355. var key;
  4356. for (i = 0; i < keys.length; ++i) {
  4357. key = keys[i];
  4358. if (key === 'removeListener') continue;
  4359. this.removeAllListeners(key);
  4360. }
  4361. this.removeAllListeners('removeListener');
  4362. this._events = objectCreate(null);
  4363. this._eventsCount = 0;
  4364. return this;
  4365. }
  4366. listeners = events[type];
  4367. if (typeof listeners === 'function') {
  4368. this.removeListener(type, listeners);
  4369. } else if (listeners) {
  4370. // LIFO order
  4371. for (i = listeners.length - 1; i >= 0; i--) {
  4372. this.removeListener(type, listeners[i]);
  4373. }
  4374. }
  4375. return this;
  4376. };
  4377. function _listeners(target, type, unwrap) {
  4378. var events = target._events;
  4379. if (!events)
  4380. return [];
  4381. var evlistener = events[type];
  4382. if (!evlistener)
  4383. return [];
  4384. if (typeof evlistener === 'function')
  4385. return unwrap ? [evlistener.listener || evlistener] : [evlistener];
  4386. return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
  4387. }
  4388. EventEmitter.prototype.listeners = function listeners(type) {
  4389. return _listeners(this, type, true);
  4390. };
  4391. EventEmitter.prototype.rawListeners = function rawListeners(type) {
  4392. return _listeners(this, type, false);
  4393. };
  4394. EventEmitter.listenerCount = function(emitter, type) {
  4395. if (typeof emitter.listenerCount === 'function') {
  4396. return emitter.listenerCount(type);
  4397. } else {
  4398. return listenerCount.call(emitter, type);
  4399. }
  4400. };
  4401. EventEmitter.prototype.listenerCount = listenerCount;
  4402. function listenerCount(type) {
  4403. var events = this._events;
  4404. if (events) {
  4405. var evlistener = events[type];
  4406. if (typeof evlistener === 'function') {
  4407. return 1;
  4408. } else if (evlistener) {
  4409. return evlistener.length;
  4410. }
  4411. }
  4412. return 0;
  4413. }
  4414. EventEmitter.prototype.eventNames = function eventNames() {
  4415. return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
  4416. };
  4417. // About 1.5x faster than the two-arg version of Array#splice().
  4418. function spliceOne(list, index) {
  4419. for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
  4420. list[i] = list[k];
  4421. list.pop();
  4422. }
  4423. function arrayClone(arr, n) {
  4424. var copy = new Array(n);
  4425. for (var i = 0; i < n; ++i)
  4426. copy[i] = arr[i];
  4427. return copy;
  4428. }
  4429. function unwrapListeners(arr) {
  4430. var ret = new Array(arr.length);
  4431. for (var i = 0; i < ret.length; ++i) {
  4432. ret[i] = arr[i].listener || arr[i];
  4433. }
  4434. return ret;
  4435. }
  4436. function objectCreatePolyfill(proto) {
  4437. var F = function() {};
  4438. F.prototype = proto;
  4439. return new F;
  4440. }
  4441. function objectKeysPolyfill(obj) {
  4442. var keys = [];
  4443. for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
  4444. keys.push(k);
  4445. }
  4446. return k;
  4447. }
  4448. function functionBindPolyfill(context) {
  4449. var fn = this;
  4450. return function () {
  4451. return fn.apply(context, arguments);
  4452. };
  4453. }
  4454. },{}],22:[function(require,module,exports){
  4455. 'use strict';
  4456. var hasOwn = Object.prototype.hasOwnProperty;
  4457. var toStr = Object.prototype.toString;
  4458. var defineProperty = Object.defineProperty;
  4459. var gOPD = Object.getOwnPropertyDescriptor;
  4460. var isArray = function isArray(arr) {
  4461. if (typeof Array.isArray === 'function') {
  4462. return Array.isArray(arr);
  4463. }
  4464. return toStr.call(arr) === '[object Array]';
  4465. };
  4466. var isPlainObject = function isPlainObject(obj) {
  4467. if (!obj || toStr.call(obj) !== '[object Object]') {
  4468. return false;
  4469. }
  4470. var hasOwnConstructor = hasOwn.call(obj, 'constructor');
  4471. var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
  4472. // Not own constructor property must be Object
  4473. if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
  4474. return false;
  4475. }
  4476. // Own properties are enumerated firstly, so to speed up,
  4477. // if last one is own, then all properties are own.
  4478. var key;
  4479. for (key in obj) { /**/ }
  4480. return typeof key === 'undefined' || hasOwn.call(obj, key);
  4481. };
  4482. // If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target
  4483. var setProperty = function setProperty(target, options) {
  4484. if (defineProperty && options.name === '__proto__') {
  4485. defineProperty(target, options.name, {
  4486. enumerable: true,
  4487. configurable: true,
  4488. value: options.newValue,
  4489. writable: true
  4490. });
  4491. } else {
  4492. target[options.name] = options.newValue;
  4493. }
  4494. };
  4495. // Return undefined instead of __proto__ if '__proto__' is not an own property
  4496. var getProperty = function getProperty(obj, name) {
  4497. if (name === '__proto__') {
  4498. if (!hasOwn.call(obj, name)) {
  4499. return void 0;
  4500. } else if (gOPD) {
  4501. // In early versions of node, obj['__proto__'] is buggy when obj has
  4502. // __proto__ as an own property. Object.getOwnPropertyDescriptor() works.
  4503. return gOPD(obj, name).value;
  4504. }
  4505. }
  4506. return obj[name];
  4507. };
  4508. module.exports = function extend() {
  4509. var options, name, src, copy, copyIsArray, clone;
  4510. var target = arguments[0];
  4511. var i = 1;
  4512. var length = arguments.length;
  4513. var deep = false;
  4514. // Handle a deep copy situation
  4515. if (typeof target === 'boolean') {
  4516. deep = target;
  4517. target = arguments[1] || {};
  4518. // skip the boolean and the target
  4519. i = 2;
  4520. }
  4521. if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {
  4522. target = {};
  4523. }
  4524. for (; i < length; ++i) {
  4525. options = arguments[i];
  4526. // Only deal with non-null/undefined values
  4527. if (options != null) {
  4528. // Extend the base object
  4529. for (name in options) {
  4530. src = getProperty(target, name);
  4531. copy = getProperty(options, name);
  4532. // Prevent never-ending loop
  4533. if (target !== copy) {
  4534. // Recurse if we're merging plain objects or arrays
  4535. if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
  4536. if (copyIsArray) {
  4537. copyIsArray = false;
  4538. clone = src && isArray(src) ? src : [];
  4539. } else {
  4540. clone = src && isPlainObject(src) ? src : {};
  4541. }
  4542. // Never move original objects, clone them
  4543. setProperty(target, { name: name, newValue: extend(deep, clone, copy) });
  4544. // Don't bring in undefined values
  4545. } else if (typeof copy !== 'undefined') {
  4546. setProperty(target, { name: name, newValue: copy });
  4547. }
  4548. }
  4549. }
  4550. }
  4551. }
  4552. // Return the modified object
  4553. return target;
  4554. };
  4555. },{}],23:[function(require,module,exports){
  4556. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  4557. var e, m
  4558. var eLen = (nBytes * 8) - mLen - 1
  4559. var eMax = (1 << eLen) - 1
  4560. var eBias = eMax >> 1
  4561. var nBits = -7
  4562. var i = isLE ? (nBytes - 1) : 0
  4563. var d = isLE ? -1 : 1
  4564. var s = buffer[offset + i]
  4565. i += d
  4566. e = s & ((1 << (-nBits)) - 1)
  4567. s >>= (-nBits)
  4568. nBits += eLen
  4569. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  4570. m = e & ((1 << (-nBits)) - 1)
  4571. e >>= (-nBits)
  4572. nBits += mLen
  4573. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  4574. if (e === 0) {
  4575. e = 1 - eBias
  4576. } else if (e === eMax) {
  4577. return m ? NaN : ((s ? -1 : 1) * Infinity)
  4578. } else {
  4579. m = m + Math.pow(2, mLen)
  4580. e = e - eBias
  4581. }
  4582. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  4583. }
  4584. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  4585. var e, m, c
  4586. var eLen = (nBytes * 8) - mLen - 1
  4587. var eMax = (1 << eLen) - 1
  4588. var eBias = eMax >> 1
  4589. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  4590. var i = isLE ? 0 : (nBytes - 1)
  4591. var d = isLE ? 1 : -1
  4592. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  4593. value = Math.abs(value)
  4594. if (isNaN(value) || value === Infinity) {
  4595. m = isNaN(value) ? 1 : 0
  4596. e = eMax
  4597. } else {
  4598. e = Math.floor(Math.log(value) / Math.LN2)
  4599. if (value * (c = Math.pow(2, -e)) < 1) {
  4600. e--
  4601. c *= 2
  4602. }
  4603. if (e + eBias >= 1) {
  4604. value += rt / c
  4605. } else {
  4606. value += rt * Math.pow(2, 1 - eBias)
  4607. }
  4608. if (value * c >= 2) {
  4609. e++
  4610. c /= 2
  4611. }
  4612. if (e + eBias >= eMax) {
  4613. m = 0
  4614. e = eMax
  4615. } else if (e + eBias >= 1) {
  4616. m = ((value * c) - 1) * Math.pow(2, mLen)
  4617. e = e + eBias
  4618. } else {
  4619. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  4620. e = 0
  4621. }
  4622. }
  4623. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  4624. e = (e << mLen) | m
  4625. eLen += mLen
  4626. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  4627. buffer[offset + i - d] |= s * 128
  4628. }
  4629. },{}],24:[function(require,module,exports){
  4630. /*!
  4631. * Determine if an object is a Buffer
  4632. *
  4633. * @author Feross Aboukhadijeh <https://feross.org>
  4634. * @license MIT
  4635. */
  4636. // The _isBuffer check is for Safari 5-7 support, because it's missing
  4637. // Object.prototype.constructor. Remove this eventually
  4638. module.exports = function (obj) {
  4639. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  4640. }
  4641. function isBuffer (obj) {
  4642. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  4643. }
  4644. // For Node v0.10 support. Remove this eventually.
  4645. function isSlowBuffer (obj) {
  4646. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  4647. }
  4648. },{}],25:[function(require,module,exports){
  4649. var toString = {}.toString;
  4650. module.exports = Array.isArray || function (arr) {
  4651. return toString.call(arr) == '[object Array]';
  4652. };
  4653. },{}],26:[function(require,module,exports){
  4654. var Buffer = require('buffer').Buffer;
  4655. module.exports = isBuffer;
  4656. function isBuffer (o) {
  4657. return Buffer.isBuffer(o)
  4658. || /\[object (.+Array|Array.+)\]/.test(Object.prototype.toString.call(o));
  4659. }
  4660. },{"buffer":17}],27:[function(require,module,exports){
  4661. /* Autogenerated with Kurento Idl */
  4662. /*
  4663. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  4664. *
  4665. * Licensed under the Apache License, Version 2.0 (the "License");
  4666. * you may not use this file except in compliance with the License.
  4667. * You may obtain a copy of the License at
  4668. *
  4669. * http://www.apache.org/licenses/LICENSE-2.0
  4670. *
  4671. * Unless required by applicable law or agreed to in writing, software
  4672. * distributed under the License is distributed on an "AS IS" BASIS,
  4673. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4674. * See the License for the specific language governing permissions and
  4675. * limitations under the License.
  4676. */
  4677. var inherits = require('inherits');
  4678. var kurentoClient = require('kurento-client');
  4679. var disguise = kurentoClient.disguise;
  4680. var ChecktypeError = kurentoClient.checkType.ChecktypeError;
  4681. var MediaElement = require('./abstracts/MediaElement');
  4682. /**
  4683. * Creates a {@link module:core.HubPort HubPort} for the given {@link
  4684. * module:core/abstracts.Hub Hub}
  4685. *
  4686. * @classdesc
  4687. * This {@link module:core/abstracts.MediaElement MediaElement} specifies a
  4688. * connection with a {@link module:core/abstracts.Hub Hub}
  4689. *
  4690. * @extends module:core/abstracts.MediaElement
  4691. *
  4692. * @constructor module:core.HubPort
  4693. */
  4694. function HubPort(){
  4695. HubPort.super_.call(this);
  4696. };
  4697. inherits(HubPort, MediaElement);
  4698. /**
  4699. * @alias module:core.HubPort.constructorParams
  4700. *
  4701. * @property {module:core/abstracts.Hub} hub
  4702. * {@link module:core/abstracts.Hub Hub} to which this port belongs
  4703. */
  4704. HubPort.constructorParams = {
  4705. hub: {
  4706. type: 'kurento.Hub',
  4707. required: true
  4708. }
  4709. };
  4710. /**
  4711. * @alias module:core.HubPort.events
  4712. *
  4713. * @extends module:core/abstracts.MediaElement.events
  4714. */
  4715. HubPort.events = MediaElement.events;
  4716. /**
  4717. * Checker for {@link module:core.HubPort}
  4718. *
  4719. * @memberof module:core
  4720. *
  4721. * @param {external:String} key
  4722. * @param {module:core.HubPort} value
  4723. */
  4724. function checkHubPort(key, value)
  4725. {
  4726. if(!(value instanceof HubPort))
  4727. throw ChecktypeError(key, HubPort, value);
  4728. };
  4729. module.exports = HubPort;
  4730. HubPort.check = checkHubPort;
  4731. },{"./abstracts/MediaElement":34,"inherits":"inherits","kurento-client":"kurento-client"}],28:[function(require,module,exports){
  4732. /* Autogenerated with Kurento Idl */
  4733. /*
  4734. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  4735. *
  4736. * Licensed under the Apache License, Version 2.0 (the "License");
  4737. * you may not use this file except in compliance with the License.
  4738. * You may obtain a copy of the License at
  4739. *
  4740. * http://www.apache.org/licenses/LICENSE-2.0
  4741. *
  4742. * Unless required by applicable law or agreed to in writing, software
  4743. * distributed under the License is distributed on an "AS IS" BASIS,
  4744. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4745. * See the License for the specific language governing permissions and
  4746. * limitations under the License.
  4747. */
  4748. var inherits = require('inherits');
  4749. var kurentoClient = require('kurento-client');
  4750. var disguise = kurentoClient.disguise;
  4751. var checkType = kurentoClient.checkType;
  4752. var ChecktypeError = checkType.ChecktypeError;
  4753. var Transaction = kurentoClient.TransactionsManager.Transaction;
  4754. var MediaObjectCreator = kurentoClient.MediaObjectCreator;
  4755. var TransactionsManager = kurentoClient.TransactionsManager;
  4756. var transactionOperation = TransactionsManager.transactionOperation;
  4757. var MediaObject = require('./abstracts/MediaObject');
  4758. function noop(error, result) {
  4759. if (error) console.trace(error);
  4760. return result
  4761. };
  4762. /**
  4763. * Create a {@link module:core.MediaPipeline MediaPipeline}
  4764. *
  4765. * @classdesc
  4766. * A pipeline is a container for a collection of {@link
  4767. * module:core/abstracts.MediaElement MediaElements} and
  4768. * :rom:cls:`MediaMixers<MediaMixer>`.
  4769. * It offers the methods needed to control the creation and connection of
  4770. * elements inside a certain pipeline.
  4771. *
  4772. * @extends module:core/abstracts.MediaObject
  4773. *
  4774. * @constructor module:core.MediaPipeline
  4775. */
  4776. function MediaPipeline(strict){
  4777. MediaPipeline.super_.call(this);
  4778. var self = this;
  4779. // Transactional API
  4780. var transactionsManager = new TransactionsManager(this, encodeTransaction);
  4781. this.beginTransaction = transactionsManager.beginTransaction.bind(transactionsManager);
  4782. this.endTransaction = transactionsManager.endTransaction.bind(transactionsManager);
  4783. this.transaction = transactionsManager.transaction.bind(transactionsManager);
  4784. // Encode commands
  4785. function encodeCreate(transaction, params, callback)
  4786. {
  4787. if(transaction)
  4788. return transactionOperation.call(transaction, 'create', params, callback);
  4789. if(transactionsManager.length)
  4790. return transactionOperation.call(transactionsManager, 'create', params, callback);
  4791. self.emit('_create', undefined, params, callback)
  4792. }
  4793. function encodeRpc(transaction, method, params, callback)
  4794. {
  4795. if(transaction)
  4796. return transactionOperation.call(transaction, method, params, callback);
  4797. if(transactionsManager.length)
  4798. return transactionOperation.call(transactionsManager, method, params, callback);
  4799. self.emit('_rpc', undefined, method, params, callback)
  4800. }
  4801. function encodeTransaction(operations, callback)
  4802. {
  4803. var params =
  4804. {
  4805. // object: self,
  4806. operations: operations
  4807. };
  4808. if(transactionsManager.length)
  4809. return transactionOperation.call(transactionsManager, 'transaction', params, callback);
  4810. self.emit('_transaction', params, callback);
  4811. }
  4812. var describe = this.emit.bind(this, '_describe');
  4813. // Creation of objects
  4814. var mediaObjectCreator = new MediaObjectCreator(this, encodeCreate, encodeRpc,
  4815. encodeTransaction, describe, strict);
  4816. /**
  4817. * Create a new instance of a {module:core/abstract.MediaObject} attached to
  4818. * this {module:core.MediaPipeline}
  4819. *
  4820. * @param {external:String} type - Type of the
  4821. * {module:core/abstract.MediaObject}
  4822. * @param {external:String[]} [params]
  4823. * @param {module:core.MediaPipeline~createCallback} callback
  4824. *
  4825. * @return {external:Promise}
  4826. */
  4827. this.create = mediaObjectCreator.create.bind(mediaObjectCreator);
  4828. /**
  4829. * @callback core.MediaPipeline~createCallback
  4830. * @param {external:Error} error
  4831. * @param {module:core/abstract~MediaElement} result
  4832. * The created MediaElement
  4833. */
  4834. };
  4835. inherits(MediaPipeline, MediaObject);
  4836. //
  4837. // Public properties
  4838. //
  4839. /**
  4840. * If statistics about pipeline latency are enabled for all mediaElements
  4841. *
  4842. * @alias module:core.MediaPipeline#getLatencyStats
  4843. *
  4844. * @param {module:core.MediaPipeline~getLatencyStatsCallback} [callback]
  4845. *
  4846. * @return {external:Promise}
  4847. */
  4848. MediaPipeline.prototype.getLatencyStats = function(callback){
  4849. var transaction = (arguments[0] instanceof Transaction)
  4850. ? Array.prototype.shift.apply(arguments)
  4851. : undefined;
  4852. var usePromise = false;
  4853. if (callback == undefined) {
  4854. usePromise = true;
  4855. }
  4856. if(!arguments.length) callback = undefined;
  4857. callback = (callback || noop).bind(this)
  4858. return disguise(this._invoke(transaction, 'getLatencyStats', callback), this)
  4859. };
  4860. /**
  4861. * @callback module:core.MediaPipeline~getLatencyStatsCallback
  4862. * @param {external:Error} error
  4863. * @param {external:Boolean} result
  4864. */
  4865. /**
  4866. * If statistics about pipeline latency are enabled for all mediaElements
  4867. *
  4868. * @alias module:core.MediaPipeline#setLatencyStats
  4869. *
  4870. * @param {external:Boolean} latencyStats
  4871. * @param {module:core.MediaPipeline~setLatencyStatsCallback} [callback]
  4872. *
  4873. * @return {external:Promise}
  4874. */
  4875. MediaPipeline.prototype.setLatencyStats = function(latencyStats, callback){
  4876. var transaction = (arguments[0] instanceof Transaction)
  4877. ? Array.prototype.shift.apply(arguments)
  4878. : undefined;
  4879. //
  4880. // checkType('boolean', 'latencyStats', latencyStats, {required: true});
  4881. //
  4882. var params = {
  4883. latencyStats: latencyStats
  4884. };
  4885. callback = (callback || noop).bind(this)
  4886. return disguise(this._invoke(transaction, 'setLatencyStats', params, callback), this)
  4887. };
  4888. /**
  4889. * @callback module:core.MediaPipeline~setLatencyStatsCallback
  4890. * @param {external:Error} error
  4891. */
  4892. //
  4893. // Public methods
  4894. //
  4895. /**
  4896. * Returns a string in dot (graphviz) format that represents the gstreamer
  4897. * elements inside the pipeline
  4898. *
  4899. * @alias module:core.MediaPipeline.getGstreamerDot
  4900. *
  4901. * @param {module:core/complexTypes.GstreamerDotDetails} [details]
  4902. * Details of graph
  4903. *
  4904. * @param {module:core.MediaPipeline~getGstreamerDotCallback} [callback]
  4905. *
  4906. * @return {external:Promise}
  4907. */
  4908. MediaPipeline.prototype.getGstreamerDot = function(details, callback){
  4909. var transaction = (arguments[0] instanceof Transaction)
  4910. ? Array.prototype.shift.apply(arguments)
  4911. : undefined;
  4912. callback = arguments[arguments.length-1] instanceof Function
  4913. ? Array.prototype.pop.call(arguments)
  4914. : undefined;
  4915. switch(arguments.length){
  4916. case 0: details = undefined;
  4917. break;
  4918. case 1:
  4919. break;
  4920. default:
  4921. var error = new RangeError('Number of params ('+arguments.length+') not in range [0-1]');
  4922. error.length = arguments.length;
  4923. error.min = 0;
  4924. error.max = 1;
  4925. throw error;
  4926. }
  4927. //
  4928. // checkType('GstreamerDotDetails', 'details', details);
  4929. //
  4930. var params = {
  4931. details: details
  4932. };
  4933. callback = (callback || noop).bind(this)
  4934. return disguise(this._invoke(transaction, 'getGstreamerDot', params, callback), this)
  4935. };
  4936. /**
  4937. * @callback module:core.MediaPipeline~getGstreamerDotCallback
  4938. * @param {external:Error} error
  4939. * @param {external:String} result
  4940. * The dot graph.
  4941. */
  4942. /**
  4943. * Connect the source of a media to the sink of the next one
  4944. *
  4945. * @param {...module:core/abstract~MediaObject} media - A media to be connected
  4946. * @callback {module:MediaPipeline~connectCallback} [callback]
  4947. *
  4948. * @return {external:Promise}
  4949. *
  4950. * @throws {SyntaxError}
  4951. */
  4952. MediaPipeline.prototype.connect = function(media, callback){
  4953. // Fix lenght-variable arguments
  4954. if(!(media instanceof Array))
  4955. {
  4956. media = Array.prototype.slice.call(arguments, 0);
  4957. callback = (typeof media[media.length - 1] === 'function')
  4958. ? media.pop()
  4959. : undefined;
  4960. }
  4961. callback = (callback || noop).bind(this)
  4962. // Check if we have enought media components
  4963. if(media.length < 2)
  4964. throw new SyntaxError('Need at least two media elements to connect');
  4965. return media[0].connect(media.slice(1), callback)
  4966. };
  4967. /**
  4968. * @callback MediaPipeline~connectCallback
  4969. * @param {external:Error} error
  4970. */
  4971. /**
  4972. * @alias module:core.MediaPipeline.constructorParams
  4973. */
  4974. MediaPipeline.constructorParams = {
  4975. };
  4976. /**
  4977. * @alias module:core.MediaPipeline.events
  4978. *
  4979. * @extends module:core/abstracts.MediaObject.events
  4980. */
  4981. MediaPipeline.events = MediaObject.events;
  4982. /**
  4983. * Checker for {@link module:core.MediaPipeline}
  4984. *
  4985. * @memberof module:core
  4986. *
  4987. * @param {external:String} key
  4988. * @param {module:core.MediaPipeline} value
  4989. */
  4990. function checkMediaPipeline(key, value)
  4991. {
  4992. if(!(value instanceof MediaPipeline))
  4993. throw ChecktypeError(key, MediaPipeline, value);
  4994. };
  4995. module.exports = MediaPipeline;
  4996. MediaPipeline.check = checkMediaPipeline;
  4997. },{"./abstracts/MediaObject":35,"inherits":"inherits","kurento-client":"kurento-client"}],29:[function(require,module,exports){
  4998. /* Autogenerated with Kurento Idl */
  4999. /*
  5000. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  5001. *
  5002. * Licensed under the Apache License, Version 2.0 (the "License");
  5003. * you may not use this file except in compliance with the License.
  5004. * You may obtain a copy of the License at
  5005. *
  5006. * http://www.apache.org/licenses/LICENSE-2.0
  5007. *
  5008. * Unless required by applicable law or agreed to in writing, software
  5009. * distributed under the License is distributed on an "AS IS" BASIS,
  5010. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5011. * See the License for the specific language governing permissions and
  5012. * limitations under the License.
  5013. */
  5014. var inherits = require('inherits');
  5015. var kurentoClient = require('kurento-client');
  5016. var disguise = kurentoClient.disguise;
  5017. var ChecktypeError = kurentoClient.checkType.ChecktypeError;
  5018. var MediaElement = require('./abstracts/MediaElement');
  5019. /**
  5020. * Builder for the {@link module:core.PassThrough PassThrough}
  5021. *
  5022. * @classdesc
  5023. * This {@link module:core/abstracts.MediaElement MediaElement} that just
  5024. * passes media through
  5025. *
  5026. * @extends module:core/abstracts.MediaElement
  5027. *
  5028. * @constructor module:core.PassThrough
  5029. */
  5030. function PassThrough(){
  5031. PassThrough.super_.call(this);
  5032. };
  5033. inherits(PassThrough, MediaElement);
  5034. /**
  5035. * @alias module:core.PassThrough.constructorParams
  5036. *
  5037. * @property {module:core.MediaPipeline} mediaPipeline
  5038. * the {@link module:core.MediaPipeline MediaPipeline} to which the element
  5039. * belongs
  5040. */
  5041. PassThrough.constructorParams = {
  5042. mediaPipeline: {
  5043. type: 'kurento.MediaPipeline',
  5044. required: true
  5045. }
  5046. };
  5047. /**
  5048. * @alias module:core.PassThrough.events
  5049. *
  5050. * @extends module:core/abstracts.MediaElement.events
  5051. */
  5052. PassThrough.events = MediaElement.events;
  5053. /**
  5054. * Checker for {@link module:core.PassThrough}
  5055. *
  5056. * @memberof module:core
  5057. *
  5058. * @param {external:String} key
  5059. * @param {module:core.PassThrough} value
  5060. */
  5061. function checkPassThrough(key, value)
  5062. {
  5063. if(!(value instanceof PassThrough))
  5064. throw ChecktypeError(key, PassThrough, value);
  5065. };
  5066. module.exports = PassThrough;
  5067. PassThrough.check = checkPassThrough;
  5068. },{"./abstracts/MediaElement":34,"inherits":"inherits","kurento-client":"kurento-client"}],30:[function(require,module,exports){
  5069. /* Autogenerated with Kurento Idl */
  5070. /*
  5071. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  5072. *
  5073. * Licensed under the Apache License, Version 2.0 (the "License");
  5074. * you may not use this file except in compliance with the License.
  5075. * You may obtain a copy of the License at
  5076. *
  5077. * http://www.apache.org/licenses/LICENSE-2.0
  5078. *
  5079. * Unless required by applicable law or agreed to in writing, software
  5080. * distributed under the License is distributed on an "AS IS" BASIS,
  5081. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5082. * See the License for the specific language governing permissions and
  5083. * limitations under the License.
  5084. */
  5085. var inherits = require('inherits');
  5086. var kurentoClient = require('kurento-client');
  5087. var disguise = kurentoClient.disguise;
  5088. var checkType = kurentoClient.checkType;
  5089. var ChecktypeError = checkType.ChecktypeError;
  5090. var Transaction = kurentoClient.TransactionsManager.Transaction;
  5091. var SdpEndpoint = require('./SdpEndpoint');
  5092. function noop(error, result) {
  5093. if (error) console.trace(error);
  5094. return result
  5095. };
  5096. /**
  5097. * @classdesc
  5098. * Handles RTP communications.
  5099. * <p>
  5100. * All endpoints that rely on the RTP protocol, like the
  5101. * <strong>RtpEndpoint</strong> or the <strong>WebRtcEndpoint</strong>,
  5102. * inherit
  5103. * from this class. The endpoint provides information about the connection
  5104. * state
  5105. * and the media state, which can be consulted at any time through the
  5106. * {@link module:core/abstracts.BaseRtpEndpoint#mediaState} and the {@link
  5107. * module:core/abstracts.BaseRtpEndpoint#connectionState} properties. It is
  5108. * also possible subscribe to events fired when these properties change.
  5109. * </p>
  5110. * <ul>
  5111. * <li>
  5112. * <strong>ConnectionStateChangedEvent</strong>: This event is raised when
  5113. * the
  5114. * connection between two peers changes. It can have two values:
  5115. * <ul>
  5116. * <li>CONNECTED</li>
  5117. * <li>DISCONNECTED</li>
  5118. * </ul>
  5119. * </li>
  5120. * <li>
  5121. * <strong>MediaStateChangedEvent</strong>: This event provides information
  5122. * about the state of the underlying RTP session.
  5123. * <p>
  5124. * The standard definition of RTP (<a
  5125. * href='https://tools.ietf.org/html/rfc3550'
  5126. * target='_blank'
  5127. * >RFC 3550</a
  5128. * >) describes a session as active whenever there is a maintained flow
  5129. * of
  5130. * RTCP control packets, regardless of whether there is actual media
  5131. * flowing
  5132. * through RTP data packets or not. The reasoning behind this is that, at
  5133. * given moment, a participant of an RTP session might temporarily stop
  5134. * sending RTP data packets, but this wouldn't necessarily mean that the
  5135. * RTP
  5136. * session as a whole is finished; it maybe just means that the
  5137. * participant
  5138. * has some temporary issues but it will soon resume sending data. For
  5139. * this
  5140. * reason, that an RTP session has really finished is something that is
  5141. * considered only by the prolonged absence of RTCP control packets
  5142. * between
  5143. * participants.
  5144. * </p>
  5145. * <p>
  5146. * Since RTCP packets do not flow at a constant rate (for instance,
  5147. * minimizing a browser window with a WebRTC's
  5148. * <code>RTCPeerConnection</code> object might affect the sending
  5149. * interval),
  5150. * it is not possible to immediately detect their absence and assume that
  5151. * RTP session has finished. Instead, there is a guard period of
  5152. * approximately <strong>5 seconds</strong> of missing RTCP packets
  5153. * before
  5154. * considering that the underlying RTP session is effectively finished,
  5155. * thus
  5156. * triggering a <code>MediaStateChangedEvent = DISCONNECTED</code> event.
  5157. * </p>
  5158. * <p>
  5159. * In other words, there is always a period during which there might be
  5160. * no
  5161. * media flowing, but this event hasn't been fired yet. Nevertheless,
  5162. * this is
  5163. * the most reliable and useful way of knowing what is the long-term,
  5164. * steady
  5165. * state of RTP media exchange.
  5166. * </p>
  5167. * <p>
  5168. * The <code>ConnectionStateChangedEvent</code> comes in contrast with
  5169. * more
  5170. * instantaneous events such as MediaElement's
  5171. * {@link module:core/abstracts.BaseRtpEndpoint#MediaFlowInStateChange}
  5172. * and
  5173. * {@link module:core/abstracts.BaseRtpEndpoint#MediaFlowOutStateChange},
  5174. * immediately after the RTP data packets stop flowing between RTP
  5175. * session
  5176. * participants. This makes the <em>MediaFlow</em> events a good way to
  5177. * know if participants are suffering from short-term intermittent
  5178. * connectivity issues, but they are not enough to know if the
  5179. * connectivity
  5180. * issues are just spurious network hiccups or are part of a more
  5181. * long-term
  5182. * disconnection problem.
  5183. * </p>
  5184. * <p>
  5185. * Possible values are:
  5186. * </p>
  5187. * <ul>
  5188. * <li>CONNECTED: There is an RTCP packet flow between peers.</li>
  5189. * <li>
  5190. * DISCONNECTED: Either no RTCP packets have been received yet, or the
  5191. * remote peer has ended the RTP session with a <code>BYE</code>
  5192. * message,
  5193. * or at least 5 seconds have elapsed since the last RTCP packet was
  5194. * received.
  5195. * </li>
  5196. * </ul>
  5197. * </li>
  5198. * </ul>
  5199. * <p>
  5200. * Part of the bandwidth control for the video component of the media session
  5201. * done here:
  5202. * </p>
  5203. * <ul>
  5204. * <li>
  5205. * Input bandwidth: Configuration value used to inform remote peers about
  5206. * the
  5207. * bitrate that can be pushed into this endpoint.
  5208. * <ul>
  5209. * <li>
  5210. * <strong>{get,set}MinVideoRecvBandwidth</strong>: Minimum bitrate
  5211. * requested on the received video stream.
  5212. * </li>
  5213. * <li>
  5214. * <strong>{get,set}Max{Audio,Video}RecvBandwidth</strong>: Maximum
  5215. * bitrate
  5216. * expected for the received stream.
  5217. * </li>
  5218. * </ul>
  5219. * </li>
  5220. * <li>
  5221. * Output bandwidth: Configuration values used to control bitrate of the
  5222. * output
  5223. * video stream sent to remote peers. It is important to keep in mind that
  5224. * pushed bitrate depends on network and remote peer capabilities. Remote
  5225. * peers
  5226. * can also announce bandwidth limitation in their SDPs (through the
  5227. * <code>b={modifier}:{value}</code> tag). Kurento will always enforce
  5228. * bitrate
  5229. * limitations specified by the remote peer over internal configurations.
  5230. * <ul>
  5231. * <li>
  5232. * <strong>{get,set}MinVideoSendBandwidth</strong>: Minimum video
  5233. * bitrate
  5234. * sent to remote peer.
  5235. * </li>
  5236. * <li>
  5237. * <strong>{get,set}MaxVideoSendBandwidth</strong>: Maximum video
  5238. * bitrate
  5239. * sent to remote peer.
  5240. * </li>
  5241. * <li>
  5242. * <strong>RembParams.rembOnConnect</strong>: Initial local REMB
  5243. * bandwidth
  5244. * estimation that gets propagated when a new endpoint is connected.
  5245. * </li>
  5246. * </ul>
  5247. * </li>
  5248. * </ul>
  5249. * <p>
  5250. * <strong>
  5251. * All bandwidth control parameters must be changed before the SDP
  5252. * negotiation
  5253. * takes place, and can't be changed afterwards.
  5254. * </strong>
  5255. * </p>
  5256. *
  5257. * @abstract
  5258. * @extends module:core/abstracts.SdpEndpoint
  5259. *
  5260. * @constructor module:core/abstracts.BaseRtpEndpoint
  5261. *
  5262. * @fires {@link module:core#event:ConnectionStateChanged ConnectionStateChanged}
  5263. * @fires {@link module:core#event:MediaStateChanged MediaStateChanged}
  5264. */
  5265. function BaseRtpEndpoint(){
  5266. BaseRtpEndpoint.super_.call(this);
  5267. };
  5268. inherits(BaseRtpEndpoint, SdpEndpoint);
  5269. //
  5270. // Public properties
  5271. //
  5272. /**
  5273. * Connection state.
  5274. * <ul>
  5275. * <li>CONNECTED</li>
  5276. * <li>DISCONNECTED</li>
  5277. * </ul>
  5278. *
  5279. * @alias module:core/abstracts.BaseRtpEndpoint#getConnectionState
  5280. *
  5281. * @param {module:core/abstracts.BaseRtpEndpoint~getConnectionStateCallback} [callback]
  5282. *
  5283. * @return {external:Promise}
  5284. */
  5285. BaseRtpEndpoint.prototype.getConnectionState = function(callback){
  5286. var transaction = (arguments[0] instanceof Transaction)
  5287. ? Array.prototype.shift.apply(arguments)
  5288. : undefined;
  5289. var usePromise = false;
  5290. if (callback == undefined) {
  5291. usePromise = true;
  5292. }
  5293. if(!arguments.length) callback = undefined;
  5294. callback = (callback || noop).bind(this)
  5295. return disguise(this._invoke(transaction, 'getConnectionState', callback), this)
  5296. };
  5297. /**
  5298. * @callback module:core/abstracts.BaseRtpEndpoint~getConnectionStateCallback
  5299. * @param {external:Error} error
  5300. * @param {module:core/complexTypes.ConnectionState} result
  5301. */
  5302. /**
  5303. * Maximum video bitrate sent to remote peer.
  5304. * <p>
  5305. * With this parameter you can control the maximum video quality that will be
  5306. * sent when reacting to good network conditions. Setting this parameter to a
  5307. * high value permits the video quality to raise when the network conditions
  5308. * get
  5309. * better.
  5310. * </p>
  5311. * <p>
  5312. * This parameter provides a way to limit the bitrate requested by remote REMB
  5313. * bandwidth estimations: the bitrate sent will be always equal or less than
  5314. * this parameter, even if the remote peer requests higher bitrates.
  5315. * </p>
  5316. * <p>
  5317. * Note that the default value of <strong>500 kbps</strong> is a VERY
  5318. * conservative one, and leads to a low maximum video quality. Most
  5319. * applications
  5320. * will probably want to increase this parameter to higher values such as 2000
  5321. * mbps) or even 10000 (10 mbps).
  5322. * </p>
  5323. * <p>
  5324. * The REMB congestion control algorithm works by gradually increasing the
  5325. * output
  5326. * video bitrate, until the available bandwidth is fully used or the maximum
  5327. * send
  5328. * bitrate has been reached. This is a slow, progressive change, which starts
  5329. * at
  5330. * 300 kbps by default. You can change the default starting point of REMB
  5331. * estimations, by setting <code>RembParams.rembOnConnect</code>.
  5332. * </p>
  5333. * <ul>
  5334. * <li>Unit: kbps (kilobits per second).</li>
  5335. * <li>Default: 500.</li>
  5336. * <li>
  5337. * 0 = unconstrained: the video bitrate will grow until all the available
  5338. * network bandwidth is used by the stream.<br />
  5339. * Note that this might have a bad effect if more than one stream is running
  5340. * (as all of them would try to raise the video bitrate indefinitely, until
  5341. * the
  5342. * network gets saturated).
  5343. * </li>
  5344. * </ul>
  5345. *
  5346. * @alias module:core/abstracts.BaseRtpEndpoint#getMaxVideoSendBandwidth
  5347. *
  5348. * @param {module:core/abstracts.BaseRtpEndpoint~getMaxVideoSendBandwidthCallback} [callback]
  5349. *
  5350. * @return {external:Promise}
  5351. */
  5352. BaseRtpEndpoint.prototype.getMaxVideoSendBandwidth = function(callback){
  5353. var transaction = (arguments[0] instanceof Transaction)
  5354. ? Array.prototype.shift.apply(arguments)
  5355. : undefined;
  5356. var usePromise = false;
  5357. if (callback == undefined) {
  5358. usePromise = true;
  5359. }
  5360. if(!arguments.length) callback = undefined;
  5361. callback = (callback || noop).bind(this)
  5362. return disguise(this._invoke(transaction, 'getMaxVideoSendBandwidth', callback), this)
  5363. };
  5364. /**
  5365. * @callback module:core/abstracts.BaseRtpEndpoint~getMaxVideoSendBandwidthCallback
  5366. * @param {external:Error} error
  5367. * @param {external:Integer} result
  5368. */
  5369. /**
  5370. * Maximum video bitrate sent to remote peer.
  5371. * <p>
  5372. * With this parameter you can control the maximum video quality that will be
  5373. * sent when reacting to good network conditions. Setting this parameter to a
  5374. * high value permits the video quality to raise when the network conditions
  5375. * get
  5376. * better.
  5377. * </p>
  5378. * <p>
  5379. * This parameter provides a way to limit the bitrate requested by remote REMB
  5380. * bandwidth estimations: the bitrate sent will be always equal or less than
  5381. * this parameter, even if the remote peer requests higher bitrates.
  5382. * </p>
  5383. * <p>
  5384. * Note that the default value of <strong>500 kbps</strong> is a VERY
  5385. * conservative one, and leads to a low maximum video quality. Most
  5386. * applications
  5387. * will probably want to increase this parameter to higher values such as 2000
  5388. * mbps) or even 10000 (10 mbps).
  5389. * </p>
  5390. * <p>
  5391. * The REMB congestion control algorithm works by gradually increasing the
  5392. * output
  5393. * video bitrate, until the available bandwidth is fully used or the maximum
  5394. * send
  5395. * bitrate has been reached. This is a slow, progressive change, which starts
  5396. * at
  5397. * 300 kbps by default. You can change the default starting point of REMB
  5398. * estimations, by setting <code>RembParams.rembOnConnect</code>.
  5399. * </p>
  5400. * <ul>
  5401. * <li>Unit: kbps (kilobits per second).</li>
  5402. * <li>Default: 500.</li>
  5403. * <li>
  5404. * 0 = unconstrained: the video bitrate will grow until all the available
  5405. * network bandwidth is used by the stream.<br />
  5406. * Note that this might have a bad effect if more than one stream is running
  5407. * (as all of them would try to raise the video bitrate indefinitely, until
  5408. * the
  5409. * network gets saturated).
  5410. * </li>
  5411. * </ul>
  5412. *
  5413. * @alias module:core/abstracts.BaseRtpEndpoint#setMaxVideoSendBandwidth
  5414. *
  5415. * @param {external:Integer} maxVideoSendBandwidth
  5416. * @param {module:core/abstracts.BaseRtpEndpoint~setMaxVideoSendBandwidthCallback} [callback]
  5417. *
  5418. * @return {external:Promise}
  5419. */
  5420. BaseRtpEndpoint.prototype.setMaxVideoSendBandwidth = function(maxVideoSendBandwidth, callback){
  5421. var transaction = (arguments[0] instanceof Transaction)
  5422. ? Array.prototype.shift.apply(arguments)
  5423. : undefined;
  5424. //
  5425. // checkType('int', 'maxVideoSendBandwidth', maxVideoSendBandwidth, {required: true});
  5426. //
  5427. var params = {
  5428. maxVideoSendBandwidth: maxVideoSendBandwidth
  5429. };
  5430. callback = (callback || noop).bind(this)
  5431. return disguise(this._invoke(transaction, 'setMaxVideoSendBandwidth', params, callback), this)
  5432. };
  5433. /**
  5434. * @callback module:core/abstracts.BaseRtpEndpoint~setMaxVideoSendBandwidthCallback
  5435. * @param {external:Error} error
  5436. */
  5437. /**
  5438. * Media flow state.
  5439. * <ul>
  5440. * <li>CONNECTED: There is an RTCP flow.</li>
  5441. * <li>DISCONNECTED: No RTCP packets have been received for at least 5
  5442. * sec.</li>
  5443. * </ul>
  5444. *
  5445. * @alias module:core/abstracts.BaseRtpEndpoint#getMediaState
  5446. *
  5447. * @param {module:core/abstracts.BaseRtpEndpoint~getMediaStateCallback} [callback]
  5448. *
  5449. * @return {external:Promise}
  5450. */
  5451. BaseRtpEndpoint.prototype.getMediaState = function(callback){
  5452. var transaction = (arguments[0] instanceof Transaction)
  5453. ? Array.prototype.shift.apply(arguments)
  5454. : undefined;
  5455. var usePromise = false;
  5456. if (callback == undefined) {
  5457. usePromise = true;
  5458. }
  5459. if(!arguments.length) callback = undefined;
  5460. callback = (callback || noop).bind(this)
  5461. return disguise(this._invoke(transaction, 'getMediaState', callback), this)
  5462. };
  5463. /**
  5464. * @callback module:core/abstracts.BaseRtpEndpoint~getMediaStateCallback
  5465. * @param {external:Error} error
  5466. * @param {module:core/complexTypes.MediaState} result
  5467. */
  5468. /**
  5469. * Minimum bitrate requested on the received video stream.
  5470. * <p>
  5471. * This is used to set a minimum value of local REMB during bandwidth
  5472. * estimation,
  5473. * if supported by the implementing class. The REMB estimation will then be
  5474. * sent
  5475. * to remote peers, requesting them to send at least the indicated video
  5476. * bitrate.
  5477. * It follows that min values will only have effect in remote peers that
  5478. * support
  5479. * this congestion control mechanism, such as Chrome.
  5480. * </p>
  5481. * <ul>
  5482. * <li>Unit: kbps (kilobits per second).</li>
  5483. * <li>Default: 0.</li>
  5484. * <li>
  5485. * Note: The absolute minimum REMB value is 30 kbps, even if a lower value
  5486. * is
  5487. * set here.
  5488. * </li>
  5489. * </ul>
  5490. *
  5491. * @alias module:core/abstracts.BaseRtpEndpoint#getMinVideoRecvBandwidth
  5492. *
  5493. * @param {module:core/abstracts.BaseRtpEndpoint~getMinVideoRecvBandwidthCallback} [callback]
  5494. *
  5495. * @return {external:Promise}
  5496. */
  5497. BaseRtpEndpoint.prototype.getMinVideoRecvBandwidth = function(callback){
  5498. var transaction = (arguments[0] instanceof Transaction)
  5499. ? Array.prototype.shift.apply(arguments)
  5500. : undefined;
  5501. var usePromise = false;
  5502. if (callback == undefined) {
  5503. usePromise = true;
  5504. }
  5505. if(!arguments.length) callback = undefined;
  5506. callback = (callback || noop).bind(this)
  5507. return disguise(this._invoke(transaction, 'getMinVideoRecvBandwidth', callback), this)
  5508. };
  5509. /**
  5510. * @callback module:core/abstracts.BaseRtpEndpoint~getMinVideoRecvBandwidthCallback
  5511. * @param {external:Error} error
  5512. * @param {external:Integer} result
  5513. */
  5514. /**
  5515. * Minimum bitrate requested on the received video stream.
  5516. * <p>
  5517. * This is used to set a minimum value of local REMB during bandwidth
  5518. * estimation,
  5519. * if supported by the implementing class. The REMB estimation will then be
  5520. * sent
  5521. * to remote peers, requesting them to send at least the indicated video
  5522. * bitrate.
  5523. * It follows that min values will only have effect in remote peers that
  5524. * support
  5525. * this congestion control mechanism, such as Chrome.
  5526. * </p>
  5527. * <ul>
  5528. * <li>Unit: kbps (kilobits per second).</li>
  5529. * <li>Default: 0.</li>
  5530. * <li>
  5531. * Note: The absolute minimum REMB value is 30 kbps, even if a lower value
  5532. * is
  5533. * set here.
  5534. * </li>
  5535. * </ul>
  5536. *
  5537. * @alias module:core/abstracts.BaseRtpEndpoint#setMinVideoRecvBandwidth
  5538. *
  5539. * @param {external:Integer} minVideoRecvBandwidth
  5540. * @param {module:core/abstracts.BaseRtpEndpoint~setMinVideoRecvBandwidthCallback} [callback]
  5541. *
  5542. * @return {external:Promise}
  5543. */
  5544. BaseRtpEndpoint.prototype.setMinVideoRecvBandwidth = function(minVideoRecvBandwidth, callback){
  5545. var transaction = (arguments[0] instanceof Transaction)
  5546. ? Array.prototype.shift.apply(arguments)
  5547. : undefined;
  5548. //
  5549. // checkType('int', 'minVideoRecvBandwidth', minVideoRecvBandwidth, {required: true});
  5550. //
  5551. var params = {
  5552. minVideoRecvBandwidth: minVideoRecvBandwidth
  5553. };
  5554. callback = (callback || noop).bind(this)
  5555. return disguise(this._invoke(transaction, 'setMinVideoRecvBandwidth', params, callback), this)
  5556. };
  5557. /**
  5558. * @callback module:core/abstracts.BaseRtpEndpoint~setMinVideoRecvBandwidthCallback
  5559. * @param {external:Error} error
  5560. */
  5561. /**
  5562. * Minimum video bitrate sent to remote peer.
  5563. * <p>
  5564. * With this parameter you can control the minimum video quality that will be
  5565. * sent when reacting to bad network conditions. Setting this parameter to a
  5566. * low
  5567. * value permits the video quality to drop when the network conditions get
  5568. * worse.
  5569. * </p>
  5570. * <p>
  5571. * This parameter provides a way to override the bitrate requested by remote
  5572. * REMB
  5573. * bandwidth estimations: the bitrate sent will be always equal or greater
  5574. * than
  5575. * this parameter, even if the remote peer requests even lower bitrates.
  5576. * </p>
  5577. * <p>
  5578. * Note that if you set this parameter too high (trying to avoid bad video
  5579. * quality altogether), you would be limiting the adaptation ability of the
  5580. * congestion control algorithm, and your stream might be unable to ever
  5581. * recover
  5582. * from adverse network conditions.
  5583. * </p>
  5584. * <ul>
  5585. * <li>Unit: kbps (kilobits per second).</li>
  5586. * <li>Default: 100.</li>
  5587. * <li>
  5588. * 0 = unconstrained: the video bitrate will drop as needed, even to the
  5589. * lowest possible quality, which might make the video completely blurry and
  5590. * pixelated.
  5591. * </li>
  5592. * </ul>
  5593. *
  5594. * @alias module:core/abstracts.BaseRtpEndpoint#getMinVideoSendBandwidth
  5595. *
  5596. * @param {module:core/abstracts.BaseRtpEndpoint~getMinVideoSendBandwidthCallback} [callback]
  5597. *
  5598. * @return {external:Promise}
  5599. */
  5600. BaseRtpEndpoint.prototype.getMinVideoSendBandwidth = function(callback){
  5601. var transaction = (arguments[0] instanceof Transaction)
  5602. ? Array.prototype.shift.apply(arguments)
  5603. : undefined;
  5604. var usePromise = false;
  5605. if (callback == undefined) {
  5606. usePromise = true;
  5607. }
  5608. if(!arguments.length) callback = undefined;
  5609. callback = (callback || noop).bind(this)
  5610. return disguise(this._invoke(transaction, 'getMinVideoSendBandwidth', callback), this)
  5611. };
  5612. /**
  5613. * @callback module:core/abstracts.BaseRtpEndpoint~getMinVideoSendBandwidthCallback
  5614. * @param {external:Error} error
  5615. * @param {external:Integer} result
  5616. */
  5617. /**
  5618. * Minimum video bitrate sent to remote peer.
  5619. * <p>
  5620. * With this parameter you can control the minimum video quality that will be
  5621. * sent when reacting to bad network conditions. Setting this parameter to a
  5622. * low
  5623. * value permits the video quality to drop when the network conditions get
  5624. * worse.
  5625. * </p>
  5626. * <p>
  5627. * This parameter provides a way to override the bitrate requested by remote
  5628. * REMB
  5629. * bandwidth estimations: the bitrate sent will be always equal or greater
  5630. * than
  5631. * this parameter, even if the remote peer requests even lower bitrates.
  5632. * </p>
  5633. * <p>
  5634. * Note that if you set this parameter too high (trying to avoid bad video
  5635. * quality altogether), you would be limiting the adaptation ability of the
  5636. * congestion control algorithm, and your stream might be unable to ever
  5637. * recover
  5638. * from adverse network conditions.
  5639. * </p>
  5640. * <ul>
  5641. * <li>Unit: kbps (kilobits per second).</li>
  5642. * <li>Default: 100.</li>
  5643. * <li>
  5644. * 0 = unconstrained: the video bitrate will drop as needed, even to the
  5645. * lowest possible quality, which might make the video completely blurry and
  5646. * pixelated.
  5647. * </li>
  5648. * </ul>
  5649. *
  5650. * @alias module:core/abstracts.BaseRtpEndpoint#setMinVideoSendBandwidth
  5651. *
  5652. * @param {external:Integer} minVideoSendBandwidth
  5653. * @param {module:core/abstracts.BaseRtpEndpoint~setMinVideoSendBandwidthCallback} [callback]
  5654. *
  5655. * @return {external:Promise}
  5656. */
  5657. BaseRtpEndpoint.prototype.setMinVideoSendBandwidth = function(minVideoSendBandwidth, callback){
  5658. var transaction = (arguments[0] instanceof Transaction)
  5659. ? Array.prototype.shift.apply(arguments)
  5660. : undefined;
  5661. //
  5662. // checkType('int', 'minVideoSendBandwidth', minVideoSendBandwidth, {required: true});
  5663. //
  5664. var params = {
  5665. minVideoSendBandwidth: minVideoSendBandwidth
  5666. };
  5667. callback = (callback || noop).bind(this)
  5668. return disguise(this._invoke(transaction, 'setMinVideoSendBandwidth', params, callback), this)
  5669. };
  5670. /**
  5671. * @callback module:core/abstracts.BaseRtpEndpoint~setMinVideoSendBandwidthCallback
  5672. * @param {external:Error} error
  5673. */
  5674. /**
  5675. * Maximum Transmission Unit (MTU) used for RTP.
  5676. * <p>
  5677. * This setting affects the maximum size that will be used by RTP payloads.
  5678. * You
  5679. * can change it from the default, if you think that a different value would
  5680. * be
  5681. * beneficial for the typical network settings of your application.
  5682. * </p>
  5683. * <p>
  5684. * The default value is 1200 Bytes. This is the same as in <b>libwebrtc</b>
  5685. * (from
  5686. * webrtc.org), as used by
  5687. * <a
  5688. * href='https://dxr.mozilla.org/mozilla-central/rev/b5c5ba07d3dbd0d07b66fa42a103f4df2c27d3a2/media/webrtc/trunk/webrtc/media/engine/constants.cc#16'
  5689. * >Firefox</a
  5690. * >
  5691. * or
  5692. * <a
  5693. * href='https://codesearch.chromium.org/chromium/src/third_party/webrtc/media/engine/constants.cc?l=15&rcl=6dd488b2e55125644263e4837f1abd950d5e410d'
  5694. * >Chrome</a
  5695. * >
  5696. * . You can read more about this value in
  5697. * <a
  5698. * href='https://groups.google.com/d/topic/discuss-webrtc/gH5ysR3SoZI/discussion'
  5699. * >Why RTP max packet size is 1200 in WebRTC?</a
  5700. * >
  5701. * .
  5702. * </p>
  5703. * <p>
  5704. * <b>WARNING</b>: Change this value ONLY if you really know what you are
  5705. * doing
  5706. * and you have strong reasons to do so. Do NOT change this parameter just
  5707. * because it <i>seems</i> to work better for some reduced scope tests. The
  5708. * default value is a consensus chosen by people who have deep knowledge about
  5709. * network optimization.
  5710. * </p>
  5711. * <ul>
  5712. * <li>Unit: Bytes.</li>
  5713. * <li>Default: 1200.</li>
  5714. * </ul>
  5715. *
  5716. * @alias module:core/abstracts.BaseRtpEndpoint#getMtu
  5717. *
  5718. * @param {module:core/abstracts.BaseRtpEndpoint~getMtuCallback} [callback]
  5719. *
  5720. * @return {external:Promise}
  5721. */
  5722. BaseRtpEndpoint.prototype.getMtu = function(callback){
  5723. var transaction = (arguments[0] instanceof Transaction)
  5724. ? Array.prototype.shift.apply(arguments)
  5725. : undefined;
  5726. var usePromise = false;
  5727. if (callback == undefined) {
  5728. usePromise = true;
  5729. }
  5730. if(!arguments.length) callback = undefined;
  5731. callback = (callback || noop).bind(this)
  5732. return disguise(this._invoke(transaction, 'getMtu', callback), this)
  5733. };
  5734. /**
  5735. * @callback module:core/abstracts.BaseRtpEndpoint~getMtuCallback
  5736. * @param {external:Error} error
  5737. * @param {external:Integer} result
  5738. */
  5739. /**
  5740. * Maximum Transmission Unit (MTU) used for RTP.
  5741. * <p>
  5742. * This setting affects the maximum size that will be used by RTP payloads.
  5743. * You
  5744. * can change it from the default, if you think that a different value would
  5745. * be
  5746. * beneficial for the typical network settings of your application.
  5747. * </p>
  5748. * <p>
  5749. * The default value is 1200 Bytes. This is the same as in <b>libwebrtc</b>
  5750. * (from
  5751. * webrtc.org), as used by
  5752. * <a
  5753. * href='https://dxr.mozilla.org/mozilla-central/rev/b5c5ba07d3dbd0d07b66fa42a103f4df2c27d3a2/media/webrtc/trunk/webrtc/media/engine/constants.cc#16'
  5754. * >Firefox</a
  5755. * >
  5756. * or
  5757. * <a
  5758. * href='https://codesearch.chromium.org/chromium/src/third_party/webrtc/media/engine/constants.cc?l=15&rcl=6dd488b2e55125644263e4837f1abd950d5e410d'
  5759. * >Chrome</a
  5760. * >
  5761. * . You can read more about this value in
  5762. * <a
  5763. * href='https://groups.google.com/d/topic/discuss-webrtc/gH5ysR3SoZI/discussion'
  5764. * >Why RTP max packet size is 1200 in WebRTC?</a
  5765. * >
  5766. * .
  5767. * </p>
  5768. * <p>
  5769. * <b>WARNING</b>: Change this value ONLY if you really know what you are
  5770. * doing
  5771. * and you have strong reasons to do so. Do NOT change this parameter just
  5772. * because it <i>seems</i> to work better for some reduced scope tests. The
  5773. * default value is a consensus chosen by people who have deep knowledge about
  5774. * network optimization.
  5775. * </p>
  5776. * <ul>
  5777. * <li>Unit: Bytes.</li>
  5778. * <li>Default: 1200.</li>
  5779. * </ul>
  5780. *
  5781. * @alias module:core/abstracts.BaseRtpEndpoint#setMtu
  5782. *
  5783. * @param {external:Integer} mtu
  5784. * @param {module:core/abstracts.BaseRtpEndpoint~setMtuCallback} [callback]
  5785. *
  5786. * @return {external:Promise}
  5787. */
  5788. BaseRtpEndpoint.prototype.setMtu = function(mtu, callback){
  5789. var transaction = (arguments[0] instanceof Transaction)
  5790. ? Array.prototype.shift.apply(arguments)
  5791. : undefined;
  5792. //
  5793. // checkType('int', 'mtu', mtu, {required: true});
  5794. //
  5795. var params = {
  5796. mtu: mtu
  5797. };
  5798. callback = (callback || noop).bind(this)
  5799. return disguise(this._invoke(transaction, 'setMtu', params, callback), this)
  5800. };
  5801. /**
  5802. * @callback module:core/abstracts.BaseRtpEndpoint~setMtuCallback
  5803. * @param {external:Error} error
  5804. */
  5805. /**
  5806. * Advanced parameters to configure the congestion control algorithm.
  5807. *
  5808. * @alias module:core/abstracts.BaseRtpEndpoint#getRembParams
  5809. *
  5810. * @param {module:core/abstracts.BaseRtpEndpoint~getRembParamsCallback} [callback]
  5811. *
  5812. * @return {external:Promise}
  5813. */
  5814. BaseRtpEndpoint.prototype.getRembParams = function(callback){
  5815. var transaction = (arguments[0] instanceof Transaction)
  5816. ? Array.prototype.shift.apply(arguments)
  5817. : undefined;
  5818. var usePromise = false;
  5819. if (callback == undefined) {
  5820. usePromise = true;
  5821. }
  5822. if(!arguments.length) callback = undefined;
  5823. callback = (callback || noop).bind(this)
  5824. return disguise(this._invoke(transaction, 'getRembParams', callback), this)
  5825. };
  5826. /**
  5827. * @callback module:core/abstracts.BaseRtpEndpoint~getRembParamsCallback
  5828. * @param {external:Error} error
  5829. * @param {module:core/complexTypes.RembParams} result
  5830. */
  5831. /**
  5832. * Advanced parameters to configure the congestion control algorithm.
  5833. *
  5834. * @alias module:core/abstracts.BaseRtpEndpoint#setRembParams
  5835. *
  5836. * @param {module:core/complexTypes.RembParams} rembParams
  5837. * @param {module:core/abstracts.BaseRtpEndpoint~setRembParamsCallback} [callback]
  5838. *
  5839. * @return {external:Promise}
  5840. */
  5841. BaseRtpEndpoint.prototype.setRembParams = function(rembParams, callback){
  5842. var transaction = (arguments[0] instanceof Transaction)
  5843. ? Array.prototype.shift.apply(arguments)
  5844. : undefined;
  5845. //
  5846. // checkType('RembParams', 'rembParams', rembParams, {required: true});
  5847. //
  5848. var params = {
  5849. rembParams: rembParams
  5850. };
  5851. callback = (callback || noop).bind(this)
  5852. return disguise(this._invoke(transaction, 'setRembParams', params, callback), this)
  5853. };
  5854. /**
  5855. * @callback module:core/abstracts.BaseRtpEndpoint~setRembParamsCallback
  5856. * @param {external:Error} error
  5857. */
  5858. /**
  5859. * @alias module:core/abstracts.BaseRtpEndpoint.constructorParams
  5860. */
  5861. BaseRtpEndpoint.constructorParams = {
  5862. };
  5863. /**
  5864. * @alias module:core/abstracts.BaseRtpEndpoint.events
  5865. *
  5866. * @extends module:core/abstracts.SdpEndpoint.events
  5867. */
  5868. BaseRtpEndpoint.events = SdpEndpoint.events.concat(['ConnectionStateChanged', 'MediaStateChanged']);
  5869. /**
  5870. * Checker for {@link module:core/abstracts.BaseRtpEndpoint}
  5871. *
  5872. * @memberof module:core/abstracts
  5873. *
  5874. * @param {external:String} key
  5875. * @param {module:core/abstracts.BaseRtpEndpoint} value
  5876. */
  5877. function checkBaseRtpEndpoint(key, value)
  5878. {
  5879. if(!(value instanceof BaseRtpEndpoint))
  5880. throw ChecktypeError(key, BaseRtpEndpoint, value);
  5881. };
  5882. module.exports = BaseRtpEndpoint;
  5883. BaseRtpEndpoint.check = checkBaseRtpEndpoint;
  5884. },{"./SdpEndpoint":36,"inherits":"inherits","kurento-client":"kurento-client"}],31:[function(require,module,exports){
  5885. /* Autogenerated with Kurento Idl */
  5886. /*
  5887. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  5888. *
  5889. * Licensed under the Apache License, Version 2.0 (the "License");
  5890. * you may not use this file except in compliance with the License.
  5891. * You may obtain a copy of the License at
  5892. *
  5893. * http://www.apache.org/licenses/LICENSE-2.0
  5894. *
  5895. * Unless required by applicable law or agreed to in writing, software
  5896. * distributed under the License is distributed on an "AS IS" BASIS,
  5897. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5898. * See the License for the specific language governing permissions and
  5899. * limitations under the License.
  5900. */
  5901. var inherits = require('inherits');
  5902. var kurentoClient = require('kurento-client');
  5903. var disguise = kurentoClient.disguise;
  5904. var ChecktypeError = kurentoClient.checkType.ChecktypeError;
  5905. var MediaElement = require('./MediaElement');
  5906. /**
  5907. * @classdesc
  5908. * Base interface for all end points.
  5909. * <p>
  5910. * An Endpoint is a {@link module:core/abstracts.MediaElement MediaElement}
  5911. * that allow <a
  5912. * href="http://www.kurento.org/docs/current/glossary.html#term-kms">KMS</a>
  5913. * to interchange
  5914. * media contents with external systems, su<a href="http<a href="http://<a
  5915. * href="http://www.kurento.org/docs/current/glossary.html#term-http">HTTP</a>org/docs/current/glossary.html#term-webrtc">WebRTC</a>.org/docs/current/glossary.html#term-rtp">RTP</a>fferent
  5916. * and mechanisms, such as :term:`RTP`, :term:`WebRTC`, :term:`HTTP`,
  5917. * <code>file://</code>
  5918. * URLs, etc.
  5919. * </p>
  5920. * <p>
  5921. * An <code>Endpoint</code> may contain both sources and sinks for different
  5922. * media types,
  5923. * to provide bidirectional communication.
  5924. * </p>
  5925. *
  5926. * @abstract
  5927. * @extends module:core/abstracts.MediaElement
  5928. *
  5929. * @constructor module:core/abstracts.Endpoint
  5930. */
  5931. function Endpoint(){
  5932. Endpoint.super_.call(this);
  5933. };
  5934. inherits(Endpoint, MediaElement);
  5935. /**
  5936. * @alias module:core/abstracts.Endpoint.constructorParams
  5937. */
  5938. Endpoint.constructorParams = {
  5939. };
  5940. /**
  5941. * @alias module:core/abstracts.Endpoint.events
  5942. *
  5943. * @extends module:core/abstracts.MediaElement.events
  5944. */
  5945. Endpoint.events = MediaElement.events;
  5946. /**
  5947. * Checker for {@link module:core/abstracts.Endpoint}
  5948. *
  5949. * @memberof module:core/abstracts
  5950. *
  5951. * @param {external:String} key
  5952. * @param {module:core/abstracts.Endpoint} value
  5953. */
  5954. function checkEndpoint(key, value)
  5955. {
  5956. if(!(value instanceof Endpoint))
  5957. throw ChecktypeError(key, Endpoint, value);
  5958. };
  5959. module.exports = Endpoint;
  5960. Endpoint.check = checkEndpoint;
  5961. },{"./MediaElement":34,"inherits":"inherits","kurento-client":"kurento-client"}],32:[function(require,module,exports){
  5962. /* Autogenerated with Kurento Idl */
  5963. /*
  5964. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  5965. *
  5966. * Licensed under the Apache License, Version 2.0 (the "License");
  5967. * you may not use this file except in compliance with the License.
  5968. * You may obtain a copy of the License at
  5969. *
  5970. * http://www.apache.org/licenses/LICENSE-2.0
  5971. *
  5972. * Unless required by applicable law or agreed to in writing, software
  5973. * distributed under the License is distributed on an "AS IS" BASIS,
  5974. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5975. * See the License for the specific language governing permissions and
  5976. * limitations under the License.
  5977. */
  5978. var inherits = require('inherits');
  5979. var kurentoClient = require('kurento-client');
  5980. var disguise = kurentoClient.disguise;
  5981. var ChecktypeError = kurentoClient.checkType.ChecktypeError;
  5982. var MediaElement = require('./MediaElement');
  5983. /**
  5984. * @classdesc
  5985. * Base interface for all filters.
  5986. * <p>
  5987. * This is a certain type of {@link module:core/abstracts.MediaElement
  5988. * MediaElement}, that processes media
  5989. * injected through its sinks, and delivers the outcome through its sources.
  5990. * </p>
  5991. *
  5992. * @abstract
  5993. * @extends module:core/abstracts.MediaElement
  5994. *
  5995. * @constructor module:core/abstracts.Filter
  5996. */
  5997. function Filter(){
  5998. Filter.super_.call(this);
  5999. };
  6000. inherits(Filter, MediaElement);
  6001. /**
  6002. * @alias module:core/abstracts.Filter.constructorParams
  6003. */
  6004. Filter.constructorParams = {
  6005. };
  6006. /**
  6007. * @alias module:core/abstracts.Filter.events
  6008. *
  6009. * @extends module:core/abstracts.MediaElement.events
  6010. */
  6011. Filter.events = MediaElement.events;
  6012. /**
  6013. * Checker for {@link module:core/abstracts.Filter}
  6014. *
  6015. * @memberof module:core/abstracts
  6016. *
  6017. * @param {external:String} key
  6018. * @param {module:core/abstracts.Filter} value
  6019. */
  6020. function checkFilter(key, value)
  6021. {
  6022. if(!(value instanceof Filter))
  6023. throw ChecktypeError(key, Filter, value);
  6024. };
  6025. module.exports = Filter;
  6026. Filter.check = checkFilter;
  6027. },{"./MediaElement":34,"inherits":"inherits","kurento-client":"kurento-client"}],33:[function(require,module,exports){
  6028. /* Autogenerated with Kurento Idl */
  6029. /*
  6030. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  6031. *
  6032. * Licensed under the Apache License, Version 2.0 (the "License");
  6033. * you may not use this file except in compliance with the License.
  6034. * You may obtain a copy of the License at
  6035. *
  6036. * http://www.apache.org/licenses/LICENSE-2.0
  6037. *
  6038. * Unless required by applicable law or agreed to in writing, software
  6039. * distributed under the License is distributed on an "AS IS" BASIS,
  6040. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6041. * See the License for the specific language governing permissions and
  6042. * limitations under the License.
  6043. */
  6044. var inherits = require('inherits');
  6045. var kurentoClient = require('kurento-client');
  6046. var disguise = kurentoClient.disguise;
  6047. var checkType = kurentoClient.checkType;
  6048. var ChecktypeError = checkType.ChecktypeError;
  6049. var Transaction = kurentoClient.TransactionsManager.Transaction;
  6050. var HubPort = require('../HubPort');
  6051. var MediaObject = require('./MediaObject');
  6052. function noop(error, result) {
  6053. if (error) console.trace(error);
  6054. return result
  6055. };
  6056. /**
  6057. * @classdesc
  6058. * A Hub is a routing {@link module:core/abstracts.MediaObject MediaObject}.
  6059. * It connects several {@link module:core/abstracts.Endpoint endpoints }
  6060. * together
  6061. *
  6062. * @abstract
  6063. * @extends module:core/abstracts.MediaObject
  6064. *
  6065. * @constructor module:core/abstracts.Hub
  6066. */
  6067. function Hub(){
  6068. Hub.super_.call(this);
  6069. };
  6070. inherits(Hub, MediaObject);
  6071. //
  6072. // Public methods
  6073. //
  6074. /**
  6075. * Returns a string in dot (graphviz) format that represents the gstreamer
  6076. * elements inside the pipeline
  6077. *
  6078. * @alias module:core/abstracts.Hub.getGstreamerDot
  6079. *
  6080. * @param {module:core/complexTypes.GstreamerDotDetails} [details]
  6081. * Details of graph
  6082. *
  6083. * @param {module:core/abstracts.Hub~getGstreamerDotCallback} [callback]
  6084. *
  6085. * @return {external:Promise}
  6086. */
  6087. Hub.prototype.getGstreamerDot = function(details, callback){
  6088. var transaction = (arguments[0] instanceof Transaction)
  6089. ? Array.prototype.shift.apply(arguments)
  6090. : undefined;
  6091. callback = arguments[arguments.length-1] instanceof Function
  6092. ? Array.prototype.pop.call(arguments)
  6093. : undefined;
  6094. switch(arguments.length){
  6095. case 0: details = undefined;
  6096. break;
  6097. case 1:
  6098. break;
  6099. default:
  6100. var error = new RangeError('Number of params ('+arguments.length+') not in range [0-1]');
  6101. error.length = arguments.length;
  6102. error.min = 0;
  6103. error.max = 1;
  6104. throw error;
  6105. }
  6106. //
  6107. // checkType('GstreamerDotDetails', 'details', details);
  6108. //
  6109. var params = {
  6110. details: details
  6111. };
  6112. callback = (callback || noop).bind(this)
  6113. return disguise(this._invoke(transaction, 'getGstreamerDot', params, callback), this)
  6114. };
  6115. /**
  6116. * @callback module:core/abstracts.Hub~getGstreamerDotCallback
  6117. * @param {external:Error} error
  6118. * @param {external:String} result
  6119. * The dot graph.
  6120. */
  6121. /**
  6122. * Create a new instance of a {module:core~HubPort} attached to this {module:core~Hub}
  6123. *
  6124. * @param {module:core/abstract.Hub~createHubCallback} callback
  6125. *
  6126. * @return {external:Promise}
  6127. */
  6128. Hub.prototype.createHubPort = function(callback){
  6129. var transaction = (arguments[0] instanceof Transaction)
  6130. ? Array.prototype.shift.apply(arguments)
  6131. : undefined;
  6132. var usePromise = false;
  6133. if (callback == undefined) {
  6134. usePromise = true;
  6135. }
  6136. if(!arguments.length) callback = undefined;
  6137. callback = (callback || noop).bind(this)
  6138. var mediaObject = new HubPort()
  6139. mediaObject.on('_rpc', this.emit.bind(this, '_rpc'));
  6140. var params =
  6141. {
  6142. type: 'HubPort',
  6143. constructorParams: {hub: this}
  6144. };
  6145. Object.defineProperty(params, 'object', {value: mediaObject});
  6146. this.emit('_create', transaction, params, callback);
  6147. return mediaObject
  6148. };
  6149. /**
  6150. * @callback core/abstract.Hub~createHubCallback
  6151. * @param {external:Error} error
  6152. * @param {module:core/abstract.HubPort} result
  6153. * The created HubPort
  6154. */
  6155. /**
  6156. * @alias module:core/abstracts.Hub.constructorParams
  6157. */
  6158. Hub.constructorParams = {
  6159. };
  6160. /**
  6161. * @alias module:core/abstracts.Hub.events
  6162. *
  6163. * @extends module:core/abstracts.MediaObject.events
  6164. */
  6165. Hub.events = MediaObject.events;
  6166. /**
  6167. * Checker for {@link module:core/abstracts.Hub}
  6168. *
  6169. * @memberof module:core/abstracts
  6170. *
  6171. * @param {external:String} key
  6172. * @param {module:core/abstracts.Hub} value
  6173. */
  6174. function checkHub(key, value)
  6175. {
  6176. if(!(value instanceof Hub))
  6177. throw ChecktypeError(key, Hub, value);
  6178. };
  6179. module.exports = Hub;
  6180. Hub.check = checkHub;
  6181. },{"../HubPort":27,"./MediaObject":35,"inherits":"inherits","kurento-client":"kurento-client"}],34:[function(require,module,exports){
  6182. /* Autogenerated with Kurento Idl */
  6183. /*
  6184. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  6185. *
  6186. * Licensed under the Apache License, Version 2.0 (the "License");
  6187. * you may not use this file except in compliance with the License.
  6188. * You may obtain a copy of the License at
  6189. *
  6190. * http://www.apache.org/licenses/LICENSE-2.0
  6191. *
  6192. * Unless required by applicable law or agreed to in writing, software
  6193. * distributed under the License is distributed on an "AS IS" BASIS,
  6194. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6195. * See the License for the specific language governing permissions and
  6196. * limitations under the License.
  6197. */
  6198. var inherits = require('inherits');
  6199. var kurentoClient = require('kurento-client');
  6200. var disguise = kurentoClient.disguise;
  6201. var checkType = kurentoClient.checkType;
  6202. var ChecktypeError = checkType.ChecktypeError;
  6203. var checkArray = checkType.checkArray;
  6204. var Transaction = kurentoClient.TransactionsManager.Transaction;
  6205. var each = require('async').each
  6206. var promiseCallback = require('promisecallback');
  6207. var MediaObject = require('./MediaObject');
  6208. function noop(error, result) {
  6209. if (error) console.trace(error);
  6210. return result
  6211. };
  6212. /**
  6213. * @classdesc
  6214. * The basic building block of the media server, that can be interconnected
  6215. * inside a pipeline.
  6216. * <p>
  6217. * A {@link module:core/abstracts.MediaElement MediaElement} is a module that
  6218. * capability, and that is able to exchange media with other MediaElements
  6219. * through an internal element called <b>pad</b>.
  6220. * </p>
  6221. * <p>
  6222. * A pad can be defined as an input or output interface. Input pads are
  6223. * called
  6224. * sinks, and it's where the media elements receive media from other media
  6225. * elements. Output interfaces are called sources, and it's the pad used by
  6226. * the
  6227. * media element to feed media to other media elements. There can be only one
  6228. * sink pad per media element. On the other hand, the number of source pads
  6229. * is
  6230. * unconstrained. This means that a certain media element can receive media
  6231. * only
  6232. * from one element at a time, while it can send media to many others. Pads
  6233. * are
  6234. * created on demand, when the connect method is invoked. When two media
  6235. * elements
  6236. * are connected, one media pad is created for each type of media connected.
  6237. * For
  6238. * example, if you connect AUDIO and VIDEO between two media elements, each
  6239. * one
  6240. * will need to create two new pads: one for AUDIO and one for VIDEO.
  6241. * </p>
  6242. * <p>
  6243. * When media elements are connected, it can be the case that the encoding
  6244. * required in both input and output pads is not the same, and thus it needs
  6245. * to
  6246. * be transcoded. This is something that is handled transparently by the
  6247. * MediaElement internals, but such transcoding has a toll in the form of a
  6248. * higher CPU load, so connecting MediaElements that need media encoded in
  6249. * different formats is something to consider as a high load operation. The
  6250. * event
  6251. * `MediaTranscodingStateChange` allows to inform the client application of
  6252. * whether media transcoding is being enabled or not inside any MediaElement
  6253. * object.
  6254. * </p>
  6255. *
  6256. * @abstract
  6257. * @extends module:core/abstracts.MediaObject
  6258. *
  6259. * @constructor module:core/abstracts.MediaElement
  6260. *
  6261. * @fires {@link module:core#event:ElementConnected ElementConnected}
  6262. * @fires {@link module:core#event:ElementDisconnected ElementDisconnected}
  6263. * @fires {@link module:core#event:MediaFlowInStateChange MediaFlowInStateChange}
  6264. * @fires {@link module:core#event:MediaFlowOutStateChange MediaFlowOutStateChange}
  6265. * @fires {@link module:core#event:MediaTranscodingStateChange MediaTranscodingStateChange}
  6266. */
  6267. function MediaElement(){
  6268. MediaElement.super_.call(this);
  6269. };
  6270. inherits(MediaElement, MediaObject);
  6271. //
  6272. // Public properties
  6273. //
  6274. /**
  6275. * Maximum video bandwidth for transcoding.
  6276. * @deprecated Deprecated due to a typo. Use {@link
  6277. * module:core/abstracts.MediaElement#maxOutputBitrate} instead of this
  6278. * function.
  6279. *
  6280. * @alias module:core/abstracts.MediaElement#getMaxOuputBitrate
  6281. *
  6282. * @param {module:core/abstracts.MediaElement~getMaxOuputBitrateCallback} [callback]
  6283. *
  6284. * @return {external:Promise}
  6285. */
  6286. MediaElement.prototype.getMaxOuputBitrate = function(callback){
  6287. var transaction = (arguments[0] instanceof Transaction)
  6288. ? Array.prototype.shift.apply(arguments)
  6289. : undefined;
  6290. var usePromise = false;
  6291. if (callback == undefined) {
  6292. usePromise = true;
  6293. }
  6294. if(!arguments.length) callback = undefined;
  6295. callback = (callback || noop).bind(this)
  6296. return disguise(this._invoke(transaction, 'getMaxOuputBitrate', callback), this)
  6297. };
  6298. /**
  6299. * @callback module:core/abstracts.MediaElement~getMaxOuputBitrateCallback
  6300. * @param {external:Error} error
  6301. * @param {external:Integer} result
  6302. */
  6303. /**
  6304. * Maximum video bandwidth for transcoding.
  6305. * @deprecated Deprecated due to a typo. Use {@link
  6306. * module:core/abstracts.MediaElement#maxOutputBitrate} instead of this
  6307. * function.
  6308. *
  6309. * @alias module:core/abstracts.MediaElement#setMaxOuputBitrate
  6310. *
  6311. * @param {external:Integer} maxOuputBitrate
  6312. * @param {module:core/abstracts.MediaElement~setMaxOuputBitrateCallback} [callback]
  6313. *
  6314. * @return {external:Promise}
  6315. */
  6316. MediaElement.prototype.setMaxOuputBitrate = function(maxOuputBitrate, callback){
  6317. var transaction = (arguments[0] instanceof Transaction)
  6318. ? Array.prototype.shift.apply(arguments)
  6319. : undefined;
  6320. //
  6321. // checkType('int', 'maxOuputBitrate', maxOuputBitrate, {required: true});
  6322. //
  6323. var params = {
  6324. maxOuputBitrate: maxOuputBitrate
  6325. };
  6326. callback = (callback || noop).bind(this)
  6327. return disguise(this._invoke(transaction, 'setMaxOuputBitrate', params, callback), this)
  6328. };
  6329. /**
  6330. * @callback module:core/abstracts.MediaElement~setMaxOuputBitrateCallback
  6331. * @param {external:Error} error
  6332. */
  6333. /**
  6334. * Maximum video bitrate for transcoding.
  6335. * <ul>
  6336. * <li>Unit: bps (bits per second).</li>
  6337. * <li>Default: MAXINT.</li>
  6338. * <li>0 = unlimited.</li>
  6339. * </ul>
  6340. *
  6341. * @alias module:core/abstracts.MediaElement#getMaxOutputBitrate
  6342. *
  6343. * @param {module:core/abstracts.MediaElement~getMaxOutputBitrateCallback} [callback]
  6344. *
  6345. * @return {external:Promise}
  6346. */
  6347. MediaElement.prototype.getMaxOutputBitrate = function(callback){
  6348. var transaction = (arguments[0] instanceof Transaction)
  6349. ? Array.prototype.shift.apply(arguments)
  6350. : undefined;
  6351. var usePromise = false;
  6352. if (callback == undefined) {
  6353. usePromise = true;
  6354. }
  6355. if(!arguments.length) callback = undefined;
  6356. callback = (callback || noop).bind(this)
  6357. return disguise(this._invoke(transaction, 'getMaxOutputBitrate', callback), this)
  6358. };
  6359. /**
  6360. * @callback module:core/abstracts.MediaElement~getMaxOutputBitrateCallback
  6361. * @param {external:Error} error
  6362. * @param {external:Integer} result
  6363. */
  6364. /**
  6365. * Maximum video bitrate for transcoding.
  6366. * <ul>
  6367. * <li>Unit: bps (bits per second).</li>
  6368. * <li>Default: MAXINT.</li>
  6369. * <li>0 = unlimited.</li>
  6370. * </ul>
  6371. *
  6372. * @alias module:core/abstracts.MediaElement#setMaxOutputBitrate
  6373. *
  6374. * @param {external:Integer} maxOutputBitrate
  6375. * @param {module:core/abstracts.MediaElement~setMaxOutputBitrateCallback} [callback]
  6376. *
  6377. * @return {external:Promise}
  6378. */
  6379. MediaElement.prototype.setMaxOutputBitrate = function(maxOutputBitrate, callback){
  6380. var transaction = (arguments[0] instanceof Transaction)
  6381. ? Array.prototype.shift.apply(arguments)
  6382. : undefined;
  6383. //
  6384. // checkType('int', 'maxOutputBitrate', maxOutputBitrate, {required: true});
  6385. //
  6386. var params = {
  6387. maxOutputBitrate: maxOutputBitrate
  6388. };
  6389. callback = (callback || noop).bind(this)
  6390. return disguise(this._invoke(transaction, 'setMaxOutputBitrate', params, callback), this)
  6391. };
  6392. /**
  6393. * @callback module:core/abstracts.MediaElement~setMaxOutputBitrateCallback
  6394. * @param {external:Error} error
  6395. */
  6396. /**
  6397. * Minimum video bandwidth for transcoding.
  6398. * @deprecated Deprecated due to a typo. Use {@link
  6399. * module:core/abstracts.MediaElement#minOutputBitrate} instead of this
  6400. * function.
  6401. *
  6402. * @alias module:core/abstracts.MediaElement#getMinOuputBitrate
  6403. *
  6404. * @param {module:core/abstracts.MediaElement~getMinOuputBitrateCallback} [callback]
  6405. *
  6406. * @return {external:Promise}
  6407. */
  6408. MediaElement.prototype.getMinOuputBitrate = function(callback){
  6409. var transaction = (arguments[0] instanceof Transaction)
  6410. ? Array.prototype.shift.apply(arguments)
  6411. : undefined;
  6412. var usePromise = false;
  6413. if (callback == undefined) {
  6414. usePromise = true;
  6415. }
  6416. if(!arguments.length) callback = undefined;
  6417. callback = (callback || noop).bind(this)
  6418. return disguise(this._invoke(transaction, 'getMinOuputBitrate', callback), this)
  6419. };
  6420. /**
  6421. * @callback module:core/abstracts.MediaElement~getMinOuputBitrateCallback
  6422. * @param {external:Error} error
  6423. * @param {external:Integer} result
  6424. */
  6425. /**
  6426. * Minimum video bandwidth for transcoding.
  6427. * @deprecated Deprecated due to a typo. Use {@link
  6428. * module:core/abstracts.MediaElement#minOutputBitrate} instead of this
  6429. * function.
  6430. *
  6431. * @alias module:core/abstracts.MediaElement#setMinOuputBitrate
  6432. *
  6433. * @param {external:Integer} minOuputBitrate
  6434. * @param {module:core/abstracts.MediaElement~setMinOuputBitrateCallback} [callback]
  6435. *
  6436. * @return {external:Promise}
  6437. */
  6438. MediaElement.prototype.setMinOuputBitrate = function(minOuputBitrate, callback){
  6439. var transaction = (arguments[0] instanceof Transaction)
  6440. ? Array.prototype.shift.apply(arguments)
  6441. : undefined;
  6442. //
  6443. // checkType('int', 'minOuputBitrate', minOuputBitrate, {required: true});
  6444. //
  6445. var params = {
  6446. minOuputBitrate: minOuputBitrate
  6447. };
  6448. callback = (callback || noop).bind(this)
  6449. return disguise(this._invoke(transaction, 'setMinOuputBitrate', params, callback), this)
  6450. };
  6451. /**
  6452. * @callback module:core/abstracts.MediaElement~setMinOuputBitrateCallback
  6453. * @param {external:Error} error
  6454. */
  6455. /**
  6456. * Minimum video bitrate for transcoding.
  6457. * <ul>
  6458. * <li>Unit: bps (bits per second).</li>
  6459. * <li>Default: 0.</li>
  6460. * </ul>
  6461. *
  6462. * @alias module:core/abstracts.MediaElement#getMinOutputBitrate
  6463. *
  6464. * @param {module:core/abstracts.MediaElement~getMinOutputBitrateCallback} [callback]
  6465. *
  6466. * @return {external:Promise}
  6467. */
  6468. MediaElement.prototype.getMinOutputBitrate = function(callback){
  6469. var transaction = (arguments[0] instanceof Transaction)
  6470. ? Array.prototype.shift.apply(arguments)
  6471. : undefined;
  6472. var usePromise = false;
  6473. if (callback == undefined) {
  6474. usePromise = true;
  6475. }
  6476. if(!arguments.length) callback = undefined;
  6477. callback = (callback || noop).bind(this)
  6478. return disguise(this._invoke(transaction, 'getMinOutputBitrate', callback), this)
  6479. };
  6480. /**
  6481. * @callback module:core/abstracts.MediaElement~getMinOutputBitrateCallback
  6482. * @param {external:Error} error
  6483. * @param {external:Integer} result
  6484. */
  6485. /**
  6486. * Minimum video bitrate for transcoding.
  6487. * <ul>
  6488. * <li>Unit: bps (bits per second).</li>
  6489. * <li>Default: 0.</li>
  6490. * </ul>
  6491. *
  6492. * @alias module:core/abstracts.MediaElement#setMinOutputBitrate
  6493. *
  6494. * @param {external:Integer} minOutputBitrate
  6495. * @param {module:core/abstracts.MediaElement~setMinOutputBitrateCallback} [callback]
  6496. *
  6497. * @return {external:Promise}
  6498. */
  6499. MediaElement.prototype.setMinOutputBitrate = function(minOutputBitrate, callback){
  6500. var transaction = (arguments[0] instanceof Transaction)
  6501. ? Array.prototype.shift.apply(arguments)
  6502. : undefined;
  6503. //
  6504. // checkType('int', 'minOutputBitrate', minOutputBitrate, {required: true});
  6505. //
  6506. var params = {
  6507. minOutputBitrate: minOutputBitrate
  6508. };
  6509. callback = (callback || noop).bind(this)
  6510. return disguise(this._invoke(transaction, 'setMinOutputBitrate', params, callback), this)
  6511. };
  6512. /**
  6513. * @callback module:core/abstracts.MediaElement~setMinOutputBitrateCallback
  6514. * @param {external:Error} error
  6515. */
  6516. //
  6517. // Public methods
  6518. //
  6519. /**
  6520. * Connects two elements, with the media flowing from left to right.
  6521. * <p>
  6522. * The element that invokes the connect will be the source of media, creating
  6523. * one
  6524. * sink pad for each type of media connected. The element given as parameter
  6525. * to
  6526. * the method will be the sink, and it will create one sink pad per media type
  6527. * connected.
  6528. * </p>
  6529. * <p>
  6530. * If otherwise not specified, all types of media are connected by default
  6531. * (AUDIO, VIDEO and DATA). It is recommended to connect the specific types of
  6532. * media if not all of them will be used. For this purpose, the connect method
  6533. * can be invoked more than once on the same two elements, but with different
  6534. * media types.
  6535. * </p>
  6536. * <p>
  6537. * The connection is unidirectional. If a bidirectional connection is desired,
  6538. * the position of the media elements must be inverted. For instance,
  6539. * webrtc1.connect(webrtc2) is connecting webrtc1 as source of webrtc2. In
  6540. * order
  6541. * to create a WebRTC one-2one conversation, the user would need to specify
  6542. * the
  6543. * connection on the other direction with webrtc2.connect(webrtc1).
  6544. * </p>
  6545. * <p>
  6546. * Even though one media element can have one sink pad per type of media, only
  6547. * one media element can be connected to another at a given time. If a media
  6548. * element is connected to another, the former will become the source of the
  6549. * sink
  6550. * media element, regardless whether there was another element connected or
  6551. * not.
  6552. * </p>
  6553. *
  6554. * @alias module:core/abstracts.MediaElement.connect
  6555. *
  6556. * @param {module:core/abstracts.MediaElement} sink
  6557. * the target {@link module:core/abstracts.MediaElement MediaElement} that will
  6558. *
  6559. * @param {module:core/complexTypes.MediaType} [mediaType]
  6560. * the {@link MediaType} of the pads that will be connected
  6561. *
  6562. * @param {external:String} [sourceMediaDescription]
  6563. * A textual description of the media source. Currently not used, aimed mainly
  6564. * for {@link module:core/abstracts.MediaElement#MediaType.DATA} sources
  6565. *
  6566. * @param {external:String} [sinkMediaDescription]
  6567. * A textual description of the media source. Currently not used, aimed mainly
  6568. * for {@link module:core/abstracts.MediaElement#MediaType.DATA} sources
  6569. *
  6570. * @param {module:core/abstracts.MediaElement~connectCallback} [callback]
  6571. *
  6572. * @return {external:Promise}
  6573. */
  6574. MediaElement.prototype.connect = function(sink, mediaType, sourceMediaDescription, sinkMediaDescription, callback){
  6575. var transaction = (arguments[0] instanceof Transaction)
  6576. ? Array.prototype.shift.apply(arguments)
  6577. : undefined;
  6578. var promise
  6579. if(sink instanceof Array)
  6580. {
  6581. callback = arguments[arguments.length-1] instanceof Function
  6582. ? Array.prototype.pop.call(arguments)
  6583. : undefined;
  6584. var media = sink
  6585. var src = this;
  6586. sink = media[media.length-1]
  6587. // Check if we have enought media components
  6588. if(!media.length)
  6589. throw new SyntaxError('Need at least one media element to connect');
  6590. // Check MediaElements are of the correct type
  6591. checkArray('MediaElement', 'media', media)
  6592. // Generate promise
  6593. promise = new Promise(function(resolve, reject)
  6594. {
  6595. function callback(error, result)
  6596. {
  6597. if(error) return reject(error);
  6598. resolve(result);
  6599. };
  6600. each(media, function(sink, callback)
  6601. {
  6602. src = src.connect(sink, callback);
  6603. },
  6604. callback);
  6605. });
  6606. promise = promiseCallback(promise, callback)
  6607. }
  6608. else
  6609. {
  6610. var transaction = (arguments[0] instanceof Transaction)
  6611. ? Array.prototype.shift.apply(arguments)
  6612. : undefined;
  6613. callback = arguments[arguments.length-1] instanceof Function
  6614. ? Array.prototype.pop.call(arguments)
  6615. : undefined;
  6616. switch(arguments.length){
  6617. case 1: mediaType = undefined;
  6618. case 2: sourceMediaDescription = undefined;
  6619. case 3: sinkMediaDescription = undefined;
  6620. break;
  6621. case 4:
  6622. break;
  6623. default:
  6624. var error = new RangeError('Number of params ('+arguments.length+') not in range [1-4]');
  6625. error.length = arguments.length;
  6626. error.min = 1;
  6627. error.max = 4;
  6628. throw error;
  6629. }
  6630. //
  6631. // checkType('MediaElement', 'sink', sink, {required: true});
  6632. //
  6633. // checkType('MediaType', 'mediaType', mediaType);
  6634. //
  6635. // checkType('String', 'sourceMediaDescription', sourceMediaDescription);
  6636. //
  6637. // checkType('String', 'sinkMediaDescription', sinkMediaDescription);
  6638. //
  6639. var params = {
  6640. sink: sink,
  6641. mediaType: mediaType,
  6642. sourceMediaDescription: sourceMediaDescription,
  6643. sinkMediaDescription: sinkMediaDescription
  6644. };
  6645. callback = (callback || noop).bind(this)
  6646. promise = this._invoke(transaction, 'connect', params, callback)
  6647. }
  6648. return disguise(promise, sink)
  6649. };
  6650. /**
  6651. * @callback module:core/abstracts.MediaElement~connectCallback
  6652. * @param {external:Error} error
  6653. */
  6654. /**
  6655. * Disconnects two media elements. This will release the source pads of the
  6656. * source media element, and the sink pads of the sink media element.
  6657. *
  6658. * @alias module:core/abstracts.MediaElement.disconnect
  6659. *
  6660. * @param {module:core/abstracts.MediaElement} sink
  6661. * the target {@link module:core/abstracts.MediaElement MediaElement} that will
  6662. *
  6663. * @param {module:core/complexTypes.MediaType} [mediaType]
  6664. * the {@link MediaType} of the pads that will be connected
  6665. *
  6666. * @param {external:String} [sourceMediaDescription]
  6667. * A textual description of the media source. Currently not used, aimed mainly
  6668. * for {@link module:core/abstracts.MediaElement#MediaType.DATA} sources
  6669. *
  6670. * @param {external:String} [sinkMediaDescription]
  6671. * A textual description of the media source. Currently not used, aimed mainly
  6672. * for {@link module:core/abstracts.MediaElement#MediaType.DATA} sources
  6673. *
  6674. * @param {module:core/abstracts.MediaElement~disconnectCallback} [callback]
  6675. *
  6676. * @return {external:Promise}
  6677. */
  6678. MediaElement.prototype.disconnect = function(sink, mediaType, sourceMediaDescription, sinkMediaDescription, callback){
  6679. var transaction = (arguments[0] instanceof Transaction)
  6680. ? Array.prototype.shift.apply(arguments)
  6681. : undefined;
  6682. callback = arguments[arguments.length-1] instanceof Function
  6683. ? Array.prototype.pop.call(arguments)
  6684. : undefined;
  6685. switch(arguments.length){
  6686. case 1: mediaType = undefined;
  6687. case 2: sourceMediaDescription = undefined;
  6688. case 3: sinkMediaDescription = undefined;
  6689. break;
  6690. case 4:
  6691. break;
  6692. default:
  6693. var error = new RangeError('Number of params ('+arguments.length+') not in range [1-4]');
  6694. error.length = arguments.length;
  6695. error.min = 1;
  6696. error.max = 4;
  6697. throw error;
  6698. }
  6699. //
  6700. // checkType('MediaElement', 'sink', sink, {required: true});
  6701. //
  6702. // checkType('MediaType', 'mediaType', mediaType);
  6703. //
  6704. // checkType('String', 'sourceMediaDescription', sourceMediaDescription);
  6705. //
  6706. // checkType('String', 'sinkMediaDescription', sinkMediaDescription);
  6707. //
  6708. var params = {
  6709. sink: sink,
  6710. mediaType: mediaType,
  6711. sourceMediaDescription: sourceMediaDescription,
  6712. sinkMediaDescription: sinkMediaDescription
  6713. };
  6714. callback = (callback || noop).bind(this)
  6715. return disguise(this._invoke(transaction, 'disconnect', params, callback), this)
  6716. };
  6717. /**
  6718. * @callback module:core/abstracts.MediaElement~disconnectCallback
  6719. * @param {external:Error} error
  6720. */
  6721. /**
  6722. * Return a .dot file describing the topology of the media element.
  6723. * <p>The element can be queried for certain type of data:</p>
  6724. * <ul>
  6725. * <li>SHOW_ALL: default value</li>
  6726. * <li>SHOW_CAPS_DETAILS</li>
  6727. * <li>SHOW_FULL_PARAMS</li>
  6728. * <li>SHOW_MEDIA_TYPE</li>
  6729. * <li>SHOW_NON_DEFAULT_PARAMS</li>
  6730. * <li>SHOW_STATES</li>
  6731. * <li>SHOW_VERBOSE</li>
  6732. * </ul>
  6733. *
  6734. * @alias module:core/abstracts.MediaElement.getGstreamerDot
  6735. *
  6736. * @param {module:core/complexTypes.GstreamerDotDetails} [details]
  6737. * Details of graph
  6738. *
  6739. * @param {module:core/abstracts.MediaElement~getGstreamerDotCallback} [callback]
  6740. *
  6741. * @return {external:Promise}
  6742. */
  6743. MediaElement.prototype.getGstreamerDot = function(details, callback){
  6744. var transaction = (arguments[0] instanceof Transaction)
  6745. ? Array.prototype.shift.apply(arguments)
  6746. : undefined;
  6747. callback = arguments[arguments.length-1] instanceof Function
  6748. ? Array.prototype.pop.call(arguments)
  6749. : undefined;
  6750. switch(arguments.length){
  6751. case 0: details = undefined;
  6752. break;
  6753. case 1:
  6754. break;
  6755. default:
  6756. var error = new RangeError('Number of params ('+arguments.length+') not in range [0-1]');
  6757. error.length = arguments.length;
  6758. error.min = 0;
  6759. error.max = 1;
  6760. throw error;
  6761. }
  6762. //
  6763. // checkType('GstreamerDotDetails', 'details', details);
  6764. //
  6765. var params = {
  6766. details: details
  6767. };
  6768. callback = (callback || noop).bind(this)
  6769. return disguise(this._invoke(transaction, 'getGstreamerDot', params, callback), this)
  6770. };
  6771. /**
  6772. * @callback module:core/abstracts.MediaElement~getGstreamerDotCallback
  6773. * @param {external:Error} error
  6774. * @param {external:String} result
  6775. * The dot graph.
  6776. */
  6777. /**
  6778. * Gets information about the source pads of this media element.
  6779. * <p>
  6780. * Since source pads connect to other media element's sinks, this is formally
  6781. * the
  6782. * sink of media from the element's perspective. Media can be filtered by
  6783. * type,
  6784. * or by the description given to the pad though which both elements are
  6785. * connected.
  6786. * </p>
  6787. *
  6788. * @alias module:core/abstracts.MediaElement.getSinkConnections
  6789. *
  6790. * @param {module:core/complexTypes.MediaType} [mediaType]
  6791. * One of {@link module:core/abstracts.MediaElement#MediaType.AUDIO}, {@link
  6792. * module:core/abstracts.MediaElement#MediaType.VIDEO} or {@link
  6793. * module:core/abstracts.MediaElement#MediaType.DATA}
  6794. *
  6795. * @param {external:String} [description]
  6796. * A textual description of the media source. Currently not used, aimed mainly
  6797. * for {@link module:core/abstracts.MediaElement#MediaType.DATA} sources
  6798. *
  6799. * @param {module:core/abstracts.MediaElement~getSinkConnectionsCallback} [callback]
  6800. *
  6801. * @return {external:Promise}
  6802. */
  6803. MediaElement.prototype.getSinkConnections = function(mediaType, description, callback){
  6804. var transaction = (arguments[0] instanceof Transaction)
  6805. ? Array.prototype.shift.apply(arguments)
  6806. : undefined;
  6807. callback = arguments[arguments.length-1] instanceof Function
  6808. ? Array.prototype.pop.call(arguments)
  6809. : undefined;
  6810. switch(arguments.length){
  6811. case 0: mediaType = undefined;
  6812. case 1: description = undefined;
  6813. break;
  6814. case 2:
  6815. break;
  6816. default:
  6817. var error = new RangeError('Number of params ('+arguments.length+') not in range [0-2]');
  6818. error.length = arguments.length;
  6819. error.min = 0;
  6820. error.max = 2;
  6821. throw error;
  6822. }
  6823. //
  6824. // checkType('MediaType', 'mediaType', mediaType);
  6825. //
  6826. // checkType('String', 'description', description);
  6827. //
  6828. var params = {
  6829. mediaType: mediaType,
  6830. description: description
  6831. };
  6832. callback = (callback || noop).bind(this)
  6833. return disguise(this._invoke(transaction, 'getSinkConnections', params, callback), this)
  6834. };
  6835. /**
  6836. * @callback module:core/abstracts.MediaElement~getSinkConnectionsCallback
  6837. * @param {external:Error} error
  6838. * @param {module:core/complexTypes.ElementConnectionData} result
  6839. * A list of the connections information that are receiving media from this
  6840. * element. The list will be empty if no sources are found.
  6841. */
  6842. /**
  6843. * Gets information about the sink pads of this media element.
  6844. * <p>
  6845. * Since sink pads are the interface through which a media element gets it's
  6846. * media, whatever is connected to an element's sink pad is formally a source
  6847. * of
  6848. * media. Media can be filtered by type, or by the description given to the
  6849. * pad
  6850. * though which both elements are connected.
  6851. * </p>
  6852. *
  6853. * @alias module:core/abstracts.MediaElement.getSourceConnections
  6854. *
  6855. * @param {module:core/complexTypes.MediaType} [mediaType]
  6856. * One of {@link module:core/abstracts.MediaElement#MediaType.AUDIO}, {@link
  6857. * module:core/abstracts.MediaElement#MediaType.VIDEO} or {@link
  6858. * module:core/abstracts.MediaElement#MediaType.DATA}
  6859. *
  6860. * @param {external:String} [description]
  6861. * A textual description of the media source. Currently not used, aimed mainly
  6862. * for {@link module:core/abstracts.MediaElement#MediaType.DATA} sources
  6863. *
  6864. * @param {module:core/abstracts.MediaElement~getSourceConnectionsCallback} [callback]
  6865. *
  6866. * @return {external:Promise}
  6867. */
  6868. MediaElement.prototype.getSourceConnections = function(mediaType, description, callback){
  6869. var transaction = (arguments[0] instanceof Transaction)
  6870. ? Array.prototype.shift.apply(arguments)
  6871. : undefined;
  6872. callback = arguments[arguments.length-1] instanceof Function
  6873. ? Array.prototype.pop.call(arguments)
  6874. : undefined;
  6875. switch(arguments.length){
  6876. case 0: mediaType = undefined;
  6877. case 1: description = undefined;
  6878. break;
  6879. case 2:
  6880. break;
  6881. default:
  6882. var error = new RangeError('Number of params ('+arguments.length+') not in range [0-2]');
  6883. error.length = arguments.length;
  6884. error.min = 0;
  6885. error.max = 2;
  6886. throw error;
  6887. }
  6888. //
  6889. // checkType('MediaType', 'mediaType', mediaType);
  6890. //
  6891. // checkType('String', 'description', description);
  6892. //
  6893. var params = {
  6894. mediaType: mediaType,
  6895. description: description
  6896. };
  6897. callback = (callback || noop).bind(this)
  6898. return disguise(this._invoke(transaction, 'getSourceConnections', params, callback), this)
  6899. };
  6900. /**
  6901. * @callback module:core/abstracts.MediaElement~getSourceConnectionsCallback
  6902. * @param {external:Error} error
  6903. * @param {module:core/complexTypes.ElementConnectionData} result
  6904. * A list of the connections information that are sending media to this
  6905. * element. The list will be empty if no sources are found.
  6906. */
  6907. /**
  6908. * Gets the statistics related to an endpoint. If no media type is specified, it
  6909. *
  6910. * @alias module:core/abstracts.MediaElement.getStats
  6911. *
  6912. * @param {module:core/complexTypes.MediaType} [mediaType]
  6913. * One of {@link module:core/abstracts.MediaElement#MediaType.AUDIO} or {@link
  6914. * module:core/abstracts.MediaElement#MediaType.VIDEO}
  6915. *
  6916. * @param {module:core/abstracts.MediaElement~getStatsCallback} [callback]
  6917. *
  6918. * @return {external:Promise}
  6919. */
  6920. MediaElement.prototype.getStats = function(mediaType, callback){
  6921. var transaction = (arguments[0] instanceof Transaction)
  6922. ? Array.prototype.shift.apply(arguments)
  6923. : undefined;
  6924. callback = arguments[arguments.length-1] instanceof Function
  6925. ? Array.prototype.pop.call(arguments)
  6926. : undefined;
  6927. switch(arguments.length){
  6928. case 0: mediaType = undefined;
  6929. break;
  6930. case 1:
  6931. break;
  6932. default:
  6933. var error = new RangeError('Number of params ('+arguments.length+') not in range [0-1]');
  6934. error.length = arguments.length;
  6935. error.min = 0;
  6936. error.max = 1;
  6937. throw error;
  6938. }
  6939. //
  6940. // checkType('MediaType', 'mediaType', mediaType);
  6941. //
  6942. var params = {
  6943. mediaType: mediaType
  6944. };
  6945. callback = (callback || noop).bind(this)
  6946. return disguise(this._invoke(transaction, 'getStats', params, callback), this)
  6947. };
  6948. /**
  6949. * @callback module:core/abstracts.MediaElement~getStatsCallback
  6950. * @param {external:Error} error
  6951. * @param {Object.<string, module:core/complexTypes.Stats>} result
  6952. * Delivers a successful result in the form of a RTC stats report. A RTC stats
  6953. * report represents a map between strings, identifying the inspected objects
  6954. * (RTCStats.id), and their corresponding RTCStats objects.
  6955. */
  6956. /**
  6957. * This method indicates whether the media element is receiving media of a
  6958. * certain type. The media sink pad can be identified individually, if needed.
  6959. * It is only supported for AUDIO and VIDEO types, raising a
  6960. * MEDIA_OBJECT_ILLEGAL_PARAM_ERROR otherwise. If the pad indicated does not
  6961. * exist, if will return false.
  6962. *
  6963. * @alias module:core/abstracts.MediaElement.isMediaFlowingIn
  6964. *
  6965. * @param {module:core/complexTypes.MediaType} mediaType
  6966. * One of {@link module:core/abstracts.MediaElement#MediaType.AUDIO} or {@link
  6967. * module:core/abstracts.MediaElement#MediaType.VIDEO}
  6968. *
  6969. * @param {external:String} [sinkMediaDescription]
  6970. * Description of the sink
  6971. *
  6972. * @param {module:core/abstracts.MediaElement~isMediaFlowingInCallback} [callback]
  6973. *
  6974. * @return {external:Promise}
  6975. */
  6976. MediaElement.prototype.isMediaFlowingIn = function(mediaType, sinkMediaDescription, callback){
  6977. var transaction = (arguments[0] instanceof Transaction)
  6978. ? Array.prototype.shift.apply(arguments)
  6979. : undefined;
  6980. callback = arguments[arguments.length-1] instanceof Function
  6981. ? Array.prototype.pop.call(arguments)
  6982. : undefined;
  6983. switch(arguments.length){
  6984. case 1: sinkMediaDescription = undefined;
  6985. break;
  6986. case 2:
  6987. break;
  6988. default:
  6989. var error = new RangeError('Number of params ('+arguments.length+') not in range [1-2]');
  6990. error.length = arguments.length;
  6991. error.min = 1;
  6992. error.max = 2;
  6993. throw error;
  6994. }
  6995. //
  6996. // checkType('MediaType', 'mediaType', mediaType, {required: true});
  6997. //
  6998. // checkType('String', 'sinkMediaDescription', sinkMediaDescription);
  6999. //
  7000. var params = {
  7001. mediaType: mediaType,
  7002. sinkMediaDescription: sinkMediaDescription
  7003. };
  7004. callback = (callback || noop).bind(this)
  7005. return disguise(this._invoke(transaction, 'isMediaFlowingIn', params, callback), this)
  7006. };
  7007. /**
  7008. * @callback module:core/abstracts.MediaElement~isMediaFlowingInCallback
  7009. * @param {external:Error} error
  7010. * @param {external:Boolean} result
  7011. * TRUE if there is media, FALSE in other case.
  7012. */
  7013. /**
  7014. * This method indicates whether the media element is emitting media of a
  7015. * certain type. The media source pad can be identified individually, if needed.
  7016. *
  7017. * @alias module:core/abstracts.MediaElement.isMediaFlowingOut
  7018. *
  7019. * @param {module:core/complexTypes.MediaType} mediaType
  7020. * One of {@link module:core/abstracts.MediaElement#MediaType.AUDIO} or {@link
  7021. * module:core/abstracts.MediaElement#MediaType.VIDEO}
  7022. *
  7023. * @param {external:String} [sourceMediaDescription]
  7024. * Description of the source
  7025. *
  7026. * @param {module:core/abstracts.MediaElement~isMediaFlowingOutCallback} [callback]
  7027. *
  7028. * @return {external:Promise}
  7029. */
  7030. MediaElement.prototype.isMediaFlowingOut = function(mediaType, sourceMediaDescription, callback){
  7031. var transaction = (arguments[0] instanceof Transaction)
  7032. ? Array.prototype.shift.apply(arguments)
  7033. : undefined;
  7034. callback = arguments[arguments.length-1] instanceof Function
  7035. ? Array.prototype.pop.call(arguments)
  7036. : undefined;
  7037. switch(arguments.length){
  7038. case 1: sourceMediaDescription = undefined;
  7039. break;
  7040. case 2:
  7041. break;
  7042. default:
  7043. var error = new RangeError('Number of params ('+arguments.length+') not in range [1-2]');
  7044. error.length = arguments.length;
  7045. error.min = 1;
  7046. error.max = 2;
  7047. throw error;
  7048. }
  7049. //
  7050. // checkType('MediaType', 'mediaType', mediaType, {required: true});
  7051. //
  7052. // checkType('String', 'sourceMediaDescription', sourceMediaDescription);
  7053. //
  7054. var params = {
  7055. mediaType: mediaType,
  7056. sourceMediaDescription: sourceMediaDescription
  7057. };
  7058. callback = (callback || noop).bind(this)
  7059. return disguise(this._invoke(transaction, 'isMediaFlowingOut', params, callback), this)
  7060. };
  7061. /**
  7062. * @callback module:core/abstracts.MediaElement~isMediaFlowingOutCallback
  7063. * @param {external:Error} error
  7064. * @param {external:Boolean} result
  7065. * TRUE if there is media, FALSE in other case.
  7066. */
  7067. /**
  7068. * Indicates whether this media element is actively transcoding between input
  7069. * and output pads. This operation is only supported for AUDIO and VIDEO media
  7070. * types, raising a MEDIA_OBJECT_ILLEGAL_PARAM_ERROR otherwise.
  7071. * The internal GStreamer processing bin can be indicated, if needed;
  7072. * if the bin doesn't exist, the return value will be FALSE.
  7073. *
  7074. * @alias module:core/abstracts.MediaElement.isMediaTranscoding
  7075. *
  7076. * @param {module:core/complexTypes.MediaType} mediaType
  7077. * One of {@link module:core/abstracts.MediaElement#MediaType.AUDIO} or {@link
  7078. * module:core/abstracts.MediaElement#MediaType.VIDEO}
  7079. *
  7080. * @param {external:String} [binName]
  7081. * Internal name of the processing bin, as previously given by
  7082. * <code>MediaTranscodingStateChange</code>.
  7083. *
  7084. * @param {module:core/abstracts.MediaElement~isMediaTranscodingCallback} [callback]
  7085. *
  7086. * @return {external:Promise}
  7087. */
  7088. MediaElement.prototype.isMediaTranscoding = function(mediaType, binName, callback){
  7089. var transaction = (arguments[0] instanceof Transaction)
  7090. ? Array.prototype.shift.apply(arguments)
  7091. : undefined;
  7092. callback = arguments[arguments.length-1] instanceof Function
  7093. ? Array.prototype.pop.call(arguments)
  7094. : undefined;
  7095. switch(arguments.length){
  7096. case 1: binName = undefined;
  7097. break;
  7098. case 2:
  7099. break;
  7100. default:
  7101. var error = new RangeError('Number of params ('+arguments.length+') not in range [1-2]');
  7102. error.length = arguments.length;
  7103. error.min = 1;
  7104. error.max = 2;
  7105. throw error;
  7106. }
  7107. //
  7108. // checkType('MediaType', 'mediaType', mediaType, {required: true});
  7109. //
  7110. // checkType('String', 'binName', binName);
  7111. //
  7112. var params = {
  7113. mediaType: mediaType,
  7114. binName: binName
  7115. };
  7116. callback = (callback || noop).bind(this)
  7117. return disguise(this._invoke(transaction, 'isMediaTranscoding', params, callback), this)
  7118. };
  7119. /**
  7120. * @callback module:core/abstracts.MediaElement~isMediaTranscodingCallback
  7121. * @param {external:Error} error
  7122. * @param {external:Boolean} result
  7123. * TRUE if media is being transcoded, FALSE otherwise.
  7124. */
  7125. /**
  7126. * Sets the type of data for the audio stream.
  7127. * <p>
  7128. * MediaElements that do not support configuration of audio capabilities will
  7129. * throw a MEDIA_OBJECT_ILLEGAL_PARAM_ERROR exception.
  7130. * </p>
  7131. *
  7132. * @alias module:core/abstracts.MediaElement.setAudioFormat
  7133. *
  7134. * @param {module:core/complexTypes.AudioCaps} caps
  7135. * The format for the stream of audio
  7136. *
  7137. * @param {module:core/abstracts.MediaElement~setAudioFormatCallback} [callback]
  7138. *
  7139. * @return {external:Promise}
  7140. */
  7141. MediaElement.prototype.setAudioFormat = function(caps, callback){
  7142. var transaction = (arguments[0] instanceof Transaction)
  7143. ? Array.prototype.shift.apply(arguments)
  7144. : undefined;
  7145. //
  7146. // checkType('AudioCaps', 'caps', caps, {required: true});
  7147. //
  7148. var params = {
  7149. caps: caps
  7150. };
  7151. callback = (callback || noop).bind(this)
  7152. return disguise(this._invoke(transaction, 'setAudioFormat', params, callback), this)
  7153. };
  7154. /**
  7155. * @callback module:core/abstracts.MediaElement~setAudioFormatCallback
  7156. * @param {external:Error} error
  7157. */
  7158. /**
  7159. * @deprecated
  7160. * Allows change the target bitrate for the media output, if the media is
  7161. * encoded using VP8 or H264. This method only works if it is called before the
  7162. * media starts to flow.
  7163. *
  7164. * @alias module:core/abstracts.MediaElement.setOutputBitrate
  7165. *
  7166. * @param {external:Integer} bitrate
  7167. * Configure the enconding media bitrate in bps
  7168. *
  7169. * @param {module:core/abstracts.MediaElement~setOutputBitrateCallback} [callback]
  7170. *
  7171. * @return {external:Promise}
  7172. */
  7173. MediaElement.prototype.setOutputBitrate = function(bitrate, callback){
  7174. var transaction = (arguments[0] instanceof Transaction)
  7175. ? Array.prototype.shift.apply(arguments)
  7176. : undefined;
  7177. //
  7178. // checkType('int', 'bitrate', bitrate, {required: true});
  7179. //
  7180. var params = {
  7181. bitrate: bitrate
  7182. };
  7183. callback = (callback || noop).bind(this)
  7184. return disguise(this._invoke(transaction, 'setOutputBitrate', params, callback), this)
  7185. };
  7186. /**
  7187. * @callback module:core/abstracts.MediaElement~setOutputBitrateCallback
  7188. * @param {external:Error} error
  7189. */
  7190. /**
  7191. * Sets the type of data for the video stream.
  7192. * <p>
  7193. * MediaElements that do not support configuration of video capabilities will
  7194. * throw a MEDIA_OBJECT_ILLEGAL_PARAM_ERROR exception
  7195. * </p>
  7196. *
  7197. * @alias module:core/abstracts.MediaElement.setVideoFormat
  7198. *
  7199. * @param {module:core/complexTypes.VideoCaps} caps
  7200. * The format for the stream of video
  7201. *
  7202. * @param {module:core/abstracts.MediaElement~setVideoFormatCallback} [callback]
  7203. *
  7204. * @return {external:Promise}
  7205. */
  7206. MediaElement.prototype.setVideoFormat = function(caps, callback){
  7207. var transaction = (arguments[0] instanceof Transaction)
  7208. ? Array.prototype.shift.apply(arguments)
  7209. : undefined;
  7210. //
  7211. // checkType('VideoCaps', 'caps', caps, {required: true});
  7212. //
  7213. var params = {
  7214. caps: caps
  7215. };
  7216. callback = (callback || noop).bind(this)
  7217. return disguise(this._invoke(transaction, 'setVideoFormat', params, callback), this)
  7218. };
  7219. /**
  7220. * @callback module:core/abstracts.MediaElement~setVideoFormatCallback
  7221. * @param {external:Error} error
  7222. */
  7223. /**
  7224. * @alias module:core/abstracts.MediaElement.constructorParams
  7225. */
  7226. MediaElement.constructorParams = {
  7227. };
  7228. /**
  7229. * @alias module:core/abstracts.MediaElement.events
  7230. *
  7231. * @extends module:core/abstracts.MediaObject.events
  7232. */
  7233. MediaElement.events = MediaObject.events.concat(['ElementConnected', 'ElementDisconnected', 'MediaFlowInStateChange', 'MediaFlowOutStateChange', 'MediaTranscodingStateChange']);
  7234. /**
  7235. * Checker for {@link module:core/abstracts.MediaElement}
  7236. *
  7237. * @memberof module:core/abstracts
  7238. *
  7239. * @param {external:String} key
  7240. * @param {module:core/abstracts.MediaElement} value
  7241. */
  7242. function checkMediaElement(key, value)
  7243. {
  7244. if(!(value instanceof MediaElement))
  7245. throw ChecktypeError(key, MediaElement, value);
  7246. };
  7247. module.exports = MediaElement;
  7248. MediaElement.check = checkMediaElement;
  7249. },{"./MediaObject":35,"async":"async","inherits":"inherits","kurento-client":"kurento-client","promisecallback":"promisecallback"}],35:[function(require,module,exports){
  7250. /* Autogenerated with Kurento Idl */
  7251. /*
  7252. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  7253. *
  7254. * Licensed under the Apache License, Version 2.0 (the "License");
  7255. * you may not use this file except in compliance with the License.
  7256. * You may obtain a copy of the License at
  7257. *
  7258. * http://www.apache.org/licenses/LICENSE-2.0
  7259. *
  7260. * Unless required by applicable law or agreed to in writing, software
  7261. * distributed under the License is distributed on an "AS IS" BASIS,
  7262. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7263. * See the License for the specific language governing permissions and
  7264. * limitations under the License.
  7265. */
  7266. var inherits = require('inherits');
  7267. var kurentoClient = require('kurento-client');
  7268. var disguise = kurentoClient.disguise;
  7269. var checkType = kurentoClient.checkType;
  7270. var ChecktypeError = checkType.ChecktypeError;
  7271. var Transaction = kurentoClient.TransactionsManager.Transaction;
  7272. var promiseCallback = require('promisecallback');
  7273. var EventEmitter = require('events').EventEmitter;
  7274. function noop(error, result) {
  7275. if (error) console.trace(error);
  7276. return result
  7277. };
  7278. /**
  7279. * @classdesc
  7280. * Base interface used to manage capabilities common to all Kurento elements.
  7281. * <h4>Properties</h4>
  7282. * <ul>
  7283. * <li>
  7284. * <b>id</b>: unique identifier assigned to this <code>MediaObject</code>
  7285. * at
  7286. * instantiation time. {@link module:core.MediaPipeline MediaPipeline} IDs
  7287. * are generated with a GUID
  7288. * followed by suffix <code>_kurento.MediaPipeline</code>.
  7289. * {@link module:core/abstracts.MediaElement MediaElement} IDs are also a
  7290. * GUID with suffix
  7291. * <code>_kurento.{ElementType}</code> and prefixed by parent's ID.
  7292. * <blockquote>
  7293. * <dl>
  7294. * <dt><i>MediaPipeline ID example</i></dt>
  7295. * <dd>
  7296. * <code>
  7297. * 907cac3a-809a-4bbe-a93e-ae7e944c5cae_kurento.MediaPipeline
  7298. * </code>
  7299. * </dd>
  7300. * <dt><i>MediaElement ID example</i></dt>
  7301. * <dd>
  7302. * <code>
  7303. * 907cac3a-809a-4bbe-a93e-ae7e944c5cae_kurento.MediaPipeline/403da25a-805b-4cf1-8c55-f190588e6c9b_kurento.WebRtcEndpoint
  7304. * </code>
  7305. * </dd>
  7306. * </dl>
  7307. * </blockquote>
  7308. * </li>
  7309. * <li>
  7310. * <b>name</b>: free text intended to provide a friendly name for this
  7311. * <code>MediaObject</code>. Its default value is the same as the ID.
  7312. * </li>
  7313. * <li>
  7314. * <b>tags</b>: key-value pairs intended for applications to associate
  7315. * metadata
  7316. * to this <code>MediaObject</code> instance.
  7317. * </li>
  7318. * </ul>
  7319. * <p></p>
  7320. * <h4>Events</h4>
  7321. * <ul>
  7322. * <li>
  7323. * <b>ErrorEvent</b>: reports asynchronous error events. It is recommended
  7324. * to
  7325. * always subscribe a listener to this event, as regular error from the
  7326. * pipeline will be notified through it, instead of through an exception
  7327. * when
  7328. * invoking a method.
  7329. * </li>
  7330. * </ul>
  7331. *
  7332. * @abstract
  7333. * @extends external:EventEmitter
  7334. *
  7335. * @constructor module:core/abstracts.MediaObject
  7336. *
  7337. * @fires {@link module:core#event:Error Error}
  7338. */
  7339. function MediaObject(){
  7340. MediaObject.super_.call(this);
  7341. var self = this;
  7342. //
  7343. // Define object properties
  7344. //
  7345. /**
  7346. * Unique identifier of this object
  7347. *
  7348. * @public
  7349. * @readonly
  7350. * @member {external:Number} id
  7351. */
  7352. this.once('_id', function(error, id)
  7353. {
  7354. if(error)
  7355. return Object.defineProperties(this,
  7356. {
  7357. '_createError': {value: error},
  7358. 'id': {value: null, enumerable: true}
  7359. });
  7360. Object.defineProperty(this, 'id',
  7361. {
  7362. configurable: true,
  7363. enumerable: true,
  7364. value: id
  7365. });
  7366. })
  7367. //
  7368. // Subscribe and unsubscribe events on the server when adding and removing
  7369. // event listeners on this MediaObject
  7370. //
  7371. var subscriptions = {};
  7372. this.on('removeListener', function(event, listener)
  7373. {
  7374. // Blacklisted events
  7375. if(event[0] == '_'
  7376. || event == 'release'
  7377. || event == 'newListener')
  7378. return;
  7379. var count = EventEmitter.listenerCount(this, event);
  7380. if(count) return;
  7381. var token = subscriptions[event];
  7382. var params =
  7383. {
  7384. object: this,
  7385. subscription: token.value,
  7386. sessionId: token.sessionId
  7387. };
  7388. this.emit('_rpc', undefined, 'unsubscribe', params, function(error)
  7389. {
  7390. if(error) return self.emit('error', error);
  7391. delete subscriptions[event];
  7392. });
  7393. });
  7394. this.on('newListener', function(event, listener)
  7395. {
  7396. // Blacklisted events
  7397. if(event[0] == '_'
  7398. || event == 'release')
  7399. return;
  7400. var constructor = this.constructor;
  7401. if(constructor.events.indexOf(event) < 0)
  7402. throw new SyntaxError(constructor.name+" doesn't accept events of type '"+event+"'")
  7403. var count = EventEmitter.listenerCount(this, event);
  7404. if(count) return;
  7405. var params =
  7406. {
  7407. object: this,
  7408. type: event
  7409. };
  7410. this.emit('_rpc', undefined, 'subscribe', params, function(error, token)
  7411. {
  7412. if(error) return self.emit('error', error);
  7413. subscriptions[event] = token;
  7414. });
  7415. });
  7416. };
  7417. inherits(MediaObject, EventEmitter);
  7418. //
  7419. // Public properties
  7420. //
  7421. /**
  7422. * Children of this <code>MediaObject</code>.
  7423. *
  7424. * @alias module:core/abstracts.MediaObject#getChildren
  7425. *
  7426. * @param {module:core/abstracts.MediaObject~getChildrenCallback} [callback]
  7427. *
  7428. * @return {external:Promise}
  7429. */
  7430. MediaObject.prototype.getChildren = function(callback){
  7431. var transaction = (arguments[0] instanceof Transaction)
  7432. ? Array.prototype.shift.apply(arguments)
  7433. : undefined;
  7434. var usePromise = false;
  7435. if (callback == undefined) {
  7436. usePromise = true;
  7437. }
  7438. if(!arguments.length) callback = undefined;
  7439. callback = (callback || noop).bind(this)
  7440. if (usePromise) {
  7441. var self = this;
  7442. var promise = new Promise(function(resolve, reject) {
  7443. function callback2(error, values) {
  7444. resolve(values)
  7445. }
  7446. self._invoke(transaction, 'getChildren', function(error, result) {
  7447. if (error) return callback(error);
  7448. self.emit('_describe', result, callback2);
  7449. })
  7450. });
  7451. return promise;
  7452. } else {
  7453. return disguise(this._invoke(transaction, 'getChildren', function(error, result) {
  7454. if (error) return callback(error);
  7455. this.emit('_describe', result, callback);
  7456. }), this)
  7457. }
  7458. };
  7459. /**
  7460. * @callback module:core/abstracts.MediaObject~getChildrenCallback
  7461. * @param {external:Error} error
  7462. * @param {module:core/abstracts.MediaObject} result
  7463. */
  7464. /**
  7465. * Children of this <code>MediaObject</code>.
  7466. * @deprecated Use children instead.
  7467. *
  7468. * @alias module:core/abstracts.MediaObject#getChilds
  7469. *
  7470. * @param {module:core/abstracts.MediaObject~getChildsCallback} [callback]
  7471. *
  7472. * @return {external:Promise}
  7473. */
  7474. MediaObject.prototype.getChilds = function(callback){
  7475. var transaction = (arguments[0] instanceof Transaction)
  7476. ? Array.prototype.shift.apply(arguments)
  7477. : undefined;
  7478. var usePromise = false;
  7479. if (callback == undefined) {
  7480. usePromise = true;
  7481. }
  7482. if(!arguments.length) callback = undefined;
  7483. callback = (callback || noop).bind(this)
  7484. if (usePromise) {
  7485. var self = this;
  7486. var promise = new Promise(function(resolve, reject) {
  7487. function callback2(error, values) {
  7488. resolve(values)
  7489. }
  7490. self._invoke(transaction, 'getChilds', function(error, result) {
  7491. if (error) return callback(error);
  7492. self.emit('_describe', result, callback2);
  7493. })
  7494. });
  7495. return promise;
  7496. } else {
  7497. return disguise(this._invoke(transaction, 'getChilds', function(error, result) {
  7498. if (error) return callback(error);
  7499. this.emit('_describe', result, callback);
  7500. }), this)
  7501. }
  7502. };
  7503. /**
  7504. * @callback module:core/abstracts.MediaObject~getChildsCallback
  7505. * @param {external:Error} error
  7506. * @param {module:core/abstracts.MediaObject} result
  7507. */
  7508. /**
  7509. * <code>MediaObject</code> creation time in seconds since Epoch.
  7510. *
  7511. * @alias module:core/abstracts.MediaObject#getCreationTime
  7512. *
  7513. * @param {module:core/abstracts.MediaObject~getCreationTimeCallback} [callback]
  7514. *
  7515. * @return {external:Promise}
  7516. */
  7517. MediaObject.prototype.getCreationTime = function(callback){
  7518. var transaction = (arguments[0] instanceof Transaction)
  7519. ? Array.prototype.shift.apply(arguments)
  7520. : undefined;
  7521. var usePromise = false;
  7522. if (callback == undefined) {
  7523. usePromise = true;
  7524. }
  7525. if(!arguments.length) callback = undefined;
  7526. callback = (callback || noop).bind(this)
  7527. return disguise(this._invoke(transaction, 'getCreationTime', callback), this)
  7528. };
  7529. /**
  7530. * @callback module:core/abstracts.MediaObject~getCreationTimeCallback
  7531. * @param {external:Error} error
  7532. * @param {external:Integer} result
  7533. */
  7534. /**
  7535. * {@link module:core.MediaPipeline MediaPipeline} to which this
  7536. * <code>MediaObject</code> belongs. It returns itself when invoked for a
  7537. * pipeline object.
  7538. *
  7539. * @alias module:core/abstracts.MediaObject#getMediaPipeline
  7540. *
  7541. * @param {module:core/abstracts.MediaObject~getMediaPipelineCallback} [callback]
  7542. *
  7543. * @return {external:Promise}
  7544. */
  7545. MediaObject.prototype.getMediaPipeline = function(callback){
  7546. var transaction = (arguments[0] instanceof Transaction)
  7547. ? Array.prototype.shift.apply(arguments)
  7548. : undefined;
  7549. var usePromise = false;
  7550. if (callback == undefined) {
  7551. usePromise = true;
  7552. }
  7553. if(!arguments.length) callback = undefined;
  7554. callback = (callback || noop).bind(this)
  7555. if (usePromise) {
  7556. var self = this;
  7557. var promise = new Promise(function(resolve, reject) {
  7558. function callback2(error, values) {
  7559. resolve(values)
  7560. }
  7561. self._invoke(transaction, 'getMediaPipeline', function(error, result) {
  7562. if (error) return callback(error);
  7563. self.emit('_describe', result, callback2);
  7564. })
  7565. });
  7566. return promise;
  7567. } else {
  7568. return disguise(this._invoke(transaction, 'getMediaPipeline', function(error, result) {
  7569. if (error) return callback(error);
  7570. this.emit('_describe', result, callback);
  7571. }), this)
  7572. }
  7573. };
  7574. /**
  7575. * @callback module:core/abstracts.MediaObject~getMediaPipelineCallback
  7576. * @param {external:Error} error
  7577. * @param {module:core.MediaPipeline} result
  7578. */
  7579. /**
  7580. * This <code>MediaObject</code>'s name.
  7581. * <p>
  7582. * This is just sugar to simplify developers' life debugging, it is not used
  7583. * internally for indexing nor identifying the objects. By default, it's the
  7584. * object's ID.
  7585. * </p>
  7586. *
  7587. * @alias module:core/abstracts.MediaObject#getName
  7588. *
  7589. * @param {module:core/abstracts.MediaObject~getNameCallback} [callback]
  7590. *
  7591. * @return {external:Promise}
  7592. */
  7593. MediaObject.prototype.getName = function(callback){
  7594. var transaction = (arguments[0] instanceof Transaction)
  7595. ? Array.prototype.shift.apply(arguments)
  7596. : undefined;
  7597. var usePromise = false;
  7598. if (callback == undefined) {
  7599. usePromise = true;
  7600. }
  7601. if(!arguments.length) callback = undefined;
  7602. callback = (callback || noop).bind(this)
  7603. return disguise(this._invoke(transaction, 'getName', callback), this)
  7604. };
  7605. /**
  7606. * @callback module:core/abstracts.MediaObject~getNameCallback
  7607. * @param {external:Error} error
  7608. * @param {external:String} result
  7609. */
  7610. /**
  7611. * This <code>MediaObject</code>'s name.
  7612. * <p>
  7613. * This is just sugar to simplify developers' life debugging, it is not used
  7614. * internally for indexing nor identifying the objects. By default, it's the
  7615. * object's ID.
  7616. * </p>
  7617. *
  7618. * @alias module:core/abstracts.MediaObject#setName
  7619. *
  7620. * @param {external:String} name
  7621. * @param {module:core/abstracts.MediaObject~setNameCallback} [callback]
  7622. *
  7623. * @return {external:Promise}
  7624. */
  7625. MediaObject.prototype.setName = function(name, callback){
  7626. var transaction = (arguments[0] instanceof Transaction)
  7627. ? Array.prototype.shift.apply(arguments)
  7628. : undefined;
  7629. //
  7630. // checkType('String', 'name', name, {required: true});
  7631. //
  7632. var params = {
  7633. name: name
  7634. };
  7635. callback = (callback || noop).bind(this)
  7636. return disguise(this._invoke(transaction, 'setName', params, callback), this)
  7637. };
  7638. /**
  7639. * @callback module:core/abstracts.MediaObject~setNameCallback
  7640. * @param {external:Error} error
  7641. */
  7642. /**
  7643. * Parent of this <code>MediaObject</code>.
  7644. * <p>
  7645. * The parent of a {@link module:core/abstracts.Hub Hub} or a {@link
  7646. * module:core/abstracts.MediaElement MediaElement} is its
  7647. * {@link module:core.MediaPipeline MediaPipeline}. A {@link
  7648. * module:core.MediaPipeline MediaPipeline} has no parent, so this
  7649. * property will be null.
  7650. * </p>
  7651. *
  7652. * @alias module:core/abstracts.MediaObject#getParent
  7653. *
  7654. * @param {module:core/abstracts.MediaObject~getParentCallback} [callback]
  7655. *
  7656. * @return {external:Promise}
  7657. */
  7658. MediaObject.prototype.getParent = function(callback){
  7659. var transaction = (arguments[0] instanceof Transaction)
  7660. ? Array.prototype.shift.apply(arguments)
  7661. : undefined;
  7662. var usePromise = false;
  7663. if (callback == undefined) {
  7664. usePromise = true;
  7665. }
  7666. if(!arguments.length) callback = undefined;
  7667. callback = (callback || noop).bind(this)
  7668. if (usePromise) {
  7669. var self = this;
  7670. var promise = new Promise(function(resolve, reject) {
  7671. function callback2(error, values) {
  7672. resolve(values)
  7673. }
  7674. self._invoke(transaction, 'getParent', function(error, result) {
  7675. if (error) return callback(error);
  7676. self.emit('_describe', result, callback2);
  7677. })
  7678. });
  7679. return promise;
  7680. } else {
  7681. return disguise(this._invoke(transaction, 'getParent', function(error, result) {
  7682. if (error) return callback(error);
  7683. this.emit('_describe', result, callback);
  7684. }), this)
  7685. }
  7686. };
  7687. /**
  7688. * @callback module:core/abstracts.MediaObject~getParentCallback
  7689. * @param {external:Error} error
  7690. * @param {module:core/abstracts.MediaObject} result
  7691. */
  7692. /**
  7693. * Flag activating or deactivating sending the element's tags in fired events.
  7694. *
  7695. * @alias module:core/abstracts.MediaObject#getSendTagsInEvents
  7696. *
  7697. * @param {module:core/abstracts.MediaObject~getSendTagsInEventsCallback} [callback]
  7698. *
  7699. * @return {external:Promise}
  7700. */
  7701. MediaObject.prototype.getSendTagsInEvents = function(callback){
  7702. var transaction = (arguments[0] instanceof Transaction)
  7703. ? Array.prototype.shift.apply(arguments)
  7704. : undefined;
  7705. var usePromise = false;
  7706. if (callback == undefined) {
  7707. usePromise = true;
  7708. }
  7709. if(!arguments.length) callback = undefined;
  7710. callback = (callback || noop).bind(this)
  7711. return disguise(this._invoke(transaction, 'getSendTagsInEvents', callback), this)
  7712. };
  7713. /**
  7714. * @callback module:core/abstracts.MediaObject~getSendTagsInEventsCallback
  7715. * @param {external:Error} error
  7716. * @param {external:Boolean} result
  7717. */
  7718. /**
  7719. * Flag activating or deactivating sending the element's tags in fired events.
  7720. *
  7721. * @alias module:core/abstracts.MediaObject#setSendTagsInEvents
  7722. *
  7723. * @param {external:Boolean} sendTagsInEvents
  7724. * @param {module:core/abstracts.MediaObject~setSendTagsInEventsCallback} [callback]
  7725. *
  7726. * @return {external:Promise}
  7727. */
  7728. MediaObject.prototype.setSendTagsInEvents = function(sendTagsInEvents, callback){
  7729. var transaction = (arguments[0] instanceof Transaction)
  7730. ? Array.prototype.shift.apply(arguments)
  7731. : undefined;
  7732. //
  7733. // checkType('boolean', 'sendTagsInEvents', sendTagsInEvents, {required: true});
  7734. //
  7735. var params = {
  7736. sendTagsInEvents: sendTagsInEvents
  7737. };
  7738. callback = (callback || noop).bind(this)
  7739. return disguise(this._invoke(transaction, 'setSendTagsInEvents', params, callback), this)
  7740. };
  7741. /**
  7742. * @callback module:core/abstracts.MediaObject~setSendTagsInEventsCallback
  7743. * @param {external:Error} error
  7744. */
  7745. //
  7746. // Public methods
  7747. //
  7748. /**
  7749. * Adds a new tag to this <code>MediaObject</code>.
  7750. * If the tag is already present, it changes the value.
  7751. *
  7752. * @alias module:core/abstracts.MediaObject.addTag
  7753. *
  7754. * @param {external:String} key
  7755. * Tag name.
  7756. *
  7757. * @param {external:String} value
  7758. * Value associated to this tag.
  7759. *
  7760. * @param {module:core/abstracts.MediaObject~addTagCallback} [callback]
  7761. *
  7762. * @return {external:Promise}
  7763. */
  7764. MediaObject.prototype.addTag = function(key, value, callback){
  7765. var transaction = (arguments[0] instanceof Transaction)
  7766. ? Array.prototype.shift.apply(arguments)
  7767. : undefined;
  7768. //
  7769. // checkType('String', 'key', key, {required: true});
  7770. //
  7771. // checkType('String', 'value', value, {required: true});
  7772. //
  7773. var params = {
  7774. key: key,
  7775. value: value
  7776. };
  7777. callback = (callback || noop).bind(this)
  7778. return disguise(this._invoke(transaction, 'addTag', params, callback), this)
  7779. };
  7780. /**
  7781. * @callback module:core/abstracts.MediaObject~addTagCallback
  7782. * @param {external:Error} error
  7783. */
  7784. /**
  7785. * Returns the value of given tag, or MEDIA_OBJECT_TAG_KEY_NOT_FOUND if tag is
  7786. * not defined.
  7787. *
  7788. * @alias module:core/abstracts.MediaObject.getTag
  7789. *
  7790. * @param {external:String} key
  7791. * Tag key.
  7792. *
  7793. * @param {module:core/abstracts.MediaObject~getTagCallback} [callback]
  7794. *
  7795. * @return {external:Promise}
  7796. */
  7797. MediaObject.prototype.getTag = function(key, callback){
  7798. var transaction = (arguments[0] instanceof Transaction)
  7799. ? Array.prototype.shift.apply(arguments)
  7800. : undefined;
  7801. //
  7802. // checkType('String', 'key', key, {required: true});
  7803. //
  7804. var params = {
  7805. key: key
  7806. };
  7807. callback = (callback || noop).bind(this)
  7808. return disguise(this._invoke(transaction, 'getTag', params, callback), this)
  7809. };
  7810. /**
  7811. * @callback module:core/abstracts.MediaObject~getTagCallback
  7812. * @param {external:Error} error
  7813. * @param {external:String} result
  7814. * The value associated to the given key.
  7815. */
  7816. /**
  7817. * Returns all tags attached to this <code>MediaObject</code>.
  7818. *
  7819. * @alias module:core/abstracts.MediaObject.getTags
  7820. *
  7821. * @param {module:core/abstracts.MediaObject~getTagsCallback} [callback]
  7822. *
  7823. * @return {external:Promise}
  7824. */
  7825. MediaObject.prototype.getTags = function(callback){
  7826. var transaction = (arguments[0] instanceof Transaction)
  7827. ? Array.prototype.shift.apply(arguments)
  7828. : undefined;
  7829. var usePromise = false;
  7830. if (callback == undefined) {
  7831. usePromise = true;
  7832. }
  7833. if(!arguments.length) callback = undefined;
  7834. callback = (callback || noop).bind(this)
  7835. return disguise(this._invoke(transaction, 'getTags', callback), this)
  7836. };
  7837. /**
  7838. * @callback module:core/abstracts.MediaObject~getTagsCallback
  7839. * @param {external:Error} error
  7840. * @param {module:core/complexTypes.Tag} result
  7841. * An array containing all key-value pairs associated with this
  7842. * <code>MediaObject</code>.
  7843. */
  7844. /**
  7845. * Removes an existing tag.
  7846. * Exists silently with no error if tag is not defined.
  7847. *
  7848. * @alias module:core/abstracts.MediaObject.removeTag
  7849. *
  7850. * @param {external:String} key
  7851. * Tag name to be removed
  7852. *
  7853. * @param {module:core/abstracts.MediaObject~removeTagCallback} [callback]
  7854. *
  7855. * @return {external:Promise}
  7856. */
  7857. MediaObject.prototype.removeTag = function(key, callback){
  7858. var transaction = (arguments[0] instanceof Transaction)
  7859. ? Array.prototype.shift.apply(arguments)
  7860. : undefined;
  7861. //
  7862. // checkType('String', 'key', key, {required: true});
  7863. //
  7864. var params = {
  7865. key: key
  7866. };
  7867. callback = (callback || noop).bind(this)
  7868. return disguise(this._invoke(transaction, 'removeTag', params, callback), this)
  7869. };
  7870. /**
  7871. * @callback module:core/abstracts.MediaObject~removeTagCallback
  7872. * @param {external:Error} error
  7873. */
  7874. function throwRpcNotReady()
  7875. {
  7876. throw new SyntaxError('RPC result is not ready, use .then() method instead');
  7877. };
  7878. /**
  7879. * Send a command to a media object
  7880. *
  7881. * @param {external:String} method - Command to be executed by the server
  7882. * @param {module:core/abstract.MediaObject.constructorParams} [params]
  7883. * @param {module:core/abstract.MediaObject~invokeCallback} callback
  7884. *
  7885. * @return {external:Promise}
  7886. */
  7887. Object.defineProperty(MediaObject.prototype, '_invoke',
  7888. {
  7889. enumerable: true,
  7890. value: function(transaction, method, params, callback){
  7891. var self = this;
  7892. // Fix optional parameters
  7893. if(params instanceof Function)
  7894. {
  7895. if(callback)
  7896. throw new SyntaxError("Nothing can be defined after the callback");
  7897. callback = params;
  7898. params = undefined;
  7899. };
  7900. var promise;
  7901. var error = this._createError;
  7902. if(error)
  7903. promise = Promise.reject(error)
  7904. else
  7905. {
  7906. promise = new Promise(function(resolve, reject)
  7907. {
  7908. // Generate request parameters
  7909. var params2 =
  7910. {
  7911. object: self,
  7912. operation: method
  7913. };
  7914. if(params)
  7915. params2.operationParams = params;
  7916. function callback(error, result)
  7917. {
  7918. if(error) return reject(error);
  7919. var value = result.value;
  7920. if(value === undefined)
  7921. value = self
  7922. resolve(value);
  7923. }
  7924. // Do request
  7925. self.emit('_rpc', transaction, 'invoke', params2, callback);
  7926. });
  7927. }
  7928. return promiseCallback(promise, callback, this)
  7929. }
  7930. })
  7931. /**
  7932. * @callback core/abstract.MediaObject~invokeCallback
  7933. * @param {external:Error} error
  7934. */
  7935. /**
  7936. * Explicity release a {@link module:core/abstract.MediaObject MediaObject} from memory
  7937. *
  7938. * All its descendants will be also released and collected
  7939. *
  7940. * @param {module:core/abstract.MediaObject~releaseCallback} callback
  7941. *
  7942. * @return {external:Promise}
  7943. */
  7944. MediaObject.prototype.release = function(callback){
  7945. var transaction = (arguments[0] instanceof Transaction)
  7946. ? Array.prototype.shift.apply(arguments)
  7947. : undefined;
  7948. var usePromise = false;
  7949. if (callback == undefined) {
  7950. usePromise = true;
  7951. }
  7952. if(!arguments.length) callback = undefined;
  7953. callback = (callback || noop).bind(this)
  7954. var self = this;
  7955. var promise;
  7956. var error = this._createError;
  7957. if(error)
  7958. promise = Promise.reject(error)
  7959. else
  7960. promise = new Promise(function(resolve, reject)
  7961. {
  7962. var params =
  7963. {
  7964. object: self
  7965. };
  7966. function callback(error)
  7967. {
  7968. if(error) return reject(error);
  7969. // Object was sucessfully released on the server,
  7970. // remove it from cache and all its events
  7971. Object.keys(self._events).forEach(function(event)
  7972. {
  7973. if(event[0] == '_'
  7974. || event == 'newListener'
  7975. || event == 'removeListener')
  7976. return;
  7977. self.removeAllListeners(event);
  7978. })
  7979. self.emit('release');
  7980. resolve();
  7981. }
  7982. self.emit('_rpc', transaction, 'release', params, callback);
  7983. });
  7984. return disguise(promiseCallback(promise, callback), this)
  7985. };
  7986. /**
  7987. * @callback core/abstract.MediaObject~releaseCallback
  7988. * @param {external:Error} error
  7989. */
  7990. // Promise interface ("thenable")
  7991. MediaObject.prototype.then = function(onFulfilled, onRejected){
  7992. if(this.id != null)
  7993. var promise = Promise.resolve(disguise.unthenable(this))
  7994. else if(this.id === null)
  7995. var promise = Promise.reject()
  7996. else {
  7997. var self = this
  7998. var promise = new Promise(function(resolve, reject) {
  7999. return self.once('_id', function(error, id) {
  8000. if(error) return reject(error);
  8001. resolve(disguise.unthenable(self));
  8002. })
  8003. })
  8004. }
  8005. promise = promise.then(onFulfilled ? onFulfilled.bind(this) :
  8006. function(result){return Promise.resolve(result)},
  8007. onRejected ? onRejected .bind(this) :
  8008. function(error) {return Promise.reject(error)});
  8009. return disguise(promise, this);
  8010. }
  8011. MediaObject.prototype.catch = function(onRejected)
  8012. {
  8013. this.then(null, onRejected);
  8014. }
  8015. Object.defineProperty(MediaObject.prototype, 'commited',
  8016. {
  8017. get: function(){return this.id !== undefined;}
  8018. });
  8019. /**
  8020. * @alias module:core/abstracts.MediaObject.constructorParams
  8021. */
  8022. MediaObject.constructorParams = {
  8023. };
  8024. /**
  8025. * @alias module:core/abstracts.MediaObject.events
  8026. */
  8027. MediaObject.events = ['Error'];
  8028. /**
  8029. * Checker for {@link module:core/abstracts.MediaObject}
  8030. *
  8031. * @memberof module:core/abstracts
  8032. *
  8033. * @param {external:String} key
  8034. * @param {module:core/abstracts.MediaObject} value
  8035. */
  8036. function checkMediaObject(key, value)
  8037. {
  8038. if(!(value instanceof MediaObject))
  8039. throw ChecktypeError(key, MediaObject, value);
  8040. };
  8041. module.exports = MediaObject;
  8042. MediaObject.check = checkMediaObject;
  8043. },{"events":21,"inherits":"inherits","kurento-client":"kurento-client","promisecallback":"promisecallback"}],36:[function(require,module,exports){
  8044. /* Autogenerated with Kurento Idl */
  8045. /*
  8046. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  8047. *
  8048. * Licensed under the Apache License, Version 2.0 (the "License");
  8049. * you may not use this file except in compliance with the License.
  8050. * You may obtain a copy of the License at
  8051. *
  8052. * http://www.apache.org/licenses/LICENSE-2.0
  8053. *
  8054. * Unless required by applicable law or agreed to in writing, software
  8055. * distributed under the License is distributed on an "AS IS" BASIS,
  8056. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8057. * See the License for the specific language governing permissions and
  8058. * limitations under the License.
  8059. */
  8060. var inherits = require('inherits');
  8061. var kurentoClient = require('kurento-client');
  8062. var disguise = kurentoClient.disguise;
  8063. var checkType = kurentoClient.checkType;
  8064. var ChecktypeError = checkType.ChecktypeError;
  8065. var Transaction = kurentoClient.TransactionsManager.Transaction;
  8066. var SessionEndpoint = require('./SessionEndpoint');
  8067. function noop(error, result) {
  8068. if (error) console.trace(error);
  8069. return result
  8070. };
  8071. /**
  8072. * @classdesc
  8073. * Interface implemented by Endpoints that require an SDP negotiation for the
  8074. * setup
  8075. * of a networked media session with remote peers.
  8076. * <p>The API provides the following functionality:</p>
  8077. * <ul>
  8078. * <li>Generate SDP offers.</li>
  8079. * <li>Process SDP offers.</li>
  8080. * <li>Configure SDP related params.</li>
  8081. * </ul>
  8082. *
  8083. * @abstract
  8084. * @extends module:core/abstracts.SessionEndpoint
  8085. *
  8086. * @constructor module:core/abstracts.SdpEndpoint
  8087. */
  8088. function SdpEndpoint(){
  8089. SdpEndpoint.super_.call(this);
  8090. };
  8091. inherits(SdpEndpoint, SessionEndpoint);
  8092. //
  8093. // Public properties
  8094. //
  8095. /**
  8096. * Maximum bitrate expected for the received audio stream.
  8097. * <p>
  8098. * This is used to put a limit on the bitrate that the remote peer will send
  8099. * to
  8100. * this endpoint. The net effect of setting this parameter is that
  8101. * <i>when Kurento generates an SDP Offer</i>, an 'Application Specific' (AS)
  8102. * maximum bandwidth attribute will be added to the SDP media section:
  8103. * <code>b=AS:{value}</code>.
  8104. * </p>
  8105. * <p>Note: This parameter has to be set before the SDP is generated.</p>
  8106. * <ul>
  8107. * <li>Unit: kbps (kilobits per second).</li>
  8108. * <li>Default: 0.</li>
  8109. * <li>0 = unconstrained.</li>
  8110. * </ul>
  8111. *
  8112. * @alias module:core/abstracts.SdpEndpoint#getMaxAudioRecvBandwidth
  8113. *
  8114. * @param {module:core/abstracts.SdpEndpoint~getMaxAudioRecvBandwidthCallback} [callback]
  8115. *
  8116. * @return {external:Promise}
  8117. */
  8118. SdpEndpoint.prototype.getMaxAudioRecvBandwidth = function(callback){
  8119. var transaction = (arguments[0] instanceof Transaction)
  8120. ? Array.prototype.shift.apply(arguments)
  8121. : undefined;
  8122. var usePromise = false;
  8123. if (callback == undefined) {
  8124. usePromise = true;
  8125. }
  8126. if(!arguments.length) callback = undefined;
  8127. callback = (callback || noop).bind(this)
  8128. return disguise(this._invoke(transaction, 'getMaxAudioRecvBandwidth', callback), this)
  8129. };
  8130. /**
  8131. * @callback module:core/abstracts.SdpEndpoint~getMaxAudioRecvBandwidthCallback
  8132. * @param {external:Error} error
  8133. * @param {external:Integer} result
  8134. */
  8135. /**
  8136. * Maximum bitrate expected for the received audio stream.
  8137. * <p>
  8138. * This is used to put a limit on the bitrate that the remote peer will send
  8139. * to
  8140. * this endpoint. The net effect of setting this parameter is that
  8141. * <i>when Kurento generates an SDP Offer</i>, an 'Application Specific' (AS)
  8142. * maximum bandwidth attribute will be added to the SDP media section:
  8143. * <code>b=AS:{value}</code>.
  8144. * </p>
  8145. * <p>Note: This parameter has to be set before the SDP is generated.</p>
  8146. * <ul>
  8147. * <li>Unit: kbps (kilobits per second).</li>
  8148. * <li>Default: 0.</li>
  8149. * <li>0 = unconstrained.</li>
  8150. * </ul>
  8151. *
  8152. * @alias module:core/abstracts.SdpEndpoint#setMaxAudioRecvBandwidth
  8153. *
  8154. * @param {external:Integer} maxAudioRecvBandwidth
  8155. * @param {module:core/abstracts.SdpEndpoint~setMaxAudioRecvBandwidthCallback} [callback]
  8156. *
  8157. * @return {external:Promise}
  8158. */
  8159. SdpEndpoint.prototype.setMaxAudioRecvBandwidth = function(maxAudioRecvBandwidth, callback){
  8160. var transaction = (arguments[0] instanceof Transaction)
  8161. ? Array.prototype.shift.apply(arguments)
  8162. : undefined;
  8163. //
  8164. // checkType('int', 'maxAudioRecvBandwidth', maxAudioRecvBandwidth, {required: true});
  8165. //
  8166. var params = {
  8167. maxAudioRecvBandwidth: maxAudioRecvBandwidth
  8168. };
  8169. callback = (callback || noop).bind(this)
  8170. return disguise(this._invoke(transaction, 'setMaxAudioRecvBandwidth', params, callback), this)
  8171. };
  8172. /**
  8173. * @callback module:core/abstracts.SdpEndpoint~setMaxAudioRecvBandwidthCallback
  8174. * @param {external:Error} error
  8175. */
  8176. /**
  8177. * Maximum bitrate expected for the received video stream.
  8178. * <p>
  8179. * This is used to put a limit on the bitrate that the remote peer will send
  8180. * to
  8181. * this endpoint. The net effect of setting this parameter is that
  8182. * <i>when Kurento generates an SDP Offer</i>, an 'Application Specific' (AS)
  8183. * maximum bandwidth attribute will be added to the SDP media section:
  8184. * <code>b=AS:{value}</code>.
  8185. * </p>
  8186. * <p>Note: This parameter has to be set before the SDP is generated.</p>
  8187. * <ul>
  8188. * <li>Unit: kbps (kilobits per second).</li>
  8189. * <li>Default: 0.</li>
  8190. * <li>0 = unconstrained.</li>
  8191. * </ul>
  8192. *
  8193. * @alias module:core/abstracts.SdpEndpoint#getMaxVideoRecvBandwidth
  8194. *
  8195. * @param {module:core/abstracts.SdpEndpoint~getMaxVideoRecvBandwidthCallback} [callback]
  8196. *
  8197. * @return {external:Promise}
  8198. */
  8199. SdpEndpoint.prototype.getMaxVideoRecvBandwidth = function(callback){
  8200. var transaction = (arguments[0] instanceof Transaction)
  8201. ? Array.prototype.shift.apply(arguments)
  8202. : undefined;
  8203. var usePromise = false;
  8204. if (callback == undefined) {
  8205. usePromise = true;
  8206. }
  8207. if(!arguments.length) callback = undefined;
  8208. callback = (callback || noop).bind(this)
  8209. return disguise(this._invoke(transaction, 'getMaxVideoRecvBandwidth', callback), this)
  8210. };
  8211. /**
  8212. * @callback module:core/abstracts.SdpEndpoint~getMaxVideoRecvBandwidthCallback
  8213. * @param {external:Error} error
  8214. * @param {external:Integer} result
  8215. */
  8216. /**
  8217. * Maximum bitrate expected for the received video stream.
  8218. * <p>
  8219. * This is used to put a limit on the bitrate that the remote peer will send
  8220. * to
  8221. * this endpoint. The net effect of setting this parameter is that
  8222. * <i>when Kurento generates an SDP Offer</i>, an 'Application Specific' (AS)
  8223. * maximum bandwidth attribute will be added to the SDP media section:
  8224. * <code>b=AS:{value}</code>.
  8225. * </p>
  8226. * <p>Note: This parameter has to be set before the SDP is generated.</p>
  8227. * <ul>
  8228. * <li>Unit: kbps (kilobits per second).</li>
  8229. * <li>Default: 0.</li>
  8230. * <li>0 = unconstrained.</li>
  8231. * </ul>
  8232. *
  8233. * @alias module:core/abstracts.SdpEndpoint#setMaxVideoRecvBandwidth
  8234. *
  8235. * @param {external:Integer} maxVideoRecvBandwidth
  8236. * @param {module:core/abstracts.SdpEndpoint~setMaxVideoRecvBandwidthCallback} [callback]
  8237. *
  8238. * @return {external:Promise}
  8239. */
  8240. SdpEndpoint.prototype.setMaxVideoRecvBandwidth = function(maxVideoRecvBandwidth, callback){
  8241. var transaction = (arguments[0] instanceof Transaction)
  8242. ? Array.prototype.shift.apply(arguments)
  8243. : undefined;
  8244. //
  8245. // checkType('int', 'maxVideoRecvBandwidth', maxVideoRecvBandwidth, {required: true});
  8246. //
  8247. var params = {
  8248. maxVideoRecvBandwidth: maxVideoRecvBandwidth
  8249. };
  8250. callback = (callback || noop).bind(this)
  8251. return disguise(this._invoke(transaction, 'setMaxVideoRecvBandwidth', params, callback), this)
  8252. };
  8253. /**
  8254. * @callback module:core/abstracts.SdpEndpoint~setMaxVideoRecvBandwidthCallback
  8255. * @param {external:Error} error
  8256. */
  8257. //
  8258. // Public methods
  8259. //
  8260. /**
  8261. * Generates an SDP offer with media capabilities of the Endpoint.
  8262. * Throws:
  8263. * <ul>
  8264. * <li>
  8265. * SDP_END_POINT_ALREADY_NEGOTIATED If the endpoint is already negotiated.
  8266. * </li>
  8267. * <li>
  8268. * SDP_END_POINT_GENERATE_OFFER_ERROR if the generated offer is empty. This
  8269. * is
  8270. * most likely due to an internal error.
  8271. * </li>
  8272. * </ul>
  8273. *
  8274. * @alias module:core/abstracts.SdpEndpoint.generateOffer
  8275. *
  8276. * @param {module:core/abstracts.SdpEndpoint~generateOfferCallback} [callback]
  8277. *
  8278. * @return {external:Promise}
  8279. */
  8280. SdpEndpoint.prototype.generateOffer = function(callback){
  8281. var transaction = (arguments[0] instanceof Transaction)
  8282. ? Array.prototype.shift.apply(arguments)
  8283. : undefined;
  8284. var usePromise = false;
  8285. if (callback == undefined) {
  8286. usePromise = true;
  8287. }
  8288. if(!arguments.length) callback = undefined;
  8289. callback = (callback || noop).bind(this)
  8290. return disguise(this._invoke(transaction, 'generateOffer', callback), this)
  8291. };
  8292. /**
  8293. * @callback module:core/abstracts.SdpEndpoint~generateOfferCallback
  8294. * @param {external:Error} error
  8295. * @param {external:String} result
  8296. * The SDP offer.
  8297. */
  8298. /**
  8299. * Returns the local SDP.
  8300. * <ul>
  8301. * <li>
  8302. * No offer has been generated: returns null.
  8303. * </li>
  8304. * <li>
  8305. * Offer has been generated: returns the SDP offer.
  8306. * </li>
  8307. * <li>
  8308. * Offer has been generated and answer processed: returns the agreed SDP.
  8309. * </li>
  8310. * </ul>
  8311. *
  8312. * @alias module:core/abstracts.SdpEndpoint.getLocalSessionDescriptor
  8313. *
  8314. * @param {module:core/abstracts.SdpEndpoint~getLocalSessionDescriptorCallback} [callback]
  8315. *
  8316. * @return {external:Promise}
  8317. */
  8318. SdpEndpoint.prototype.getLocalSessionDescriptor = function(callback){
  8319. var transaction = (arguments[0] instanceof Transaction)
  8320. ? Array.prototype.shift.apply(arguments)
  8321. : undefined;
  8322. var usePromise = false;
  8323. if (callback == undefined) {
  8324. usePromise = true;
  8325. }
  8326. if(!arguments.length) callback = undefined;
  8327. callback = (callback || noop).bind(this)
  8328. return disguise(this._invoke(transaction, 'getLocalSessionDescriptor', callback), this)
  8329. };
  8330. /**
  8331. * @callback module:core/abstracts.SdpEndpoint~getLocalSessionDescriptorCallback
  8332. * @param {external:Error} error
  8333. * @param {external:String} result
  8334. * The last agreed SessionSpec.
  8335. */
  8336. /**
  8337. * This method returns the remote SDP.
  8338. * If the negotiation process is not complete, it will return NULL.
  8339. *
  8340. * @alias module:core/abstracts.SdpEndpoint.getRemoteSessionDescriptor
  8341. *
  8342. * @param {module:core/abstracts.SdpEndpoint~getRemoteSessionDescriptorCallback} [callback]
  8343. *
  8344. * @return {external:Promise}
  8345. */
  8346. SdpEndpoint.prototype.getRemoteSessionDescriptor = function(callback){
  8347. var transaction = (arguments[0] instanceof Transaction)
  8348. ? Array.prototype.shift.apply(arguments)
  8349. : undefined;
  8350. var usePromise = false;
  8351. if (callback == undefined) {
  8352. usePromise = true;
  8353. }
  8354. if(!arguments.length) callback = undefined;
  8355. callback = (callback || noop).bind(this)
  8356. return disguise(this._invoke(transaction, 'getRemoteSessionDescriptor', callback), this)
  8357. };
  8358. /**
  8359. * @callback module:core/abstracts.SdpEndpoint~getRemoteSessionDescriptorCallback
  8360. * @param {external:Error} error
  8361. * @param {external:String} result
  8362. * The last agreed User Agent session description.
  8363. */
  8364. /**
  8365. * Generates an SDP offer with media capabilities of the Endpoint.
  8366. * Throws:
  8367. * <ul>
  8368. * <li>
  8369. * SDP_PARSE_ERROR If the offer is empty or has errors.
  8370. * </li>
  8371. * <li>
  8372. * SDP_END_POINT_ALREADY_NEGOTIATED If the endpoint is already negotiated.
  8373. * </li>
  8374. * <li>
  8375. * SDP_END_POINT_PROCESS_ANSWER_ERROR if the result of processing the answer
  8376. * an empty string. This is most likely due to an internal error.
  8377. * </li>
  8378. * <li>
  8379. * SDP_END_POINT_NOT_OFFER_GENERATED If the method is invoked before the
  8380. * generateOffer method.
  8381. * </li>
  8382. * </ul>
  8383. *
  8384. * @alias module:core/abstracts.SdpEndpoint.processAnswer
  8385. *
  8386. * @param {external:String} answer
  8387. * SessionSpec answer from the remote User Agent
  8388. *
  8389. * @param {module:core/abstracts.SdpEndpoint~processAnswerCallback} [callback]
  8390. *
  8391. * @return {external:Promise}
  8392. */
  8393. SdpEndpoint.prototype.processAnswer = function(answer, callback){
  8394. var transaction = (arguments[0] instanceof Transaction)
  8395. ? Array.prototype.shift.apply(arguments)
  8396. : undefined;
  8397. //
  8398. // checkType('String', 'answer', answer, {required: true});
  8399. //
  8400. var params = {
  8401. answer: answer
  8402. };
  8403. callback = (callback || noop).bind(this)
  8404. return disguise(this._invoke(transaction, 'processAnswer', params, callback), this)
  8405. };
  8406. /**
  8407. * @callback module:core/abstracts.SdpEndpoint~processAnswerCallback
  8408. * @param {external:Error} error
  8409. * @param {external:String} result
  8410. * Updated SDP offer, based on the answer received.
  8411. */
  8412. /**
  8413. * Processes SDP offer of the remote peer, and generates an SDP answer based on
  8414. * the endpoint's capabilities.
  8415. * <p>
  8416. * If no matching capabilities are found, the SDP will contain no codecs.
  8417. * </p>
  8418. * Throws:
  8419. * <ul>
  8420. * <li>
  8421. * SDP_PARSE_ERROR If the offer is empty or has errors.
  8422. * </li>
  8423. * <li>
  8424. * SDP_END_POINT_ALREADY_NEGOTIATED If the endpoint is already negotiated.
  8425. * </li>
  8426. * <li>
  8427. * SDP_END_POINT_PROCESS_OFFER_ERROR if the generated offer is empty. This
  8428. * is
  8429. * most likely due to an internal error.
  8430. * </li>
  8431. * </ul>
  8432. *
  8433. * @alias module:core/abstracts.SdpEndpoint.processOffer
  8434. *
  8435. * @param {external:String} offer
  8436. * SessionSpec offer from the remote User Agent
  8437. *
  8438. * @param {module:core/abstracts.SdpEndpoint~processOfferCallback} [callback]
  8439. *
  8440. * @return {external:Promise}
  8441. */
  8442. SdpEndpoint.prototype.processOffer = function(offer, callback){
  8443. var transaction = (arguments[0] instanceof Transaction)
  8444. ? Array.prototype.shift.apply(arguments)
  8445. : undefined;
  8446. //
  8447. // checkType('String', 'offer', offer, {required: true});
  8448. //
  8449. var params = {
  8450. offer: offer
  8451. };
  8452. callback = (callback || noop).bind(this)
  8453. return disguise(this._invoke(transaction, 'processOffer', params, callback), this)
  8454. };
  8455. /**
  8456. * @callback module:core/abstracts.SdpEndpoint~processOfferCallback
  8457. * @param {external:Error} error
  8458. * @param {external:String} result
  8459. * The chosen configuration from the ones stated in the SDP offer.
  8460. */
  8461. /**
  8462. * @alias module:core/abstracts.SdpEndpoint.constructorParams
  8463. */
  8464. SdpEndpoint.constructorParams = {
  8465. };
  8466. /**
  8467. * @alias module:core/abstracts.SdpEndpoint.events
  8468. *
  8469. * @extends module:core/abstracts.SessionEndpoint.events
  8470. */
  8471. SdpEndpoint.events = SessionEndpoint.events;
  8472. /**
  8473. * Checker for {@link module:core/abstracts.SdpEndpoint}
  8474. *
  8475. * @memberof module:core/abstracts
  8476. *
  8477. * @param {external:String} key
  8478. * @param {module:core/abstracts.SdpEndpoint} value
  8479. */
  8480. function checkSdpEndpoint(key, value)
  8481. {
  8482. if(!(value instanceof SdpEndpoint))
  8483. throw ChecktypeError(key, SdpEndpoint, value);
  8484. };
  8485. module.exports = SdpEndpoint;
  8486. SdpEndpoint.check = checkSdpEndpoint;
  8487. },{"./SessionEndpoint":38,"inherits":"inherits","kurento-client":"kurento-client"}],37:[function(require,module,exports){
  8488. /* Autogenerated with Kurento Idl */
  8489. /*
  8490. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  8491. *
  8492. * Licensed under the Apache License, Version 2.0 (the "License");
  8493. * you may not use this file except in compliance with the License.
  8494. * You may obtain a copy of the License at
  8495. *
  8496. * http://www.apache.org/licenses/LICENSE-2.0
  8497. *
  8498. * Unless required by applicable law or agreed to in writing, software
  8499. * distributed under the License is distributed on an "AS IS" BASIS,
  8500. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8501. * See the License for the specific language governing permissions and
  8502. * limitations under the License.
  8503. */
  8504. var inherits = require('inherits');
  8505. var kurentoClient = require('kurento-client');
  8506. var disguise = kurentoClient.disguise;
  8507. var checkType = kurentoClient.checkType;
  8508. var ChecktypeError = checkType.ChecktypeError;
  8509. var Transaction = kurentoClient.TransactionsManager.Transaction;
  8510. var MediaObject = require('./MediaObject');
  8511. function noop(error, result) {
  8512. if (error) console.trace(error);
  8513. return result
  8514. };
  8515. /**
  8516. * @classdesc
  8517. * This is a standalone object for managing the MediaServer
  8518. *
  8519. * @abstract
  8520. * @extends module:core/abstracts.MediaObject
  8521. *
  8522. * @constructor module:core/abstracts.ServerManager
  8523. *
  8524. * @fires {@link module:core#event:ObjectCreated ObjectCreated}
  8525. * @fires {@link module:core#event:ObjectDestroyed ObjectDestroyed}
  8526. */
  8527. function ServerManager(){
  8528. ServerManager.super_.call(this);
  8529. };
  8530. inherits(ServerManager, MediaObject);
  8531. //
  8532. // Public properties
  8533. //
  8534. /**
  8535. * Server information, version, modules, factories, etc
  8536. *
  8537. * @alias module:core/abstracts.ServerManager#getInfo
  8538. *
  8539. * @param {module:core/abstracts.ServerManager~getInfoCallback} [callback]
  8540. *
  8541. * @return {external:Promise}
  8542. */
  8543. ServerManager.prototype.getInfo = function(callback){
  8544. var transaction = (arguments[0] instanceof Transaction)
  8545. ? Array.prototype.shift.apply(arguments)
  8546. : undefined;
  8547. var usePromise = false;
  8548. if (callback == undefined) {
  8549. usePromise = true;
  8550. }
  8551. if(!arguments.length) callback = undefined;
  8552. callback = (callback || noop).bind(this)
  8553. return disguise(this._invoke(transaction, 'getInfo', callback), this)
  8554. };
  8555. /**
  8556. * @callback module:core/abstracts.ServerManager~getInfoCallback
  8557. * @param {external:Error} error
  8558. * @param {module:core/complexTypes.ServerInfo} result
  8559. */
  8560. /**
  8561. * Metadata stored in the server
  8562. *
  8563. * @alias module:core/abstracts.ServerManager#getMetadata
  8564. *
  8565. * @param {module:core/abstracts.ServerManager~getMetadataCallback} [callback]
  8566. *
  8567. * @return {external:Promise}
  8568. */
  8569. ServerManager.prototype.getMetadata = function(callback){
  8570. var transaction = (arguments[0] instanceof Transaction)
  8571. ? Array.prototype.shift.apply(arguments)
  8572. : undefined;
  8573. var usePromise = false;
  8574. if (callback == undefined) {
  8575. usePromise = true;
  8576. }
  8577. if(!arguments.length) callback = undefined;
  8578. callback = (callback || noop).bind(this)
  8579. return disguise(this._invoke(transaction, 'getMetadata', callback), this)
  8580. };
  8581. /**
  8582. * @callback module:core/abstracts.ServerManager~getMetadataCallback
  8583. * @param {external:Error} error
  8584. * @param {external:String} result
  8585. */
  8586. /**
  8587. * All the pipelines available in the server
  8588. *
  8589. * @alias module:core/abstracts.ServerManager#getPipelines
  8590. *
  8591. * @param {module:core/abstracts.ServerManager~getPipelinesCallback} [callback]
  8592. *
  8593. * @return {external:Promise}
  8594. */
  8595. ServerManager.prototype.getPipelines = function(callback){
  8596. var transaction = (arguments[0] instanceof Transaction)
  8597. ? Array.prototype.shift.apply(arguments)
  8598. : undefined;
  8599. var usePromise = false;
  8600. if (callback == undefined) {
  8601. usePromise = true;
  8602. }
  8603. if(!arguments.length) callback = undefined;
  8604. callback = (callback || noop).bind(this)
  8605. if (usePromise) {
  8606. var self = this;
  8607. var promise = new Promise(function(resolve, reject) {
  8608. function callback2(error, values) {
  8609. resolve(values)
  8610. }
  8611. self._invoke(transaction, 'getPipelines', function(error, result) {
  8612. if (error) return callback(error);
  8613. self.emit('_describe', result, callback2);
  8614. })
  8615. });
  8616. return promise;
  8617. } else {
  8618. return disguise(this._invoke(transaction, 'getPipelines', function(error, result) {
  8619. if (error) return callback(error);
  8620. this.emit('_describe', result, callback);
  8621. }), this)
  8622. }
  8623. };
  8624. /**
  8625. * @callback module:core/abstracts.ServerManager~getPipelinesCallback
  8626. * @param {external:Error} error
  8627. * @param {module:core.MediaPipeline} result
  8628. */
  8629. /**
  8630. * All active sessions in the server
  8631. *
  8632. * @alias module:core/abstracts.ServerManager#getSessions
  8633. *
  8634. * @param {module:core/abstracts.ServerManager~getSessionsCallback} [callback]
  8635. *
  8636. * @return {external:Promise}
  8637. */
  8638. ServerManager.prototype.getSessions = function(callback){
  8639. var transaction = (arguments[0] instanceof Transaction)
  8640. ? Array.prototype.shift.apply(arguments)
  8641. : undefined;
  8642. var usePromise = false;
  8643. if (callback == undefined) {
  8644. usePromise = true;
  8645. }
  8646. if(!arguments.length) callback = undefined;
  8647. callback = (callback || noop).bind(this)
  8648. return disguise(this._invoke(transaction, 'getSessions', callback), this)
  8649. };
  8650. /**
  8651. * @callback module:core/abstracts.ServerManager~getSessionsCallback
  8652. * @param {external:Error} error
  8653. * @param {external:String} result
  8654. */
  8655. //
  8656. // Public methods
  8657. //
  8658. /**
  8659. * Number of CPU cores that the media server can use.
  8660. * <p>
  8661. * Linux processes can be configured to use only a subset of the cores that
  8662. * are
  8663. * available in the system, via the process affinity settings
  8664. * (<strong>sched_setaffinity(2)</strong>). With this method it is possible to
  8665. * know the number of cores that the media server can use in the machine where
  8666. * is running.
  8667. * </p>
  8668. * <p>
  8669. * For example, it's possible to limit the core affinity inside a Docker
  8670. * container by running with a command such as
  8671. * <em>docker run --cpuset-cpus='0,1'</em>.
  8672. * </p>
  8673. * <p>
  8674. * Note that the return value represents the number of
  8675. * <em>logical</em> processing units available, i.e. CPU cores including
  8676. * Hyper-Threading.
  8677. * </p>
  8678. *
  8679. * @alias module:core/abstracts.ServerManager.getCpuCount
  8680. *
  8681. * @param {module:core/abstracts.ServerManager~getCpuCountCallback} [callback]
  8682. *
  8683. * @return {external:Promise}
  8684. */
  8685. ServerManager.prototype.getCpuCount = function(callback){
  8686. var transaction = (arguments[0] instanceof Transaction)
  8687. ? Array.prototype.shift.apply(arguments)
  8688. : undefined;
  8689. var usePromise = false;
  8690. if (callback == undefined) {
  8691. usePromise = true;
  8692. }
  8693. if(!arguments.length) callback = undefined;
  8694. callback = (callback || noop).bind(this)
  8695. return disguise(this._invoke(transaction, 'getCpuCount', callback), this)
  8696. };
  8697. /**
  8698. * @callback module:core/abstracts.ServerManager~getCpuCountCallback
  8699. * @param {external:Error} error
  8700. * @param {external:Integer} result
  8701. * Number of CPU cores available for the media server.
  8702. */
  8703. /**
  8704. * Returns the kmd associated to a module
  8705. *
  8706. * @alias module:core/abstracts.ServerManager.getKmd
  8707. *
  8708. * @param {external:String} moduleName
  8709. * Name of the module to get its kmd file
  8710. *
  8711. * @param {module:core/abstracts.ServerManager~getKmdCallback} [callback]
  8712. *
  8713. * @return {external:Promise}
  8714. */
  8715. ServerManager.prototype.getKmd = function(moduleName, callback){
  8716. var transaction = (arguments[0] instanceof Transaction)
  8717. ? Array.prototype.shift.apply(arguments)
  8718. : undefined;
  8719. //
  8720. // checkType('String', 'moduleName', moduleName, {required: true});
  8721. //
  8722. var params = {
  8723. moduleName: moduleName
  8724. };
  8725. callback = (callback || noop).bind(this)
  8726. return disguise(this._invoke(transaction, 'getKmd', params, callback), this)
  8727. };
  8728. /**
  8729. * @callback module:core/abstracts.ServerManager~getKmdCallback
  8730. * @param {external:Error} error
  8731. * @param {external:String} result
  8732. * The kmd file.
  8733. */
  8734. /**
  8735. * Average CPU usage of the server.
  8736. * <p>
  8737. * This method measures the average CPU usage of the media server during the
  8738. * requested interval. Normally you will want to choose an interval between
  8739. * 1000
  8740. * and 10000 ms.
  8741. * </p>
  8742. * <p>
  8743. * The returned value represents the global system CPU usage of the media
  8744. * server,
  8745. * as an average across all processing units (CPU cores).
  8746. * </p>
  8747. *
  8748. * @alias module:core/abstracts.ServerManager.getUsedCpu
  8749. *
  8750. * @param {external:Integer} interval
  8751. * Time to measure the average CPU usage, in milliseconds.
  8752. *
  8753. * @param {module:core/abstracts.ServerManager~getUsedCpuCallback} [callback]
  8754. *
  8755. * @return {external:Promise}
  8756. */
  8757. ServerManager.prototype.getUsedCpu = function(interval, callback){
  8758. var transaction = (arguments[0] instanceof Transaction)
  8759. ? Array.prototype.shift.apply(arguments)
  8760. : undefined;
  8761. //
  8762. // checkType('int', 'interval', interval, {required: true});
  8763. //
  8764. var params = {
  8765. interval: interval
  8766. };
  8767. callback = (callback || noop).bind(this)
  8768. return disguise(this._invoke(transaction, 'getUsedCpu', params, callback), this)
  8769. };
  8770. /**
  8771. * @callback module:core/abstracts.ServerManager~getUsedCpuCallback
  8772. * @param {external:Error} error
  8773. * @param {external:Number} result
  8774. * CPU usage %.
  8775. */
  8776. /**
  8777. * Returns the amount of memory that the server is using, in KiB
  8778. *
  8779. * @alias module:core/abstracts.ServerManager.getUsedMemory
  8780. *
  8781. * @param {module:core/abstracts.ServerManager~getUsedMemoryCallback} [callback]
  8782. *
  8783. * @return {external:Promise}
  8784. */
  8785. ServerManager.prototype.getUsedMemory = function(callback){
  8786. var transaction = (arguments[0] instanceof Transaction)
  8787. ? Array.prototype.shift.apply(arguments)
  8788. : undefined;
  8789. var usePromise = false;
  8790. if (callback == undefined) {
  8791. usePromise = true;
  8792. }
  8793. if(!arguments.length) callback = undefined;
  8794. callback = (callback || noop).bind(this)
  8795. return disguise(this._invoke(transaction, 'getUsedMemory', callback), this)
  8796. };
  8797. /**
  8798. * @callback module:core/abstracts.ServerManager~getUsedMemoryCallback
  8799. * @param {external:Error} error
  8800. * @param {external:int64} result
  8801. * Used memory, in KiB.
  8802. */
  8803. /**
  8804. * @alias module:core/abstracts.ServerManager.constructorParams
  8805. */
  8806. ServerManager.constructorParams = {
  8807. };
  8808. /**
  8809. * @alias module:core/abstracts.ServerManager.events
  8810. *
  8811. * @extends module:core/abstracts.MediaObject.events
  8812. */
  8813. ServerManager.events = MediaObject.events.concat(['ObjectCreated', 'ObjectDestroyed']);
  8814. /**
  8815. * Checker for {@link module:core/abstracts.ServerManager}
  8816. *
  8817. * @memberof module:core/abstracts
  8818. *
  8819. * @param {external:String} key
  8820. * @param {module:core/abstracts.ServerManager} value
  8821. */
  8822. function checkServerManager(key, value)
  8823. {
  8824. if(!(value instanceof ServerManager))
  8825. throw ChecktypeError(key, ServerManager, value);
  8826. };
  8827. module.exports = ServerManager;
  8828. ServerManager.check = checkServerManager;
  8829. },{"./MediaObject":35,"inherits":"inherits","kurento-client":"kurento-client"}],38:[function(require,module,exports){
  8830. /* Autogenerated with Kurento Idl */
  8831. /*
  8832. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  8833. *
  8834. * Licensed under the Apache License, Version 2.0 (the "License");
  8835. * you may not use this file except in compliance with the License.
  8836. * You may obtain a copy of the License at
  8837. *
  8838. * http://www.apache.org/licenses/LICENSE-2.0
  8839. *
  8840. * Unless required by applicable law or agreed to in writing, software
  8841. * distributed under the License is distributed on an "AS IS" BASIS,
  8842. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8843. * See the License for the specific language governing permissions and
  8844. * limitations under the License.
  8845. */
  8846. var inherits = require('inherits');
  8847. var kurentoClient = require('kurento-client');
  8848. var disguise = kurentoClient.disguise;
  8849. var ChecktypeError = kurentoClient.checkType.ChecktypeError;
  8850. var Endpoint = require('./Endpoint');
  8851. /**
  8852. * @classdesc
  8853. * All networked Endpoints that require to manage connection sessions with
  8854. * remote peers implement this interface.
  8855. *
  8856. * @abstract
  8857. * @extends module:core/abstracts.Endpoint
  8858. *
  8859. * @constructor module:core/abstracts.SessionEndpoint
  8860. *
  8861. * @fires {@link module:core#event:MediaSessionStarted MediaSessionStarted}
  8862. * @fires {@link module:core#event:MediaSessionTerminated MediaSessionTerminated}
  8863. */
  8864. function SessionEndpoint(){
  8865. SessionEndpoint.super_.call(this);
  8866. };
  8867. inherits(SessionEndpoint, Endpoint);
  8868. /**
  8869. * @alias module:core/abstracts.SessionEndpoint.constructorParams
  8870. */
  8871. SessionEndpoint.constructorParams = {
  8872. };
  8873. /**
  8874. * @alias module:core/abstracts.SessionEndpoint.events
  8875. *
  8876. * @extends module:core/abstracts.Endpoint.events
  8877. */
  8878. SessionEndpoint.events = Endpoint.events.concat(['MediaSessionStarted', 'MediaSessionTerminated']);
  8879. /**
  8880. * Checker for {@link module:core/abstracts.SessionEndpoint}
  8881. *
  8882. * @memberof module:core/abstracts
  8883. *
  8884. * @param {external:String} key
  8885. * @param {module:core/abstracts.SessionEndpoint} value
  8886. */
  8887. function checkSessionEndpoint(key, value)
  8888. {
  8889. if(!(value instanceof SessionEndpoint))
  8890. throw ChecktypeError(key, SessionEndpoint, value);
  8891. };
  8892. module.exports = SessionEndpoint;
  8893. SessionEndpoint.check = checkSessionEndpoint;
  8894. },{"./Endpoint":31,"inherits":"inherits","kurento-client":"kurento-client"}],39:[function(require,module,exports){
  8895. /* Autogenerated with Kurento Idl */
  8896. /*
  8897. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  8898. *
  8899. * Licensed under the Apache License, Version 2.0 (the "License");
  8900. * you may not use this file except in compliance with the License.
  8901. * You may obtain a copy of the License at
  8902. *
  8903. * http://www.apache.org/licenses/LICENSE-2.0
  8904. *
  8905. * Unless required by applicable law or agreed to in writing, software
  8906. * distributed under the License is distributed on an "AS IS" BASIS,
  8907. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8908. * See the License for the specific language governing permissions and
  8909. * limitations under the License.
  8910. */
  8911. var inherits = require('inherits');
  8912. var kurentoClient = require('kurento-client');
  8913. var disguise = kurentoClient.disguise;
  8914. var checkType = kurentoClient.checkType;
  8915. var ChecktypeError = checkType.ChecktypeError;
  8916. var Transaction = kurentoClient.TransactionsManager.Transaction;
  8917. var Endpoint = require('./Endpoint');
  8918. function noop(error, result) {
  8919. if (error) console.trace(error);
  8920. return result
  8921. };
  8922. /**
  8923. * @classdesc
  8924. * Interface for endpoints the require a URI to work.
  8925. * An example of this, would be a :rom:cls:`PlayerEndpoint` whose URI property
  8926. * could be used to locate a file to stream.
  8927. *
  8928. * @abstract
  8929. * @extends module:core/abstracts.Endpoint
  8930. *
  8931. * @constructor module:core/abstracts.UriEndpoint
  8932. *
  8933. * @fires {@link module:core#event:UriEndpointStateChanged UriEndpointStateChanged}
  8934. */
  8935. function UriEndpoint(){
  8936. UriEndpoint.super_.call(this);
  8937. };
  8938. inherits(UriEndpoint, Endpoint);
  8939. //
  8940. // Public properties
  8941. //
  8942. /**
  8943. * State of the endpoint
  8944. *
  8945. * @alias module:core/abstracts.UriEndpoint#getState
  8946. *
  8947. * @param {module:core/abstracts.UriEndpoint~getStateCallback} [callback]
  8948. *
  8949. * @return {external:Promise}
  8950. */
  8951. UriEndpoint.prototype.getState = function(callback){
  8952. var transaction = (arguments[0] instanceof Transaction)
  8953. ? Array.prototype.shift.apply(arguments)
  8954. : undefined;
  8955. var usePromise = false;
  8956. if (callback == undefined) {
  8957. usePromise = true;
  8958. }
  8959. if(!arguments.length) callback = undefined;
  8960. callback = (callback || noop).bind(this)
  8961. return disguise(this._invoke(transaction, 'getState', callback), this)
  8962. };
  8963. /**
  8964. * @callback module:core/abstracts.UriEndpoint~getStateCallback
  8965. * @param {external:Error} error
  8966. * @param {module:core/complexTypes.UriEndpointState} result
  8967. */
  8968. /**
  8969. * The uri for this endpoint.
  8970. *
  8971. * @alias module:core/abstracts.UriEndpoint#getUri
  8972. *
  8973. * @param {module:core/abstracts.UriEndpoint~getUriCallback} [callback]
  8974. *
  8975. * @return {external:Promise}
  8976. */
  8977. UriEndpoint.prototype.getUri = function(callback){
  8978. var transaction = (arguments[0] instanceof Transaction)
  8979. ? Array.prototype.shift.apply(arguments)
  8980. : undefined;
  8981. var usePromise = false;
  8982. if (callback == undefined) {
  8983. usePromise = true;
  8984. }
  8985. if(!arguments.length) callback = undefined;
  8986. callback = (callback || noop).bind(this)
  8987. return disguise(this._invoke(transaction, 'getUri', callback), this)
  8988. };
  8989. /**
  8990. * @callback module:core/abstracts.UriEndpoint~getUriCallback
  8991. * @param {external:Error} error
  8992. * @param {external:String} result
  8993. */
  8994. //
  8995. // Public methods
  8996. //
  8997. /**
  8998. * Pauses the feed
  8999. *
  9000. * @alias module:core/abstracts.UriEndpoint.pause
  9001. *
  9002. * @param {module:core/abstracts.UriEndpoint~pauseCallback} [callback]
  9003. *
  9004. * @return {external:Promise}
  9005. */
  9006. UriEndpoint.prototype.pause = function(callback){
  9007. var transaction = (arguments[0] instanceof Transaction)
  9008. ? Array.prototype.shift.apply(arguments)
  9009. : undefined;
  9010. var usePromise = false;
  9011. if (callback == undefined) {
  9012. usePromise = true;
  9013. }
  9014. if(!arguments.length) callback = undefined;
  9015. callback = (callback || noop).bind(this)
  9016. return disguise(this._invoke(transaction, 'pause', callback), this)
  9017. };
  9018. /**
  9019. * @callback module:core/abstracts.UriEndpoint~pauseCallback
  9020. * @param {external:Error} error
  9021. */
  9022. /**
  9023. * Stops the feed
  9024. *
  9025. * @alias module:core/abstracts.UriEndpoint.stop
  9026. *
  9027. * @param {module:core/abstracts.UriEndpoint~stopCallback} [callback]
  9028. *
  9029. * @return {external:Promise}
  9030. */
  9031. UriEndpoint.prototype.stop = function(callback){
  9032. var transaction = (arguments[0] instanceof Transaction)
  9033. ? Array.prototype.shift.apply(arguments)
  9034. : undefined;
  9035. var usePromise = false;
  9036. if (callback == undefined) {
  9037. usePromise = true;
  9038. }
  9039. if(!arguments.length) callback = undefined;
  9040. callback = (callback || noop).bind(this)
  9041. return disguise(this._invoke(transaction, 'stop', callback), this)
  9042. };
  9043. /**
  9044. * @callback module:core/abstracts.UriEndpoint~stopCallback
  9045. * @param {external:Error} error
  9046. */
  9047. /**
  9048. * @alias module:core/abstracts.UriEndpoint.constructorParams
  9049. */
  9050. UriEndpoint.constructorParams = {
  9051. };
  9052. /**
  9053. * @alias module:core/abstracts.UriEndpoint.events
  9054. *
  9055. * @extends module:core/abstracts.Endpoint.events
  9056. */
  9057. UriEndpoint.events = Endpoint.events.concat(['UriEndpointStateChanged']);
  9058. /**
  9059. * Checker for {@link module:core/abstracts.UriEndpoint}
  9060. *
  9061. * @memberof module:core/abstracts
  9062. *
  9063. * @param {external:String} key
  9064. * @param {module:core/abstracts.UriEndpoint} value
  9065. */
  9066. function checkUriEndpoint(key, value)
  9067. {
  9068. if(!(value instanceof UriEndpoint))
  9069. throw ChecktypeError(key, UriEndpoint, value);
  9070. };
  9071. module.exports = UriEndpoint;
  9072. UriEndpoint.check = checkUriEndpoint;
  9073. },{"./Endpoint":31,"inherits":"inherits","kurento-client":"kurento-client"}],40:[function(require,module,exports){
  9074. /* Autogenerated with Kurento Idl */
  9075. /*
  9076. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  9077. *
  9078. * Licensed under the Apache License, Version 2.0 (the "License");
  9079. * you may not use this file except in compliance with the License.
  9080. * You may obtain a copy of the License at
  9081. *
  9082. * http://www.apache.org/licenses/LICENSE-2.0
  9083. *
  9084. * Unless required by applicable law or agreed to in writing, software
  9085. * distributed under the License is distributed on an "AS IS" BASIS,
  9086. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9087. * See the License for the specific language governing permissions and
  9088. * limitations under the License.
  9089. */
  9090. /**
  9091. * Media API for the Kurento Web SDK
  9092. *
  9093. * @module core/abstracts
  9094. *
  9095. * @copyright 2013-2015 Kurento (http://kurento.org/)
  9096. * @license ALv2
  9097. */
  9098. var BaseRtpEndpoint = require('./BaseRtpEndpoint');
  9099. var Endpoint = require('./Endpoint');
  9100. var Filter = require('./Filter');
  9101. var Hub = require('./Hub');
  9102. var MediaElement = require('./MediaElement');
  9103. var MediaObject = require('./MediaObject');
  9104. var SdpEndpoint = require('./SdpEndpoint');
  9105. var ServerManager = require('./ServerManager');
  9106. var SessionEndpoint = require('./SessionEndpoint');
  9107. var UriEndpoint = require('./UriEndpoint');
  9108. exports.BaseRtpEndpoint = BaseRtpEndpoint;
  9109. exports.Endpoint = Endpoint;
  9110. exports.Filter = Filter;
  9111. exports.Hub = Hub;
  9112. exports.MediaElement = MediaElement;
  9113. exports.MediaObject = MediaObject;
  9114. exports.SdpEndpoint = SdpEndpoint;
  9115. exports.ServerManager = ServerManager;
  9116. exports.SessionEndpoint = SessionEndpoint;
  9117. exports.UriEndpoint = UriEndpoint;
  9118. },{"./BaseRtpEndpoint":30,"./Endpoint":31,"./Filter":32,"./Hub":33,"./MediaElement":34,"./MediaObject":35,"./SdpEndpoint":36,"./ServerManager":37,"./SessionEndpoint":38,"./UriEndpoint":39}],41:[function(require,module,exports){
  9119. /* Autogenerated with Kurento Idl */
  9120. /*
  9121. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  9122. *
  9123. * Licensed under the Apache License, Version 2.0 (the "License");
  9124. * you may not use this file except in compliance with the License.
  9125. * You may obtain a copy of the License at
  9126. *
  9127. * http://www.apache.org/licenses/LICENSE-2.0
  9128. *
  9129. * Unless required by applicable law or agreed to in writing, software
  9130. * distributed under the License is distributed on an "AS IS" BASIS,
  9131. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9132. * See the License for the specific language governing permissions and
  9133. * limitations under the License.
  9134. */
  9135. var inherits = require('inherits');
  9136. var kurentoClient = require('kurento-client');
  9137. var checkType = kurentoClient.checkType;
  9138. var ChecktypeError = checkType.ChecktypeError;
  9139. var ComplexType = require('./ComplexType');
  9140. /**
  9141. * Format for audio media
  9142. *
  9143. * @constructor module:core/complexTypes.AudioCaps
  9144. *
  9145. * @property {module:core/complexTypes.AudioCodec} codec
  9146. * Audio codec
  9147. * @property {external:Integer} bitrate
  9148. * Bitrate
  9149. */
  9150. function AudioCaps(audioCapsDict){
  9151. if(!(this instanceof AudioCaps))
  9152. return new AudioCaps(audioCapsDict)
  9153. audioCapsDict = audioCapsDict || {}
  9154. // Check audioCapsDict has the required fields
  9155. //
  9156. // checkType('AudioCodec', 'audioCapsDict.codec', audioCapsDict.codec, {required: true});
  9157. //
  9158. // checkType('int', 'audioCapsDict.bitrate', audioCapsDict.bitrate, {required: true});
  9159. //
  9160. // Init parent class
  9161. AudioCaps.super_.call(this, audioCapsDict)
  9162. // Set object properties
  9163. Object.defineProperties(this, {
  9164. codec: {
  9165. writable: true,
  9166. enumerable: true,
  9167. value: audioCapsDict.codec
  9168. },
  9169. bitrate: {
  9170. writable: true,
  9171. enumerable: true,
  9172. value: audioCapsDict.bitrate
  9173. }
  9174. })
  9175. }
  9176. inherits(AudioCaps, ComplexType)
  9177. // Private identifiers to allow re-construction of the complexType on the server
  9178. // They need to be enumerable so JSON.stringify() can access to them
  9179. Object.defineProperties(AudioCaps.prototype, {
  9180. __module__: {
  9181. enumerable: true,
  9182. value: "kurento"
  9183. },
  9184. __type__: {
  9185. enumerable: true,
  9186. value: "AudioCaps"
  9187. }
  9188. })
  9189. /**
  9190. * Checker for {@link module:core/complexTypes.AudioCaps}
  9191. *
  9192. * @memberof module:core/complexTypes
  9193. *
  9194. * @param {external:String} key
  9195. * @param {module:core/complexTypes.AudioCaps} value
  9196. */
  9197. function checkAudioCaps(key, value)
  9198. {
  9199. if(!(value instanceof AudioCaps))
  9200. throw ChecktypeError(key, AudioCaps, value);
  9201. };
  9202. module.exports = AudioCaps;
  9203. AudioCaps.check = checkAudioCaps;
  9204. },{"./ComplexType":44,"inherits":"inherits","kurento-client":"kurento-client"}],42:[function(require,module,exports){
  9205. /* Autogenerated with Kurento Idl */
  9206. /*
  9207. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  9208. *
  9209. * Licensed under the Apache License, Version 2.0 (the "License");
  9210. * you may not use this file except in compliance with the License.
  9211. * You may obtain a copy of the License at
  9212. *
  9213. * http://www.apache.org/licenses/LICENSE-2.0
  9214. *
  9215. * Unless required by applicable law or agreed to in writing, software
  9216. * distributed under the License is distributed on an "AS IS" BASIS,
  9217. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9218. * See the License for the specific language governing permissions and
  9219. * limitations under the License.
  9220. */
  9221. var kurentoClient = require('kurento-client');
  9222. /**
  9223. * Codec used for transmission of audio.
  9224. *
  9225. * @typedef core/complexTypes.AudioCodec
  9226. *
  9227. * @type {(OPUS|PCMU|RAW)}
  9228. */
  9229. /**
  9230. * Checker for {@link module:core/complexTypes.AudioCodec}
  9231. *
  9232. * @memberof module:core/complexTypes
  9233. *
  9234. * @param {external:String} key
  9235. * @param {module:core/complexTypes.AudioCodec} value
  9236. */
  9237. function checkAudioCodec(key, value)
  9238. {
  9239. if(typeof value != 'string')
  9240. throw SyntaxError(key+' param should be a String, not '+typeof value);
  9241. if(!value.match('OPUS|PCMU|RAW'))
  9242. throw SyntaxError(key+' param is not one of [OPUS|PCMU|RAW] ('+value+')');
  9243. };
  9244. module.exports = checkAudioCodec;
  9245. },{"kurento-client":"kurento-client"}],43:[function(require,module,exports){
  9246. /* Autogenerated with Kurento Idl */
  9247. /*
  9248. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  9249. *
  9250. * Licensed under the Apache License, Version 2.0 (the "License");
  9251. * you may not use this file except in compliance with the License.
  9252. * You may obtain a copy of the License at
  9253. *
  9254. * http://www.apache.org/licenses/LICENSE-2.0
  9255. *
  9256. * Unless required by applicable law or agreed to in writing, software
  9257. * distributed under the License is distributed on an "AS IS" BASIS,
  9258. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9259. * See the License for the specific language governing permissions and
  9260. * limitations under the License.
  9261. */
  9262. var inherits = require('inherits');
  9263. var kurentoClient = require('kurento-client');
  9264. var checkType = kurentoClient.checkType;
  9265. var ChecktypeError = checkType.ChecktypeError;
  9266. var ComplexType = require('./ComplexType');
  9267. /**
  9268. * Defines specific configuration for codecs
  9269. *
  9270. * @constructor module:core/complexTypes.CodecConfiguration
  9271. *
  9272. * @property {external:String} name
  9273. * Name of the codec. Must follow this format: <encoding name>/<clock
  9274. * rate>[/<encoding parameters>]
  9275. * @property {external:String} properties
  9276. * String used for tuning codec properties
  9277. */
  9278. function CodecConfiguration(codecConfigurationDict){
  9279. if(!(this instanceof CodecConfiguration))
  9280. return new CodecConfiguration(codecConfigurationDict)
  9281. codecConfigurationDict = codecConfigurationDict || {}
  9282. // Check codecConfigurationDict has the required fields
  9283. //
  9284. // checkType('String', 'codecConfigurationDict.name', codecConfigurationDict.name);
  9285. //
  9286. // checkType('String', 'codecConfigurationDict.properties', codecConfigurationDict.properties);
  9287. //
  9288. // Init parent class
  9289. CodecConfiguration.super_.call(this, codecConfigurationDict)
  9290. // Set object properties
  9291. Object.defineProperties(this, {
  9292. name: {
  9293. writable: true,
  9294. enumerable: true,
  9295. value: codecConfigurationDict.name
  9296. },
  9297. properties: {
  9298. writable: true,
  9299. enumerable: true,
  9300. value: codecConfigurationDict.properties
  9301. }
  9302. })
  9303. }
  9304. inherits(CodecConfiguration, ComplexType)
  9305. // Private identifiers to allow re-construction of the complexType on the server
  9306. // They need to be enumerable so JSON.stringify() can access to them
  9307. Object.defineProperties(CodecConfiguration.prototype, {
  9308. __module__: {
  9309. enumerable: true,
  9310. value: "kurento"
  9311. },
  9312. __type__: {
  9313. enumerable: true,
  9314. value: "CodecConfiguration"
  9315. }
  9316. })
  9317. /**
  9318. * Checker for {@link module:core/complexTypes.CodecConfiguration}
  9319. *
  9320. * @memberof module:core/complexTypes
  9321. *
  9322. * @param {external:String} key
  9323. * @param {module:core/complexTypes.CodecConfiguration} value
  9324. */
  9325. function checkCodecConfiguration(key, value)
  9326. {
  9327. if(!(value instanceof CodecConfiguration))
  9328. throw ChecktypeError(key, CodecConfiguration, value);
  9329. };
  9330. module.exports = CodecConfiguration;
  9331. CodecConfiguration.check = checkCodecConfiguration;
  9332. },{"./ComplexType":44,"inherits":"inherits","kurento-client":"kurento-client"}],44:[function(require,module,exports){
  9333. /* Autogenerated with Kurento Idl */
  9334. /*
  9335. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  9336. *
  9337. * Licensed under the Apache License, Version 2.0 (the "License");
  9338. * you may not use this file except in compliance with the License.
  9339. * You may obtain a copy of the License at
  9340. *
  9341. * http://www.apache.org/licenses/LICENSE-2.0
  9342. *
  9343. * Unless required by applicable law or agreed to in writing, software
  9344. * distributed under the License is distributed on an "AS IS" BASIS,
  9345. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9346. * See the License for the specific language governing permissions and
  9347. * limitations under the License.
  9348. */
  9349. var ChecktypeError = require('kurento-client').checkType.ChecktypeError;
  9350. /**
  9351. * @constructor module:core/complexTypes.ComplexType
  9352. *
  9353. * @abstract
  9354. */
  9355. function ComplexType(){}
  9356. // Based on http://stackoverflow.com/a/14078260/586382
  9357. ComplexType.prototype.toJSON = function()
  9358. {
  9359. var result = {};
  9360. for(var key in this)
  9361. {
  9362. var value = this[key]
  9363. if(typeof value !== 'function')
  9364. result[key] = value;
  9365. }
  9366. return result;
  9367. }
  9368. /**
  9369. * Checker for {@link core/complexTypes.ComplexType}
  9370. *
  9371. * @memberof module:core/complexTypes
  9372. *
  9373. * @param {external:String} key
  9374. * @param {module:core/complexTypes.ComplexType} value
  9375. */
  9376. function checkComplexType(key, value)
  9377. {
  9378. if(!(value instanceof ComplexType))
  9379. throw ChecktypeError(key, ComplexType, value);
  9380. };
  9381. module.exports = ComplexType;
  9382. ComplexType.check = checkComplexType;
  9383. },{"kurento-client":"kurento-client"}],45:[function(require,module,exports){
  9384. /* Autogenerated with Kurento Idl */
  9385. /*
  9386. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  9387. *
  9388. * Licensed under the Apache License, Version 2.0 (the "License");
  9389. * you may not use this file except in compliance with the License.
  9390. * You may obtain a copy of the License at
  9391. *
  9392. * http://www.apache.org/licenses/LICENSE-2.0
  9393. *
  9394. * Unless required by applicable law or agreed to in writing, software
  9395. * distributed under the License is distributed on an "AS IS" BASIS,
  9396. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9397. * See the License for the specific language governing permissions and
  9398. * limitations under the License.
  9399. */
  9400. var kurentoClient = require('kurento-client');
  9401. /**
  9402. * State of the connection.
  9403. *
  9404. * @typedef core/complexTypes.ConnectionState
  9405. *
  9406. * @type {(DISCONNECTED|CONNECTED)}
  9407. */
  9408. /**
  9409. * Checker for {@link module:core/complexTypes.ConnectionState}
  9410. *
  9411. * @memberof module:core/complexTypes
  9412. *
  9413. * @param {external:String} key
  9414. * @param {module:core/complexTypes.ConnectionState} value
  9415. */
  9416. function checkConnectionState(key, value)
  9417. {
  9418. if(typeof value != 'string')
  9419. throw SyntaxError(key+' param should be a String, not '+typeof value);
  9420. if(!value.match('DISCONNECTED|CONNECTED'))
  9421. throw SyntaxError(key+' param is not one of [DISCONNECTED|CONNECTED] ('+value+')');
  9422. };
  9423. module.exports = checkConnectionState;
  9424. },{"kurento-client":"kurento-client"}],46:[function(require,module,exports){
  9425. /* Autogenerated with Kurento Idl */
  9426. /*
  9427. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  9428. *
  9429. * Licensed under the Apache License, Version 2.0 (the "License");
  9430. * you may not use this file except in compliance with the License.
  9431. * You may obtain a copy of the License at
  9432. *
  9433. * http://www.apache.org/licenses/LICENSE-2.0
  9434. *
  9435. * Unless required by applicable law or agreed to in writing, software
  9436. * distributed under the License is distributed on an "AS IS" BASIS,
  9437. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9438. * See the License for the specific language governing permissions and
  9439. * limitations under the License.
  9440. */
  9441. var inherits = require('inherits');
  9442. var kurentoClient = require('kurento-client');
  9443. var checkType = kurentoClient.checkType;
  9444. var ChecktypeError = checkType.ChecktypeError;
  9445. var ComplexType = require('./ComplexType');
  9446. /**
  9447. * @constructor module:core/complexTypes.ElementConnectionData
  9448. *
  9449. * @property {module:core/abstracts.MediaElement} source
  9450. * The source element in the connection
  9451. * @property {module:core/abstracts.MediaElement} sink
  9452. * The sink element in the connection
  9453. * @property {module:core/complexTypes.MediaType} type
  9454. * MediaType of the connection
  9455. * @property {external:String} sourceDescription
  9456. * Description of source media. Could be emty.
  9457. * @property {external:String} sinkDescription
  9458. * Description of sink media. Could be emty.
  9459. */
  9460. function ElementConnectionData(elementConnectionDataDict){
  9461. if(!(this instanceof ElementConnectionData))
  9462. return new ElementConnectionData(elementConnectionDataDict)
  9463. elementConnectionDataDict = elementConnectionDataDict || {}
  9464. // Check elementConnectionDataDict has the required fields
  9465. //
  9466. // checkType('MediaElement', 'elementConnectionDataDict.source', elementConnectionDataDict.source, {required: true});
  9467. //
  9468. // checkType('MediaElement', 'elementConnectionDataDict.sink', elementConnectionDataDict.sink, {required: true});
  9469. //
  9470. // checkType('MediaType', 'elementConnectionDataDict.type', elementConnectionDataDict.type, {required: true});
  9471. //
  9472. // checkType('String', 'elementConnectionDataDict.sourceDescription', elementConnectionDataDict.sourceDescription, {required: true});
  9473. //
  9474. // checkType('String', 'elementConnectionDataDict.sinkDescription', elementConnectionDataDict.sinkDescription, {required: true});
  9475. //
  9476. // Init parent class
  9477. ElementConnectionData.super_.call(this, elementConnectionDataDict)
  9478. // Set object properties
  9479. Object.defineProperties(this, {
  9480. source: {
  9481. writable: true,
  9482. enumerable: true,
  9483. value: elementConnectionDataDict.source
  9484. },
  9485. sink: {
  9486. writable: true,
  9487. enumerable: true,
  9488. value: elementConnectionDataDict.sink
  9489. },
  9490. type: {
  9491. writable: true,
  9492. enumerable: true,
  9493. value: elementConnectionDataDict.type
  9494. },
  9495. sourceDescription: {
  9496. writable: true,
  9497. enumerable: true,
  9498. value: elementConnectionDataDict.sourceDescription
  9499. },
  9500. sinkDescription: {
  9501. writable: true,
  9502. enumerable: true,
  9503. value: elementConnectionDataDict.sinkDescription
  9504. }
  9505. })
  9506. }
  9507. inherits(ElementConnectionData, ComplexType)
  9508. // Private identifiers to allow re-construction of the complexType on the server
  9509. // They need to be enumerable so JSON.stringify() can access to them
  9510. Object.defineProperties(ElementConnectionData.prototype, {
  9511. __module__: {
  9512. enumerable: true,
  9513. value: "kurento"
  9514. },
  9515. __type__: {
  9516. enumerable: true,
  9517. value: "ElementConnectionData"
  9518. }
  9519. })
  9520. /**
  9521. * Checker for {@link module:core/complexTypes.ElementConnectionData}
  9522. *
  9523. * @memberof module:core/complexTypes
  9524. *
  9525. * @param {external:String} key
  9526. * @param {module:core/complexTypes.ElementConnectionData} value
  9527. */
  9528. function checkElementConnectionData(key, value)
  9529. {
  9530. if(!(value instanceof ElementConnectionData))
  9531. throw ChecktypeError(key, ElementConnectionData, value);
  9532. };
  9533. module.exports = ElementConnectionData;
  9534. ElementConnectionData.check = checkElementConnectionData;
  9535. },{"./ComplexType":44,"inherits":"inherits","kurento-client":"kurento-client"}],47:[function(require,module,exports){
  9536. /* Autogenerated with Kurento Idl */
  9537. /*
  9538. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  9539. *
  9540. * Licensed under the Apache License, Version 2.0 (the "License");
  9541. * you may not use this file except in compliance with the License.
  9542. * You may obtain a copy of the License at
  9543. *
  9544. * http://www.apache.org/licenses/LICENSE-2.0
  9545. *
  9546. * Unless required by applicable law or agreed to in writing, software
  9547. * distributed under the License is distributed on an "AS IS" BASIS,
  9548. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9549. * See the License for the specific language governing permissions and
  9550. * limitations under the License.
  9551. */
  9552. var inherits = require('inherits');
  9553. var kurentoClient = require('kurento-client');
  9554. var checkType = kurentoClient.checkType;
  9555. var ChecktypeError = checkType.ChecktypeError;
  9556. var Stats = require('./Stats');
  9557. /**
  9558. * A dictionary that represents the stats gathered in the media element.
  9559. *
  9560. * @constructor module:core/complexTypes.ElementStats
  9561. *
  9562. * @property {external:double} inputAudioLatency
  9563. * @deprecated
  9564. * Audio average measured on the sink pad in nano seconds
  9565. * @property {external:double} inputVideoLatency
  9566. * @deprecated
  9567. * Video average measured on the sink pad in nano seconds
  9568. * @property {module:core/complexTypes.MediaLatencyStat} inputLatency
  9569. * The average time that buffers take to get on the input pads of this element
  9570. * in nano seconds
  9571. * @extends module:core.Stats
  9572. */
  9573. function ElementStats(elementStatsDict){
  9574. if(!(this instanceof ElementStats))
  9575. return new ElementStats(elementStatsDict)
  9576. elementStatsDict = elementStatsDict || {}
  9577. // Check elementStatsDict has the required fields
  9578. //
  9579. // checkType('double', 'elementStatsDict.inputAudioLatency', elementStatsDict.inputAudioLatency, {required: true});
  9580. //
  9581. // checkType('double', 'elementStatsDict.inputVideoLatency', elementStatsDict.inputVideoLatency, {required: true});
  9582. //
  9583. // checkType('MediaLatencyStat', 'elementStatsDict.inputLatency', elementStatsDict.inputLatency, {isArray: true, required: true});
  9584. //
  9585. // Init parent class
  9586. ElementStats.super_.call(this, elementStatsDict)
  9587. // Set object properties
  9588. Object.defineProperties(this, {
  9589. inputAudioLatency: {
  9590. writable: true,
  9591. enumerable: true,
  9592. value: elementStatsDict.inputAudioLatency
  9593. },
  9594. inputVideoLatency: {
  9595. writable: true,
  9596. enumerable: true,
  9597. value: elementStatsDict.inputVideoLatency
  9598. },
  9599. inputLatency: {
  9600. writable: true,
  9601. enumerable: true,
  9602. value: elementStatsDict.inputLatency
  9603. }
  9604. })
  9605. }
  9606. inherits(ElementStats, Stats)
  9607. // Private identifiers to allow re-construction of the complexType on the server
  9608. // They need to be enumerable so JSON.stringify() can access to them
  9609. Object.defineProperties(ElementStats.prototype, {
  9610. __module__: {
  9611. enumerable: true,
  9612. value: "kurento"
  9613. },
  9614. __type__: {
  9615. enumerable: true,
  9616. value: "ElementStats"
  9617. }
  9618. })
  9619. /**
  9620. * Checker for {@link module:core/complexTypes.ElementStats}
  9621. *
  9622. * @memberof module:core/complexTypes
  9623. *
  9624. * @param {external:String} key
  9625. * @param {module:core/complexTypes.ElementStats} value
  9626. */
  9627. function checkElementStats(key, value)
  9628. {
  9629. if(!(value instanceof ElementStats))
  9630. throw ChecktypeError(key, ElementStats, value);
  9631. };
  9632. module.exports = ElementStats;
  9633. ElementStats.check = checkElementStats;
  9634. },{"./Stats":77,"inherits":"inherits","kurento-client":"kurento-client"}],48:[function(require,module,exports){
  9635. /* Autogenerated with Kurento Idl */
  9636. /*
  9637. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  9638. *
  9639. * Licensed under the Apache License, Version 2.0 (the "License");
  9640. * you may not use this file except in compliance with the License.
  9641. * You may obtain a copy of the License at
  9642. *
  9643. * http://www.apache.org/licenses/LICENSE-2.0
  9644. *
  9645. * Unless required by applicable law or agreed to in writing, software
  9646. * distributed under the License is distributed on an "AS IS" BASIS,
  9647. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9648. * See the License for the specific language governing permissions and
  9649. * limitations under the License.
  9650. */
  9651. var inherits = require('inherits');
  9652. var kurentoClient = require('kurento-client');
  9653. var checkType = kurentoClient.checkType;
  9654. var ChecktypeError = checkType.ChecktypeError;
  9655. var ElementStats = require('./ElementStats');
  9656. /**
  9657. * A dictionary that represents the stats gathered in the endpoint element.
  9658. *
  9659. * @constructor module:core/complexTypes.EndpointStats
  9660. *
  9661. * @property {external:double} audioE2ELatency
  9662. * @deprecated
  9663. * End-to-end audio latency measured in nano seconds
  9664. * @property {external:double} videoE2ELatency
  9665. * @deprecated
  9666. * End-to-end video latency measured in nano seconds
  9667. * @property {module:core/complexTypes.MediaLatencyStat} E2ELatency
  9668. * The average end to end latency for each media stream measured in nano
  9669. * seconds
  9670. * @extends module:core.ElementStats
  9671. */
  9672. function EndpointStats(endpointStatsDict){
  9673. if(!(this instanceof EndpointStats))
  9674. return new EndpointStats(endpointStatsDict)
  9675. endpointStatsDict = endpointStatsDict || {}
  9676. // Check endpointStatsDict has the required fields
  9677. //
  9678. // checkType('double', 'endpointStatsDict.audioE2ELatency', endpointStatsDict.audioE2ELatency, {required: true});
  9679. //
  9680. // checkType('double', 'endpointStatsDict.videoE2ELatency', endpointStatsDict.videoE2ELatency, {required: true});
  9681. //
  9682. // checkType('MediaLatencyStat', 'endpointStatsDict.E2ELatency', endpointStatsDict.E2ELatency, {isArray: true, required: true});
  9683. //
  9684. // Init parent class
  9685. EndpointStats.super_.call(this, endpointStatsDict)
  9686. // Set object properties
  9687. Object.defineProperties(this, {
  9688. audioE2ELatency: {
  9689. writable: true,
  9690. enumerable: true,
  9691. value: endpointStatsDict.audioE2ELatency
  9692. },
  9693. videoE2ELatency: {
  9694. writable: true,
  9695. enumerable: true,
  9696. value: endpointStatsDict.videoE2ELatency
  9697. },
  9698. E2ELatency: {
  9699. writable: true,
  9700. enumerable: true,
  9701. value: endpointStatsDict.E2ELatency
  9702. }
  9703. })
  9704. }
  9705. inherits(EndpointStats, ElementStats)
  9706. // Private identifiers to allow re-construction of the complexType on the server
  9707. // They need to be enumerable so JSON.stringify() can access to them
  9708. Object.defineProperties(EndpointStats.prototype, {
  9709. __module__: {
  9710. enumerable: true,
  9711. value: "kurento"
  9712. },
  9713. __type__: {
  9714. enumerable: true,
  9715. value: "EndpointStats"
  9716. }
  9717. })
  9718. /**
  9719. * Checker for {@link module:core/complexTypes.EndpointStats}
  9720. *
  9721. * @memberof module:core/complexTypes
  9722. *
  9723. * @param {external:String} key
  9724. * @param {module:core/complexTypes.EndpointStats} value
  9725. */
  9726. function checkEndpointStats(key, value)
  9727. {
  9728. if(!(value instanceof EndpointStats))
  9729. throw ChecktypeError(key, EndpointStats, value);
  9730. };
  9731. module.exports = EndpointStats;
  9732. EndpointStats.check = checkEndpointStats;
  9733. },{"./ElementStats":47,"inherits":"inherits","kurento-client":"kurento-client"}],49:[function(require,module,exports){
  9734. /* Autogenerated with Kurento Idl */
  9735. /*
  9736. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  9737. *
  9738. * Licensed under the Apache License, Version 2.0 (the "License");
  9739. * you may not use this file except in compliance with the License.
  9740. * You may obtain a copy of the License at
  9741. *
  9742. * http://www.apache.org/licenses/LICENSE-2.0
  9743. *
  9744. * Unless required by applicable law or agreed to in writing, software
  9745. * distributed under the License is distributed on an "AS IS" BASIS,
  9746. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9747. * See the License for the specific language governing permissions and
  9748. * limitations under the License.
  9749. */
  9750. var kurentoClient = require('kurento-client');
  9751. /**
  9752. * Type of filter to be created.
  9753. * Can take the values AUDIO, VIDEO or AUTODETECT.
  9754. *
  9755. * @typedef core/complexTypes.FilterType
  9756. *
  9757. * @type {(AUDIO|AUTODETECT|VIDEO)}
  9758. */
  9759. /**
  9760. * Checker for {@link module:core/complexTypes.FilterType}
  9761. *
  9762. * @memberof module:core/complexTypes
  9763. *
  9764. * @param {external:String} key
  9765. * @param {module:core/complexTypes.FilterType} value
  9766. */
  9767. function checkFilterType(key, value)
  9768. {
  9769. if(typeof value != 'string')
  9770. throw SyntaxError(key+' param should be a String, not '+typeof value);
  9771. if(!value.match('AUDIO|AUTODETECT|VIDEO'))
  9772. throw SyntaxError(key+' param is not one of [AUDIO|AUTODETECT|VIDEO] ('+value+')');
  9773. };
  9774. module.exports = checkFilterType;
  9775. },{"kurento-client":"kurento-client"}],50:[function(require,module,exports){
  9776. /* Autogenerated with Kurento Idl */
  9777. /*
  9778. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  9779. *
  9780. * Licensed under the Apache License, Version 2.0 (the "License");
  9781. * you may not use this file except in compliance with the License.
  9782. * You may obtain a copy of the License at
  9783. *
  9784. * http://www.apache.org/licenses/LICENSE-2.0
  9785. *
  9786. * Unless required by applicable law or agreed to in writing, software
  9787. * distributed under the License is distributed on an "AS IS" BASIS,
  9788. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9789. * See the License for the specific language governing permissions and
  9790. * limitations under the License.
  9791. */
  9792. var inherits = require('inherits');
  9793. var kurentoClient = require('kurento-client');
  9794. var checkType = kurentoClient.checkType;
  9795. var ChecktypeError = checkType.ChecktypeError;
  9796. var ComplexType = require('./ComplexType');
  9797. /**
  9798. * Type that represents a fraction of an integer numerator over an integer
  9799. * denominator
  9800. *
  9801. * @constructor module:core/complexTypes.Fraction
  9802. *
  9803. * @property {external:Integer} numerator
  9804. * the numerator of the fraction
  9805. * @property {external:Integer} denominator
  9806. * the denominator of the fraction
  9807. */
  9808. function Fraction(fractionDict){
  9809. if(!(this instanceof Fraction))
  9810. return new Fraction(fractionDict)
  9811. fractionDict = fractionDict || {}
  9812. // Check fractionDict has the required fields
  9813. //
  9814. // checkType('int', 'fractionDict.numerator', fractionDict.numerator, {required: true});
  9815. //
  9816. // checkType('int', 'fractionDict.denominator', fractionDict.denominator, {required: true});
  9817. //
  9818. // Init parent class
  9819. Fraction.super_.call(this, fractionDict)
  9820. // Set object properties
  9821. Object.defineProperties(this, {
  9822. numerator: {
  9823. writable: true,
  9824. enumerable: true,
  9825. value: fractionDict.numerator
  9826. },
  9827. denominator: {
  9828. writable: true,
  9829. enumerable: true,
  9830. value: fractionDict.denominator
  9831. }
  9832. })
  9833. }
  9834. inherits(Fraction, ComplexType)
  9835. // Private identifiers to allow re-construction of the complexType on the server
  9836. // They need to be enumerable so JSON.stringify() can access to them
  9837. Object.defineProperties(Fraction.prototype, {
  9838. __module__: {
  9839. enumerable: true,
  9840. value: "kurento"
  9841. },
  9842. __type__: {
  9843. enumerable: true,
  9844. value: "Fraction"
  9845. }
  9846. })
  9847. /**
  9848. * Checker for {@link module:core/complexTypes.Fraction}
  9849. *
  9850. * @memberof module:core/complexTypes
  9851. *
  9852. * @param {external:String} key
  9853. * @param {module:core/complexTypes.Fraction} value
  9854. */
  9855. function checkFraction(key, value)
  9856. {
  9857. if(!(value instanceof Fraction))
  9858. throw ChecktypeError(key, Fraction, value);
  9859. };
  9860. module.exports = Fraction;
  9861. Fraction.check = checkFraction;
  9862. },{"./ComplexType":44,"inherits":"inherits","kurento-client":"kurento-client"}],51:[function(require,module,exports){
  9863. /* Autogenerated with Kurento Idl */
  9864. /*
  9865. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  9866. *
  9867. * Licensed under the Apache License, Version 2.0 (the "License");
  9868. * you may not use this file except in compliance with the License.
  9869. * You may obtain a copy of the License at
  9870. *
  9871. * http://www.apache.org/licenses/LICENSE-2.0
  9872. *
  9873. * Unless required by applicable law or agreed to in writing, software
  9874. * distributed under the License is distributed on an "AS IS" BASIS,
  9875. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9876. * See the License for the specific language governing permissions and
  9877. * limitations under the License.
  9878. */
  9879. var kurentoClient = require('kurento-client');
  9880. /**
  9881. * Details of gstreamer dot graphs
  9882. *
  9883. * @typedef core/complexTypes.GstreamerDotDetails
  9884. *
  9885. * @type {(SHOW_MEDIA_TYPE|SHOW_CAPS_DETAILS|SHOW_NON_DEFAULT_PARAMS|SHOW_STATES|SHOW_FULL_PARAMS|SHOW_ALL|SHOW_VERBOSE)}
  9886. */
  9887. /**
  9888. * Checker for {@link module:core/complexTypes.GstreamerDotDetails}
  9889. *
  9890. * @memberof module:core/complexTypes
  9891. *
  9892. * @param {external:String} key
  9893. * @param {module:core/complexTypes.GstreamerDotDetails} value
  9894. */
  9895. function checkGstreamerDotDetails(key, value)
  9896. {
  9897. if(typeof value != 'string')
  9898. throw SyntaxError(key+' param should be a String, not '+typeof value);
  9899. if(!value.match('SHOW_MEDIA_TYPE|SHOW_CAPS_DETAILS|SHOW_NON_DEFAULT_PARAMS|SHOW_STATES|SHOW_FULL_PARAMS|SHOW_ALL|SHOW_VERBOSE'))
  9900. throw SyntaxError(key+' param is not one of [SHOW_MEDIA_TYPE|SHOW_CAPS_DETAILS|SHOW_NON_DEFAULT_PARAMS|SHOW_STATES|SHOW_FULL_PARAMS|SHOW_ALL|SHOW_VERBOSE] ('+value+')');
  9901. };
  9902. module.exports = checkGstreamerDotDetails;
  9903. },{"kurento-client":"kurento-client"}],52:[function(require,module,exports){
  9904. /* Autogenerated with Kurento Idl */
  9905. /*
  9906. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  9907. *
  9908. * Licensed under the Apache License, Version 2.0 (the "License");
  9909. * you may not use this file except in compliance with the License.
  9910. * You may obtain a copy of the License at
  9911. *
  9912. * http://www.apache.org/licenses/LICENSE-2.0
  9913. *
  9914. * Unless required by applicable law or agreed to in writing, software
  9915. * distributed under the License is distributed on an "AS IS" BASIS,
  9916. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9917. * See the License for the specific language governing permissions and
  9918. * limitations under the License.
  9919. */
  9920. var kurentoClient = require('kurento-client');
  9921. /**
  9922. * Flowing state of the media.
  9923. *
  9924. * @typedef core/complexTypes.MediaFlowState
  9925. *
  9926. * @type {(FLOWING|NOT_FLOWING)}
  9927. */
  9928. /**
  9929. * Checker for {@link module:core/complexTypes.MediaFlowState}
  9930. *
  9931. * @memberof module:core/complexTypes
  9932. *
  9933. * @param {external:String} key
  9934. * @param {module:core/complexTypes.MediaFlowState} value
  9935. */
  9936. function checkMediaFlowState(key, value)
  9937. {
  9938. if(typeof value != 'string')
  9939. throw SyntaxError(key+' param should be a String, not '+typeof value);
  9940. if(!value.match('FLOWING|NOT_FLOWING'))
  9941. throw SyntaxError(key+' param is not one of [FLOWING|NOT_FLOWING] ('+value+')');
  9942. };
  9943. module.exports = checkMediaFlowState;
  9944. },{"kurento-client":"kurento-client"}],53:[function(require,module,exports){
  9945. /* Autogenerated with Kurento Idl */
  9946. /*
  9947. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  9948. *
  9949. * Licensed under the Apache License, Version 2.0 (the "License");
  9950. * you may not use this file except in compliance with the License.
  9951. * You may obtain a copy of the License at
  9952. *
  9953. * http://www.apache.org/licenses/LICENSE-2.0
  9954. *
  9955. * Unless required by applicable law or agreed to in writing, software
  9956. * distributed under the License is distributed on an "AS IS" BASIS,
  9957. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9958. * See the License for the specific language governing permissions and
  9959. * limitations under the License.
  9960. */
  9961. var inherits = require('inherits');
  9962. var kurentoClient = require('kurento-client');
  9963. var checkType = kurentoClient.checkType;
  9964. var ChecktypeError = checkType.ChecktypeError;
  9965. var ComplexType = require('./ComplexType');
  9966. /**
  9967. * A dictionary that represents the stats gathered.
  9968. *
  9969. * @constructor module:core/complexTypes.MediaLatencyStat
  9970. *
  9971. * @property {external:String} name
  9972. * The identifier of the media stream
  9973. * @property {module:core/complexTypes.MediaType} type
  9974. * Type of media stream
  9975. * @property {external:double} avg
  9976. * The average time that buffers take to get on the input pad of this element
  9977. */
  9978. function MediaLatencyStat(mediaLatencyStatDict){
  9979. if(!(this instanceof MediaLatencyStat))
  9980. return new MediaLatencyStat(mediaLatencyStatDict)
  9981. mediaLatencyStatDict = mediaLatencyStatDict || {}
  9982. // Check mediaLatencyStatDict has the required fields
  9983. //
  9984. // checkType('String', 'mediaLatencyStatDict.name', mediaLatencyStatDict.name, {required: true});
  9985. //
  9986. // checkType('MediaType', 'mediaLatencyStatDict.type', mediaLatencyStatDict.type, {required: true});
  9987. //
  9988. // checkType('double', 'mediaLatencyStatDict.avg', mediaLatencyStatDict.avg, {required: true});
  9989. //
  9990. // Init parent class
  9991. MediaLatencyStat.super_.call(this, mediaLatencyStatDict)
  9992. // Set object properties
  9993. Object.defineProperties(this, {
  9994. name: {
  9995. writable: true,
  9996. enumerable: true,
  9997. value: mediaLatencyStatDict.name
  9998. },
  9999. type: {
  10000. writable: true,
  10001. enumerable: true,
  10002. value: mediaLatencyStatDict.type
  10003. },
  10004. avg: {
  10005. writable: true,
  10006. enumerable: true,
  10007. value: mediaLatencyStatDict.avg
  10008. }
  10009. })
  10010. }
  10011. inherits(MediaLatencyStat, ComplexType)
  10012. // Private identifiers to allow re-construction of the complexType on the server
  10013. // They need to be enumerable so JSON.stringify() can access to them
  10014. Object.defineProperties(MediaLatencyStat.prototype, {
  10015. __module__: {
  10016. enumerable: true,
  10017. value: "kurento"
  10018. },
  10019. __type__: {
  10020. enumerable: true,
  10021. value: "MediaLatencyStat"
  10022. }
  10023. })
  10024. /**
  10025. * Checker for {@link module:core/complexTypes.MediaLatencyStat}
  10026. *
  10027. * @memberof module:core/complexTypes
  10028. *
  10029. * @param {external:String} key
  10030. * @param {module:core/complexTypes.MediaLatencyStat} value
  10031. */
  10032. function checkMediaLatencyStat(key, value)
  10033. {
  10034. if(!(value instanceof MediaLatencyStat))
  10035. throw ChecktypeError(key, MediaLatencyStat, value);
  10036. };
  10037. module.exports = MediaLatencyStat;
  10038. MediaLatencyStat.check = checkMediaLatencyStat;
  10039. },{"./ComplexType":44,"inherits":"inherits","kurento-client":"kurento-client"}],54:[function(require,module,exports){
  10040. /* Autogenerated with Kurento Idl */
  10041. /*
  10042. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  10043. *
  10044. * Licensed under the Apache License, Version 2.0 (the "License");
  10045. * you may not use this file except in compliance with the License.
  10046. * You may obtain a copy of the License at
  10047. *
  10048. * http://www.apache.org/licenses/LICENSE-2.0
  10049. *
  10050. * Unless required by applicable law or agreed to in writing, software
  10051. * distributed under the License is distributed on an "AS IS" BASIS,
  10052. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10053. * See the License for the specific language governing permissions and
  10054. * limitations under the License.
  10055. */
  10056. var kurentoClient = require('kurento-client');
  10057. /**
  10058. * State of the media.
  10059. *
  10060. * @typedef core/complexTypes.MediaState
  10061. *
  10062. * @type {(DISCONNECTED|CONNECTED)}
  10063. */
  10064. /**
  10065. * Checker for {@link module:core/complexTypes.MediaState}
  10066. *
  10067. * @memberof module:core/complexTypes
  10068. *
  10069. * @param {external:String} key
  10070. * @param {module:core/complexTypes.MediaState} value
  10071. */
  10072. function checkMediaState(key, value)
  10073. {
  10074. if(typeof value != 'string')
  10075. throw SyntaxError(key+' param should be a String, not '+typeof value);
  10076. if(!value.match('DISCONNECTED|CONNECTED'))
  10077. throw SyntaxError(key+' param is not one of [DISCONNECTED|CONNECTED] ('+value+')');
  10078. };
  10079. module.exports = checkMediaState;
  10080. },{"kurento-client":"kurento-client"}],55:[function(require,module,exports){
  10081. /* Autogenerated with Kurento Idl */
  10082. /*
  10083. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  10084. *
  10085. * Licensed under the Apache License, Version 2.0 (the "License");
  10086. * you may not use this file except in compliance with the License.
  10087. * You may obtain a copy of the License at
  10088. *
  10089. * http://www.apache.org/licenses/LICENSE-2.0
  10090. *
  10091. * Unless required by applicable law or agreed to in writing, software
  10092. * distributed under the License is distributed on an "AS IS" BASIS,
  10093. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10094. * See the License for the specific language governing permissions and
  10095. * limitations under the License.
  10096. */
  10097. var kurentoClient = require('kurento-client');
  10098. /**
  10099. * Transcoding state for a media.
  10100. *
  10101. * @typedef core/complexTypes.MediaTranscodingState
  10102. *
  10103. * @type {(TRANSCODING|NOT_TRANSCODING)}
  10104. */
  10105. /**
  10106. * Checker for {@link module:core/complexTypes.MediaTranscodingState}
  10107. *
  10108. * @memberof module:core/complexTypes
  10109. *
  10110. * @param {external:String} key
  10111. * @param {module:core/complexTypes.MediaTranscodingState} value
  10112. */
  10113. function checkMediaTranscodingState(key, value)
  10114. {
  10115. if(typeof value != 'string')
  10116. throw SyntaxError(key+' param should be a String, not '+typeof value);
  10117. if(!value.match('TRANSCODING|NOT_TRANSCODING'))
  10118. throw SyntaxError(key+' param is not one of [TRANSCODING|NOT_TRANSCODING] ('+value+')');
  10119. };
  10120. module.exports = checkMediaTranscodingState;
  10121. },{"kurento-client":"kurento-client"}],56:[function(require,module,exports){
  10122. /* Autogenerated with Kurento Idl */
  10123. /*
  10124. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  10125. *
  10126. * Licensed under the Apache License, Version 2.0 (the "License");
  10127. * you may not use this file except in compliance with the License.
  10128. * You may obtain a copy of the License at
  10129. *
  10130. * http://www.apache.org/licenses/LICENSE-2.0
  10131. *
  10132. * Unless required by applicable law or agreed to in writing, software
  10133. * distributed under the License is distributed on an "AS IS" BASIS,
  10134. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10135. * See the License for the specific language governing permissions and
  10136. * limitations under the License.
  10137. */
  10138. var kurentoClient = require('kurento-client');
  10139. /**
  10140. * Type of media stream to be exchanged.
  10141. * Can take the values AUDIO, DATA or VIDEO.
  10142. *
  10143. * @typedef core/complexTypes.MediaType
  10144. *
  10145. * @type {(AUDIO|DATA|VIDEO)}
  10146. */
  10147. /**
  10148. * Checker for {@link module:core/complexTypes.MediaType}
  10149. *
  10150. * @memberof module:core/complexTypes
  10151. *
  10152. * @param {external:String} key
  10153. * @param {module:core/complexTypes.MediaType} value
  10154. */
  10155. function checkMediaType(key, value)
  10156. {
  10157. if(typeof value != 'string')
  10158. throw SyntaxError(key+' param should be a String, not '+typeof value);
  10159. if(!value.match('AUDIO|DATA|VIDEO'))
  10160. throw SyntaxError(key+' param is not one of [AUDIO|DATA|VIDEO] ('+value+')');
  10161. };
  10162. module.exports = checkMediaType;
  10163. },{"kurento-client":"kurento-client"}],57:[function(require,module,exports){
  10164. /* Autogenerated with Kurento Idl */
  10165. /*
  10166. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  10167. *
  10168. * Licensed under the Apache License, Version 2.0 (the "License");
  10169. * you may not use this file except in compliance with the License.
  10170. * You may obtain a copy of the License at
  10171. *
  10172. * http://www.apache.org/licenses/LICENSE-2.0
  10173. *
  10174. * Unless required by applicable law or agreed to in writing, software
  10175. * distributed under the License is distributed on an "AS IS" BASIS,
  10176. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10177. * See the License for the specific language governing permissions and
  10178. * limitations under the License.
  10179. */
  10180. var inherits = require('inherits');
  10181. var kurentoClient = require('kurento-client');
  10182. var checkType = kurentoClient.checkType;
  10183. var ChecktypeError = checkType.ChecktypeError;
  10184. var ComplexType = require('./ComplexType');
  10185. /**
  10186. * Description of a loaded modules
  10187. *
  10188. * @constructor module:core/complexTypes.ModuleInfo
  10189. *
  10190. * @property {external:String} version
  10191. * Module version
  10192. * @property {external:String} name
  10193. * Module name
  10194. * @property {external:String} generationTime
  10195. * Time that this module was generated
  10196. * @property {external:String} factories
  10197. * Module available factories
  10198. */
  10199. function ModuleInfo(moduleInfoDict){
  10200. if(!(this instanceof ModuleInfo))
  10201. return new ModuleInfo(moduleInfoDict)
  10202. moduleInfoDict = moduleInfoDict || {}
  10203. // Check moduleInfoDict has the required fields
  10204. //
  10205. // checkType('String', 'moduleInfoDict.version', moduleInfoDict.version, {required: true});
  10206. //
  10207. // checkType('String', 'moduleInfoDict.name', moduleInfoDict.name, {required: true});
  10208. //
  10209. // checkType('String', 'moduleInfoDict.generationTime', moduleInfoDict.generationTime, {required: true});
  10210. //
  10211. // checkType('String', 'moduleInfoDict.factories', moduleInfoDict.factories, {isArray: true, required: true});
  10212. //
  10213. // Init parent class
  10214. ModuleInfo.super_.call(this, moduleInfoDict)
  10215. // Set object properties
  10216. Object.defineProperties(this, {
  10217. version: {
  10218. writable: true,
  10219. enumerable: true,
  10220. value: moduleInfoDict.version
  10221. },
  10222. name: {
  10223. writable: true,
  10224. enumerable: true,
  10225. value: moduleInfoDict.name
  10226. },
  10227. generationTime: {
  10228. writable: true,
  10229. enumerable: true,
  10230. value: moduleInfoDict.generationTime
  10231. },
  10232. factories: {
  10233. writable: true,
  10234. enumerable: true,
  10235. value: moduleInfoDict.factories
  10236. }
  10237. })
  10238. }
  10239. inherits(ModuleInfo, ComplexType)
  10240. // Private identifiers to allow re-construction of the complexType on the server
  10241. // They need to be enumerable so JSON.stringify() can access to them
  10242. Object.defineProperties(ModuleInfo.prototype, {
  10243. __module__: {
  10244. enumerable: true,
  10245. value: "kurento"
  10246. },
  10247. __type__: {
  10248. enumerable: true,
  10249. value: "ModuleInfo"
  10250. }
  10251. })
  10252. /**
  10253. * Checker for {@link module:core/complexTypes.ModuleInfo}
  10254. *
  10255. * @memberof module:core/complexTypes
  10256. *
  10257. * @param {external:String} key
  10258. * @param {module:core/complexTypes.ModuleInfo} value
  10259. */
  10260. function checkModuleInfo(key, value)
  10261. {
  10262. if(!(value instanceof ModuleInfo))
  10263. throw ChecktypeError(key, ModuleInfo, value);
  10264. };
  10265. module.exports = ModuleInfo;
  10266. ModuleInfo.check = checkModuleInfo;
  10267. },{"./ComplexType":44,"inherits":"inherits","kurento-client":"kurento-client"}],58:[function(require,module,exports){
  10268. /* Autogenerated with Kurento Idl */
  10269. /*
  10270. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  10271. *
  10272. * Licensed under the Apache License, Version 2.0 (the "License");
  10273. * you may not use this file except in compliance with the License.
  10274. * You may obtain a copy of the License at
  10275. *
  10276. * http://www.apache.org/licenses/LICENSE-2.0
  10277. *
  10278. * Unless required by applicable law or agreed to in writing, software
  10279. * distributed under the License is distributed on an "AS IS" BASIS,
  10280. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10281. * See the License for the specific language governing permissions and
  10282. * limitations under the License.
  10283. */
  10284. var inherits = require('inherits');
  10285. var kurentoClient = require('kurento-client');
  10286. var checkType = kurentoClient.checkType;
  10287. var ChecktypeError = checkType.ChecktypeError;
  10288. var RTCStats = require('./RTCStats');
  10289. /**
  10290. *
  10291. * @constructor module:core/complexTypes.RTCCertificateStats
  10292. *
  10293. * @property {external:String} fingerprint
  10294. * Only use the fingerprint value as defined in Section 5 of [RFC4572].
  10295. * @property {external:String} fingerprintAlgorithm
  10296. * For instance, 'sha-256'.
  10297. * @property {external:String} base64Certificate
  10298. * For example, DER-encoded, base-64 representation of a certifiate.
  10299. * @property {external:String} issuerCertificateId
  10300. * @extends module:core.RTCStats
  10301. */
  10302. function RTCCertificateStats(rTCCertificateStatsDict){
  10303. if(!(this instanceof RTCCertificateStats))
  10304. return new RTCCertificateStats(rTCCertificateStatsDict)
  10305. rTCCertificateStatsDict = rTCCertificateStatsDict || {}
  10306. // Check rTCCertificateStatsDict has the required fields
  10307. //
  10308. // checkType('String', 'rTCCertificateStatsDict.fingerprint', rTCCertificateStatsDict.fingerprint, {required: true});
  10309. //
  10310. // checkType('String', 'rTCCertificateStatsDict.fingerprintAlgorithm', rTCCertificateStatsDict.fingerprintAlgorithm, {required: true});
  10311. //
  10312. // checkType('String', 'rTCCertificateStatsDict.base64Certificate', rTCCertificateStatsDict.base64Certificate, {required: true});
  10313. //
  10314. // checkType('String', 'rTCCertificateStatsDict.issuerCertificateId', rTCCertificateStatsDict.issuerCertificateId, {required: true});
  10315. //
  10316. // Init parent class
  10317. RTCCertificateStats.super_.call(this, rTCCertificateStatsDict)
  10318. // Set object properties
  10319. Object.defineProperties(this, {
  10320. fingerprint: {
  10321. writable: true,
  10322. enumerable: true,
  10323. value: rTCCertificateStatsDict.fingerprint
  10324. },
  10325. fingerprintAlgorithm: {
  10326. writable: true,
  10327. enumerable: true,
  10328. value: rTCCertificateStatsDict.fingerprintAlgorithm
  10329. },
  10330. base64Certificate: {
  10331. writable: true,
  10332. enumerable: true,
  10333. value: rTCCertificateStatsDict.base64Certificate
  10334. },
  10335. issuerCertificateId: {
  10336. writable: true,
  10337. enumerable: true,
  10338. value: rTCCertificateStatsDict.issuerCertificateId
  10339. }
  10340. })
  10341. }
  10342. inherits(RTCCertificateStats, RTCStats)
  10343. // Private identifiers to allow re-construction of the complexType on the server
  10344. // They need to be enumerable so JSON.stringify() can access to them
  10345. Object.defineProperties(RTCCertificateStats.prototype, {
  10346. __module__: {
  10347. enumerable: true,
  10348. value: "kurento"
  10349. },
  10350. __type__: {
  10351. enumerable: true,
  10352. value: "RTCCertificateStats"
  10353. }
  10354. })
  10355. /**
  10356. * Checker for {@link module:core/complexTypes.RTCCertificateStats}
  10357. *
  10358. * @memberof module:core/complexTypes
  10359. *
  10360. * @param {external:String} key
  10361. * @param {module:core/complexTypes.RTCCertificateStats} value
  10362. */
  10363. function checkRTCCertificateStats(key, value)
  10364. {
  10365. if(!(value instanceof RTCCertificateStats))
  10366. throw ChecktypeError(key, RTCCertificateStats, value);
  10367. };
  10368. module.exports = RTCCertificateStats;
  10369. RTCCertificateStats.check = checkRTCCertificateStats;
  10370. },{"./RTCStats":70,"inherits":"inherits","kurento-client":"kurento-client"}],59:[function(require,module,exports){
  10371. /* Autogenerated with Kurento Idl */
  10372. /*
  10373. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  10374. *
  10375. * Licensed under the Apache License, Version 2.0 (the "License");
  10376. * you may not use this file except in compliance with the License.
  10377. * You may obtain a copy of the License at
  10378. *
  10379. * http://www.apache.org/licenses/LICENSE-2.0
  10380. *
  10381. * Unless required by applicable law or agreed to in writing, software
  10382. * distributed under the License is distributed on an "AS IS" BASIS,
  10383. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10384. * See the License for the specific language governing permissions and
  10385. * limitations under the License.
  10386. */
  10387. var inherits = require('inherits');
  10388. var kurentoClient = require('kurento-client');
  10389. var checkType = kurentoClient.checkType;
  10390. var ChecktypeError = checkType.ChecktypeError;
  10391. var RTCStats = require('./RTCStats');
  10392. /**
  10393. * RTC codec statistics
  10394. *
  10395. * @constructor module:core/complexTypes.RTCCodec
  10396. *
  10397. * @property {external:int64} payloadType
  10398. * Payload type as used in RTP encoding.
  10399. * @property {external:String} codec
  10400. * e.g., video/vp8 or equivalent.
  10401. * @property {external:int64} clockRate
  10402. * Represents the media sampling rate.
  10403. * @property {external:int64} channels
  10404. * Use 2 for stereo, missing for most other cases.
  10405. * @property {external:String} parameters
  10406. * From the SDP description line.
  10407. * @extends module:core.RTCStats
  10408. */
  10409. function RTCCodec(rTCCodecDict){
  10410. if(!(this instanceof RTCCodec))
  10411. return new RTCCodec(rTCCodecDict)
  10412. rTCCodecDict = rTCCodecDict || {}
  10413. // Check rTCCodecDict has the required fields
  10414. //
  10415. // checkType('int64', 'rTCCodecDict.payloadType', rTCCodecDict.payloadType, {required: true});
  10416. //
  10417. // checkType('String', 'rTCCodecDict.codec', rTCCodecDict.codec, {required: true});
  10418. //
  10419. // checkType('int64', 'rTCCodecDict.clockRate', rTCCodecDict.clockRate, {required: true});
  10420. //
  10421. // checkType('int64', 'rTCCodecDict.channels', rTCCodecDict.channels, {required: true});
  10422. //
  10423. // checkType('String', 'rTCCodecDict.parameters', rTCCodecDict.parameters, {required: true});
  10424. //
  10425. // Init parent class
  10426. RTCCodec.super_.call(this, rTCCodecDict)
  10427. // Set object properties
  10428. Object.defineProperties(this, {
  10429. payloadType: {
  10430. writable: true,
  10431. enumerable: true,
  10432. value: rTCCodecDict.payloadType
  10433. },
  10434. codec: {
  10435. writable: true,
  10436. enumerable: true,
  10437. value: rTCCodecDict.codec
  10438. },
  10439. clockRate: {
  10440. writable: true,
  10441. enumerable: true,
  10442. value: rTCCodecDict.clockRate
  10443. },
  10444. channels: {
  10445. writable: true,
  10446. enumerable: true,
  10447. value: rTCCodecDict.channels
  10448. },
  10449. parameters: {
  10450. writable: true,
  10451. enumerable: true,
  10452. value: rTCCodecDict.parameters
  10453. }
  10454. })
  10455. }
  10456. inherits(RTCCodec, RTCStats)
  10457. // Private identifiers to allow re-construction of the complexType on the server
  10458. // They need to be enumerable so JSON.stringify() can access to them
  10459. Object.defineProperties(RTCCodec.prototype, {
  10460. __module__: {
  10461. enumerable: true,
  10462. value: "kurento"
  10463. },
  10464. __type__: {
  10465. enumerable: true,
  10466. value: "RTCCodec"
  10467. }
  10468. })
  10469. /**
  10470. * Checker for {@link module:core/complexTypes.RTCCodec}
  10471. *
  10472. * @memberof module:core/complexTypes
  10473. *
  10474. * @param {external:String} key
  10475. * @param {module:core/complexTypes.RTCCodec} value
  10476. */
  10477. function checkRTCCodec(key, value)
  10478. {
  10479. if(!(value instanceof RTCCodec))
  10480. throw ChecktypeError(key, RTCCodec, value);
  10481. };
  10482. module.exports = RTCCodec;
  10483. RTCCodec.check = checkRTCCodec;
  10484. },{"./RTCStats":70,"inherits":"inherits","kurento-client":"kurento-client"}],60:[function(require,module,exports){
  10485. /* Autogenerated with Kurento Idl */
  10486. /*
  10487. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  10488. *
  10489. * Licensed under the Apache License, Version 2.0 (the "License");
  10490. * you may not use this file except in compliance with the License.
  10491. * You may obtain a copy of the License at
  10492. *
  10493. * http://www.apache.org/licenses/LICENSE-2.0
  10494. *
  10495. * Unless required by applicable law or agreed to in writing, software
  10496. * distributed under the License is distributed on an "AS IS" BASIS,
  10497. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10498. * See the License for the specific language governing permissions and
  10499. * limitations under the License.
  10500. */
  10501. var kurentoClient = require('kurento-client');
  10502. /**
  10503. * Represents the state of the RTCDataChannel
  10504. *
  10505. * @typedef core/complexTypes.RTCDataChannelState
  10506. *
  10507. * @type {(connecting|open|closing|closed)}
  10508. */
  10509. /**
  10510. * Checker for {@link module:core/complexTypes.RTCDataChannelState}
  10511. *
  10512. * @memberof module:core/complexTypes
  10513. *
  10514. * @param {external:String} key
  10515. * @param {module:core/complexTypes.RTCDataChannelState} value
  10516. */
  10517. function checkRTCDataChannelState(key, value)
  10518. {
  10519. if(typeof value != 'string')
  10520. throw SyntaxError(key+' param should be a String, not '+typeof value);
  10521. if(!value.match('connecting|open|closing|closed'))
  10522. throw SyntaxError(key+' param is not one of [connecting|open|closing|closed] ('+value+')');
  10523. };
  10524. module.exports = checkRTCDataChannelState;
  10525. },{"kurento-client":"kurento-client"}],61:[function(require,module,exports){
  10526. /* Autogenerated with Kurento Idl */
  10527. /*
  10528. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  10529. *
  10530. * Licensed under the Apache License, Version 2.0 (the "License");
  10531. * you may not use this file except in compliance with the License.
  10532. * You may obtain a copy of the License at
  10533. *
  10534. * http://www.apache.org/licenses/LICENSE-2.0
  10535. *
  10536. * Unless required by applicable law or agreed to in writing, software
  10537. * distributed under the License is distributed on an "AS IS" BASIS,
  10538. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10539. * See the License for the specific language governing permissions and
  10540. * limitations under the License.
  10541. */
  10542. var inherits = require('inherits');
  10543. var kurentoClient = require('kurento-client');
  10544. var checkType = kurentoClient.checkType;
  10545. var ChecktypeError = checkType.ChecktypeError;
  10546. var RTCStats = require('./RTCStats');
  10547. /**
  10548. * Statistics related to RTC data channels.
  10549. *
  10550. * @constructor module:core/complexTypes.RTCDataChannelStats
  10551. *
  10552. * @property {external:String} label
  10553. * The RTCDatachannel label.
  10554. * @property {external:String} protocol
  10555. * The protocol used.
  10556. * @property {external:int64} datachannelid
  10557. * The RTCDatachannel identifier.
  10558. * @property {module:core/complexTypes.RTCDataChannelState} state
  10559. * The state of the RTCDatachannel.
  10560. * @property {external:int64} messagesSent
  10561. * Represents the total number of API 'message' events sent.
  10562. * @property {external:int64} bytesSent
  10563. * Represents the total number of payload bytes sent on this RTCDatachannel,
  10564. * i.e., not including headers or padding.
  10565. * @property {external:int64} messagesReceived
  10566. * Represents the total number of API 'message' events received.
  10567. * @property {external:int64} bytesReceived
  10568. * Represents the total number of bytes received on this RTCDatachannel, i.e.,
  10569. * not including headers or padding.
  10570. * @extends module:core.RTCStats
  10571. */
  10572. function RTCDataChannelStats(rTCDataChannelStatsDict){
  10573. if(!(this instanceof RTCDataChannelStats))
  10574. return new RTCDataChannelStats(rTCDataChannelStatsDict)
  10575. rTCDataChannelStatsDict = rTCDataChannelStatsDict || {}
  10576. // Check rTCDataChannelStatsDict has the required fields
  10577. //
  10578. // checkType('String', 'rTCDataChannelStatsDict.label', rTCDataChannelStatsDict.label, {required: true});
  10579. //
  10580. // checkType('String', 'rTCDataChannelStatsDict.protocol', rTCDataChannelStatsDict.protocol, {required: true});
  10581. //
  10582. // checkType('int64', 'rTCDataChannelStatsDict.datachannelid', rTCDataChannelStatsDict.datachannelid, {required: true});
  10583. //
  10584. // checkType('RTCDataChannelState', 'rTCDataChannelStatsDict.state', rTCDataChannelStatsDict.state, {required: true});
  10585. //
  10586. // checkType('int64', 'rTCDataChannelStatsDict.messagesSent', rTCDataChannelStatsDict.messagesSent, {required: true});
  10587. //
  10588. // checkType('int64', 'rTCDataChannelStatsDict.bytesSent', rTCDataChannelStatsDict.bytesSent, {required: true});
  10589. //
  10590. // checkType('int64', 'rTCDataChannelStatsDict.messagesReceived', rTCDataChannelStatsDict.messagesReceived, {required: true});
  10591. //
  10592. // checkType('int64', 'rTCDataChannelStatsDict.bytesReceived', rTCDataChannelStatsDict.bytesReceived, {required: true});
  10593. //
  10594. // Init parent class
  10595. RTCDataChannelStats.super_.call(this, rTCDataChannelStatsDict)
  10596. // Set object properties
  10597. Object.defineProperties(this, {
  10598. label: {
  10599. writable: true,
  10600. enumerable: true,
  10601. value: rTCDataChannelStatsDict.label
  10602. },
  10603. protocol: {
  10604. writable: true,
  10605. enumerable: true,
  10606. value: rTCDataChannelStatsDict.protocol
  10607. },
  10608. datachannelid: {
  10609. writable: true,
  10610. enumerable: true,
  10611. value: rTCDataChannelStatsDict.datachannelid
  10612. },
  10613. state: {
  10614. writable: true,
  10615. enumerable: true,
  10616. value: rTCDataChannelStatsDict.state
  10617. },
  10618. messagesSent: {
  10619. writable: true,
  10620. enumerable: true,
  10621. value: rTCDataChannelStatsDict.messagesSent
  10622. },
  10623. bytesSent: {
  10624. writable: true,
  10625. enumerable: true,
  10626. value: rTCDataChannelStatsDict.bytesSent
  10627. },
  10628. messagesReceived: {
  10629. writable: true,
  10630. enumerable: true,
  10631. value: rTCDataChannelStatsDict.messagesReceived
  10632. },
  10633. bytesReceived: {
  10634. writable: true,
  10635. enumerable: true,
  10636. value: rTCDataChannelStatsDict.bytesReceived
  10637. }
  10638. })
  10639. }
  10640. inherits(RTCDataChannelStats, RTCStats)
  10641. // Private identifiers to allow re-construction of the complexType on the server
  10642. // They need to be enumerable so JSON.stringify() can access to them
  10643. Object.defineProperties(RTCDataChannelStats.prototype, {
  10644. __module__: {
  10645. enumerable: true,
  10646. value: "kurento"
  10647. },
  10648. __type__: {
  10649. enumerable: true,
  10650. value: "RTCDataChannelStats"
  10651. }
  10652. })
  10653. /**
  10654. * Checker for {@link module:core/complexTypes.RTCDataChannelStats}
  10655. *
  10656. * @memberof module:core/complexTypes
  10657. *
  10658. * @param {external:String} key
  10659. * @param {module:core/complexTypes.RTCDataChannelStats} value
  10660. */
  10661. function checkRTCDataChannelStats(key, value)
  10662. {
  10663. if(!(value instanceof RTCDataChannelStats))
  10664. throw ChecktypeError(key, RTCDataChannelStats, value);
  10665. };
  10666. module.exports = RTCDataChannelStats;
  10667. RTCDataChannelStats.check = checkRTCDataChannelStats;
  10668. },{"./RTCStats":70,"inherits":"inherits","kurento-client":"kurento-client"}],62:[function(require,module,exports){
  10669. /* Autogenerated with Kurento Idl */
  10670. /*
  10671. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  10672. *
  10673. * Licensed under the Apache License, Version 2.0 (the "License");
  10674. * you may not use this file except in compliance with the License.
  10675. * You may obtain a copy of the License at
  10676. *
  10677. * http://www.apache.org/licenses/LICENSE-2.0
  10678. *
  10679. * Unless required by applicable law or agreed to in writing, software
  10680. * distributed under the License is distributed on an "AS IS" BASIS,
  10681. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10682. * See the License for the specific language governing permissions and
  10683. * limitations under the License.
  10684. */
  10685. var inherits = require('inherits');
  10686. var kurentoClient = require('kurento-client');
  10687. var checkType = kurentoClient.checkType;
  10688. var ChecktypeError = checkType.ChecktypeError;
  10689. var RTCStats = require('./RTCStats');
  10690. /**
  10691. *
  10692. * @constructor module:core/complexTypes.RTCIceCandidateAttributes
  10693. *
  10694. * @property {external:String} ipAddress
  10695. * It is the IP address of the candidate, allowing for IPv4 addresses, IPv6
  10696. * addresses, and fully qualified domain names (FQDNs).
  10697. * @property {external:int64} portNumber
  10698. * It is the port number of the candidate.
  10699. * @property {external:String} transport
  10700. * Valid values for transport is one of udp and tcp. Based on the 'transport'
  10701. * defined in [RFC5245] section 15.1.
  10702. * @property {module:core/complexTypes.RTCStatsIceCandidateType} candidateType
  10703. * The enumeration RTCStatsIceCandidateType is based on the cand-type defined
  10704. * in [RFC5245] section 15.1.
  10705. * @property {external:int64} priority
  10706. * Represents the priority of the candidate
  10707. * @property {external:String} addressSourceUrl
  10708. * The URL of the TURN or STUN server indicated in the RTCIceServers that
  10709. * translated this IP address.
  10710. * @extends module:core.RTCStats
  10711. */
  10712. function RTCIceCandidateAttributes(rTCIceCandidateAttributesDict){
  10713. if(!(this instanceof RTCIceCandidateAttributes))
  10714. return new RTCIceCandidateAttributes(rTCIceCandidateAttributesDict)
  10715. rTCIceCandidateAttributesDict = rTCIceCandidateAttributesDict || {}
  10716. // Check rTCIceCandidateAttributesDict has the required fields
  10717. //
  10718. // checkType('String', 'rTCIceCandidateAttributesDict.ipAddress', rTCIceCandidateAttributesDict.ipAddress, {required: true});
  10719. //
  10720. // checkType('int64', 'rTCIceCandidateAttributesDict.portNumber', rTCIceCandidateAttributesDict.portNumber, {required: true});
  10721. //
  10722. // checkType('String', 'rTCIceCandidateAttributesDict.transport', rTCIceCandidateAttributesDict.transport, {required: true});
  10723. //
  10724. // checkType('RTCStatsIceCandidateType', 'rTCIceCandidateAttributesDict.candidateType', rTCIceCandidateAttributesDict.candidateType, {required: true});
  10725. //
  10726. // checkType('int64', 'rTCIceCandidateAttributesDict.priority', rTCIceCandidateAttributesDict.priority, {required: true});
  10727. //
  10728. // checkType('String', 'rTCIceCandidateAttributesDict.addressSourceUrl', rTCIceCandidateAttributesDict.addressSourceUrl, {required: true});
  10729. //
  10730. // Init parent class
  10731. RTCIceCandidateAttributes.super_.call(this, rTCIceCandidateAttributesDict)
  10732. // Set object properties
  10733. Object.defineProperties(this, {
  10734. ipAddress: {
  10735. writable: true,
  10736. enumerable: true,
  10737. value: rTCIceCandidateAttributesDict.ipAddress
  10738. },
  10739. portNumber: {
  10740. writable: true,
  10741. enumerable: true,
  10742. value: rTCIceCandidateAttributesDict.portNumber
  10743. },
  10744. transport: {
  10745. writable: true,
  10746. enumerable: true,
  10747. value: rTCIceCandidateAttributesDict.transport
  10748. },
  10749. candidateType: {
  10750. writable: true,
  10751. enumerable: true,
  10752. value: rTCIceCandidateAttributesDict.candidateType
  10753. },
  10754. priority: {
  10755. writable: true,
  10756. enumerable: true,
  10757. value: rTCIceCandidateAttributesDict.priority
  10758. },
  10759. addressSourceUrl: {
  10760. writable: true,
  10761. enumerable: true,
  10762. value: rTCIceCandidateAttributesDict.addressSourceUrl
  10763. }
  10764. })
  10765. }
  10766. inherits(RTCIceCandidateAttributes, RTCStats)
  10767. // Private identifiers to allow re-construction of the complexType on the server
  10768. // They need to be enumerable so JSON.stringify() can access to them
  10769. Object.defineProperties(RTCIceCandidateAttributes.prototype, {
  10770. __module__: {
  10771. enumerable: true,
  10772. value: "kurento"
  10773. },
  10774. __type__: {
  10775. enumerable: true,
  10776. value: "RTCIceCandidateAttributes"
  10777. }
  10778. })
  10779. /**
  10780. * Checker for {@link module:core/complexTypes.RTCIceCandidateAttributes}
  10781. *
  10782. * @memberof module:core/complexTypes
  10783. *
  10784. * @param {external:String} key
  10785. * @param {module:core/complexTypes.RTCIceCandidateAttributes} value
  10786. */
  10787. function checkRTCIceCandidateAttributes(key, value)
  10788. {
  10789. if(!(value instanceof RTCIceCandidateAttributes))
  10790. throw ChecktypeError(key, RTCIceCandidateAttributes, value);
  10791. };
  10792. module.exports = RTCIceCandidateAttributes;
  10793. RTCIceCandidateAttributes.check = checkRTCIceCandidateAttributes;
  10794. },{"./RTCStats":70,"inherits":"inherits","kurento-client":"kurento-client"}],63:[function(require,module,exports){
  10795. /* Autogenerated with Kurento Idl */
  10796. /*
  10797. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  10798. *
  10799. * Licensed under the Apache License, Version 2.0 (the "License");
  10800. * you may not use this file except in compliance with the License.
  10801. * You may obtain a copy of the License at
  10802. *
  10803. * http://www.apache.org/licenses/LICENSE-2.0
  10804. *
  10805. * Unless required by applicable law or agreed to in writing, software
  10806. * distributed under the License is distributed on an "AS IS" BASIS,
  10807. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10808. * See the License for the specific language governing permissions and
  10809. * limitations under the License.
  10810. */
  10811. var inherits = require('inherits');
  10812. var kurentoClient = require('kurento-client');
  10813. var checkType = kurentoClient.checkType;
  10814. var ChecktypeError = checkType.ChecktypeError;
  10815. var RTCStats = require('./RTCStats');
  10816. /**
  10817. *
  10818. * @constructor module:core/complexTypes.RTCIceCandidatePairStats
  10819. *
  10820. * @property {external:String} transportId
  10821. * It is a unique identifier that is associated to the object that was
  10822. * inspected to produce the RTCTransportStats associated with this candidate
  10823. * pair.
  10824. * @property {external:String} localCandidateId
  10825. * It is a unique identifier that is associated to the object that was
  10826. * inspected to produce the RTCIceCandidateAttributes for the local candidate
  10827. * associated with this candidate pair.
  10828. * @property {external:String} remoteCandidateId
  10829. * It is a unique identifier that is associated to the object that was
  10830. * inspected to produce the RTCIceCandidateAttributes for the remote candidate
  10831. * associated with this candidate pair.
  10832. * @property {module:core/complexTypes.RTCStatsIceCandidatePairState} state
  10833. * Represents the state of the checklist for the local and remote candidates in
  10834. * @property {external:int64} priority
  10835. * Calculated from candidate priorities as defined in [RFC5245] section 5.7.2.
  10836. * @property {external:Boolean} nominated
  10837. * Related to updating the nominated flag described in Section 7.1.3.2.4 of
  10838. * [RFC5245].
  10839. * @property {external:Boolean} writable
  10840. * Has gotten ACK to an ICE request.
  10841. * @property {external:Boolean} readable
  10842. * Has gotten a valid incoming ICE request.
  10843. * @property {external:int64} bytesSent
  10844. * Represents the total number of payload bytes sent on this candidate pair,
  10845. * i.e., not including headers or padding.
  10846. * @property {external:int64} bytesReceived
  10847. * Represents the total number of payload bytes received on this candidate
  10848. * pair, i.e., not including headers or padding.
  10849. * @property {external:double} roundTripTime
  10850. * Represents the RTT computed by the STUN connectivity checks
  10851. * @property {external:double} availableOutgoingBitrate
  10852. * Measured in Bits per second, and is implementation dependent. It may be
  10853. * calculated by the underlying congestion control.
  10854. * @property {external:double} availableIncomingBitrate
  10855. * Measured in Bits per second, and is implementation dependent. It may be
  10856. * calculated by the underlying congestion control.
  10857. * @extends module:core.RTCStats
  10858. */
  10859. function RTCIceCandidatePairStats(rTCIceCandidatePairStatsDict){
  10860. if(!(this instanceof RTCIceCandidatePairStats))
  10861. return new RTCIceCandidatePairStats(rTCIceCandidatePairStatsDict)
  10862. rTCIceCandidatePairStatsDict = rTCIceCandidatePairStatsDict || {}
  10863. // Check rTCIceCandidatePairStatsDict has the required fields
  10864. //
  10865. // checkType('String', 'rTCIceCandidatePairStatsDict.transportId', rTCIceCandidatePairStatsDict.transportId, {required: true});
  10866. //
  10867. // checkType('String', 'rTCIceCandidatePairStatsDict.localCandidateId', rTCIceCandidatePairStatsDict.localCandidateId, {required: true});
  10868. //
  10869. // checkType('String', 'rTCIceCandidatePairStatsDict.remoteCandidateId', rTCIceCandidatePairStatsDict.remoteCandidateId, {required: true});
  10870. //
  10871. // checkType('RTCStatsIceCandidatePairState', 'rTCIceCandidatePairStatsDict.state', rTCIceCandidatePairStatsDict.state, {required: true});
  10872. //
  10873. // checkType('int64', 'rTCIceCandidatePairStatsDict.priority', rTCIceCandidatePairStatsDict.priority, {required: true});
  10874. //
  10875. // checkType('boolean', 'rTCIceCandidatePairStatsDict.nominated', rTCIceCandidatePairStatsDict.nominated, {required: true});
  10876. //
  10877. // checkType('boolean', 'rTCIceCandidatePairStatsDict.writable', rTCIceCandidatePairStatsDict.writable, {required: true});
  10878. //
  10879. // checkType('boolean', 'rTCIceCandidatePairStatsDict.readable', rTCIceCandidatePairStatsDict.readable, {required: true});
  10880. //
  10881. // checkType('int64', 'rTCIceCandidatePairStatsDict.bytesSent', rTCIceCandidatePairStatsDict.bytesSent, {required: true});
  10882. //
  10883. // checkType('int64', 'rTCIceCandidatePairStatsDict.bytesReceived', rTCIceCandidatePairStatsDict.bytesReceived, {required: true});
  10884. //
  10885. // checkType('double', 'rTCIceCandidatePairStatsDict.roundTripTime', rTCIceCandidatePairStatsDict.roundTripTime, {required: true});
  10886. //
  10887. // checkType('double', 'rTCIceCandidatePairStatsDict.availableOutgoingBitrate', rTCIceCandidatePairStatsDict.availableOutgoingBitrate, {required: true});
  10888. //
  10889. // checkType('double', 'rTCIceCandidatePairStatsDict.availableIncomingBitrate', rTCIceCandidatePairStatsDict.availableIncomingBitrate, {required: true});
  10890. //
  10891. // Init parent class
  10892. RTCIceCandidatePairStats.super_.call(this, rTCIceCandidatePairStatsDict)
  10893. // Set object properties
  10894. Object.defineProperties(this, {
  10895. transportId: {
  10896. writable: true,
  10897. enumerable: true,
  10898. value: rTCIceCandidatePairStatsDict.transportId
  10899. },
  10900. localCandidateId: {
  10901. writable: true,
  10902. enumerable: true,
  10903. value: rTCIceCandidatePairStatsDict.localCandidateId
  10904. },
  10905. remoteCandidateId: {
  10906. writable: true,
  10907. enumerable: true,
  10908. value: rTCIceCandidatePairStatsDict.remoteCandidateId
  10909. },
  10910. state: {
  10911. writable: true,
  10912. enumerable: true,
  10913. value: rTCIceCandidatePairStatsDict.state
  10914. },
  10915. priority: {
  10916. writable: true,
  10917. enumerable: true,
  10918. value: rTCIceCandidatePairStatsDict.priority
  10919. },
  10920. nominated: {
  10921. writable: true,
  10922. enumerable: true,
  10923. value: rTCIceCandidatePairStatsDict.nominated
  10924. },
  10925. writable: {
  10926. writable: true,
  10927. enumerable: true,
  10928. value: rTCIceCandidatePairStatsDict.writable
  10929. },
  10930. readable: {
  10931. writable: true,
  10932. enumerable: true,
  10933. value: rTCIceCandidatePairStatsDict.readable
  10934. },
  10935. bytesSent: {
  10936. writable: true,
  10937. enumerable: true,
  10938. value: rTCIceCandidatePairStatsDict.bytesSent
  10939. },
  10940. bytesReceived: {
  10941. writable: true,
  10942. enumerable: true,
  10943. value: rTCIceCandidatePairStatsDict.bytesReceived
  10944. },
  10945. roundTripTime: {
  10946. writable: true,
  10947. enumerable: true,
  10948. value: rTCIceCandidatePairStatsDict.roundTripTime
  10949. },
  10950. availableOutgoingBitrate: {
  10951. writable: true,
  10952. enumerable: true,
  10953. value: rTCIceCandidatePairStatsDict.availableOutgoingBitrate
  10954. },
  10955. availableIncomingBitrate: {
  10956. writable: true,
  10957. enumerable: true,
  10958. value: rTCIceCandidatePairStatsDict.availableIncomingBitrate
  10959. }
  10960. })
  10961. }
  10962. inherits(RTCIceCandidatePairStats, RTCStats)
  10963. // Private identifiers to allow re-construction of the complexType on the server
  10964. // They need to be enumerable so JSON.stringify() can access to them
  10965. Object.defineProperties(RTCIceCandidatePairStats.prototype, {
  10966. __module__: {
  10967. enumerable: true,
  10968. value: "kurento"
  10969. },
  10970. __type__: {
  10971. enumerable: true,
  10972. value: "RTCIceCandidatePairStats"
  10973. }
  10974. })
  10975. /**
  10976. * Checker for {@link module:core/complexTypes.RTCIceCandidatePairStats}
  10977. *
  10978. * @memberof module:core/complexTypes
  10979. *
  10980. * @param {external:String} key
  10981. * @param {module:core/complexTypes.RTCIceCandidatePairStats} value
  10982. */
  10983. function checkRTCIceCandidatePairStats(key, value)
  10984. {
  10985. if(!(value instanceof RTCIceCandidatePairStats))
  10986. throw ChecktypeError(key, RTCIceCandidatePairStats, value);
  10987. };
  10988. module.exports = RTCIceCandidatePairStats;
  10989. RTCIceCandidatePairStats.check = checkRTCIceCandidatePairStats;
  10990. },{"./RTCStats":70,"inherits":"inherits","kurento-client":"kurento-client"}],64:[function(require,module,exports){
  10991. /* Autogenerated with Kurento Idl */
  10992. /*
  10993. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  10994. *
  10995. * Licensed under the Apache License, Version 2.0 (the "License");
  10996. * you may not use this file except in compliance with the License.
  10997. * You may obtain a copy of the License at
  10998. *
  10999. * http://www.apache.org/licenses/LICENSE-2.0
  11000. *
  11001. * Unless required by applicable law or agreed to in writing, software
  11002. * distributed under the License is distributed on an "AS IS" BASIS,
  11003. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11004. * See the License for the specific language governing permissions and
  11005. * limitations under the License.
  11006. */
  11007. var inherits = require('inherits');
  11008. var kurentoClient = require('kurento-client');
  11009. var checkType = kurentoClient.checkType;
  11010. var ChecktypeError = checkType.ChecktypeError;
  11011. var RTCRTPStreamStats = require('./RTCRTPStreamStats');
  11012. /**
  11013. * Statistics that represents the measurement metrics for the incoming media
  11014. * stream.
  11015. *
  11016. * @constructor module:core/complexTypes.RTCInboundRTPStreamStats
  11017. *
  11018. * @property {external:int64} packetsReceived
  11019. * Total number of RTP packets received for this SSRC.
  11020. * @property {external:int64} bytesReceived
  11021. * Total number of bytes received for this SSRC.
  11022. * @property {external:double} jitter
  11023. * Packet Jitter measured in seconds for this SSRC.
  11024. * @extends module:core.RTCRTPStreamStats
  11025. */
  11026. function RTCInboundRTPStreamStats(rTCInboundRTPStreamStatsDict){
  11027. if(!(this instanceof RTCInboundRTPStreamStats))
  11028. return new RTCInboundRTPStreamStats(rTCInboundRTPStreamStatsDict)
  11029. rTCInboundRTPStreamStatsDict = rTCInboundRTPStreamStatsDict || {}
  11030. // Check rTCInboundRTPStreamStatsDict has the required fields
  11031. //
  11032. // checkType('int64', 'rTCInboundRTPStreamStatsDict.packetsReceived', rTCInboundRTPStreamStatsDict.packetsReceived, {required: true});
  11033. //
  11034. // checkType('int64', 'rTCInboundRTPStreamStatsDict.bytesReceived', rTCInboundRTPStreamStatsDict.bytesReceived, {required: true});
  11035. //
  11036. // checkType('double', 'rTCInboundRTPStreamStatsDict.jitter', rTCInboundRTPStreamStatsDict.jitter, {required: true});
  11037. //
  11038. // Init parent class
  11039. RTCInboundRTPStreamStats.super_.call(this, rTCInboundRTPStreamStatsDict)
  11040. // Set object properties
  11041. Object.defineProperties(this, {
  11042. packetsReceived: {
  11043. writable: true,
  11044. enumerable: true,
  11045. value: rTCInboundRTPStreamStatsDict.packetsReceived
  11046. },
  11047. bytesReceived: {
  11048. writable: true,
  11049. enumerable: true,
  11050. value: rTCInboundRTPStreamStatsDict.bytesReceived
  11051. },
  11052. jitter: {
  11053. writable: true,
  11054. enumerable: true,
  11055. value: rTCInboundRTPStreamStatsDict.jitter
  11056. }
  11057. })
  11058. }
  11059. inherits(RTCInboundRTPStreamStats, RTCRTPStreamStats)
  11060. // Private identifiers to allow re-construction of the complexType on the server
  11061. // They need to be enumerable so JSON.stringify() can access to them
  11062. Object.defineProperties(RTCInboundRTPStreamStats.prototype, {
  11063. __module__: {
  11064. enumerable: true,
  11065. value: "kurento"
  11066. },
  11067. __type__: {
  11068. enumerable: true,
  11069. value: "RTCInboundRTPStreamStats"
  11070. }
  11071. })
  11072. /**
  11073. * Checker for {@link module:core/complexTypes.RTCInboundRTPStreamStats}
  11074. *
  11075. * @memberof module:core/complexTypes
  11076. *
  11077. * @param {external:String} key
  11078. * @param {module:core/complexTypes.RTCInboundRTPStreamStats} value
  11079. */
  11080. function checkRTCInboundRTPStreamStats(key, value)
  11081. {
  11082. if(!(value instanceof RTCInboundRTPStreamStats))
  11083. throw ChecktypeError(key, RTCInboundRTPStreamStats, value);
  11084. };
  11085. module.exports = RTCInboundRTPStreamStats;
  11086. RTCInboundRTPStreamStats.check = checkRTCInboundRTPStreamStats;
  11087. },{"./RTCRTPStreamStats":69,"inherits":"inherits","kurento-client":"kurento-client"}],65:[function(require,module,exports){
  11088. /* Autogenerated with Kurento Idl */
  11089. /*
  11090. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  11091. *
  11092. * Licensed under the Apache License, Version 2.0 (the "License");
  11093. * you may not use this file except in compliance with the License.
  11094. * You may obtain a copy of the License at
  11095. *
  11096. * http://www.apache.org/licenses/LICENSE-2.0
  11097. *
  11098. * Unless required by applicable law or agreed to in writing, software
  11099. * distributed under the License is distributed on an "AS IS" BASIS,
  11100. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11101. * See the License for the specific language governing permissions and
  11102. * limitations under the License.
  11103. */
  11104. var inherits = require('inherits');
  11105. var kurentoClient = require('kurento-client');
  11106. var checkType = kurentoClient.checkType;
  11107. var ChecktypeError = checkType.ChecktypeError;
  11108. var RTCStats = require('./RTCStats');
  11109. /**
  11110. * Statistics related to the media stream.
  11111. *
  11112. * @constructor module:core/complexTypes.RTCMediaStreamStats
  11113. *
  11114. * @property {external:String} streamIdentifier
  11115. * Stream identifier.
  11116. * @property {external:String} trackIds
  11117. * This is the id of the stats object, not the track.id.
  11118. * @extends module:core.RTCStats
  11119. */
  11120. function RTCMediaStreamStats(rTCMediaStreamStatsDict){
  11121. if(!(this instanceof RTCMediaStreamStats))
  11122. return new RTCMediaStreamStats(rTCMediaStreamStatsDict)
  11123. rTCMediaStreamStatsDict = rTCMediaStreamStatsDict || {}
  11124. // Check rTCMediaStreamStatsDict has the required fields
  11125. //
  11126. // checkType('String', 'rTCMediaStreamStatsDict.streamIdentifier', rTCMediaStreamStatsDict.streamIdentifier, {required: true});
  11127. //
  11128. // checkType('String', 'rTCMediaStreamStatsDict.trackIds', rTCMediaStreamStatsDict.trackIds, {isArray: true, required: true});
  11129. //
  11130. // Init parent class
  11131. RTCMediaStreamStats.super_.call(this, rTCMediaStreamStatsDict)
  11132. // Set object properties
  11133. Object.defineProperties(this, {
  11134. streamIdentifier: {
  11135. writable: true,
  11136. enumerable: true,
  11137. value: rTCMediaStreamStatsDict.streamIdentifier
  11138. },
  11139. trackIds: {
  11140. writable: true,
  11141. enumerable: true,
  11142. value: rTCMediaStreamStatsDict.trackIds
  11143. }
  11144. })
  11145. }
  11146. inherits(RTCMediaStreamStats, RTCStats)
  11147. // Private identifiers to allow re-construction of the complexType on the server
  11148. // They need to be enumerable so JSON.stringify() can access to them
  11149. Object.defineProperties(RTCMediaStreamStats.prototype, {
  11150. __module__: {
  11151. enumerable: true,
  11152. value: "kurento"
  11153. },
  11154. __type__: {
  11155. enumerable: true,
  11156. value: "RTCMediaStreamStats"
  11157. }
  11158. })
  11159. /**
  11160. * Checker for {@link module:core/complexTypes.RTCMediaStreamStats}
  11161. *
  11162. * @memberof module:core/complexTypes
  11163. *
  11164. * @param {external:String} key
  11165. * @param {module:core/complexTypes.RTCMediaStreamStats} value
  11166. */
  11167. function checkRTCMediaStreamStats(key, value)
  11168. {
  11169. if(!(value instanceof RTCMediaStreamStats))
  11170. throw ChecktypeError(key, RTCMediaStreamStats, value);
  11171. };
  11172. module.exports = RTCMediaStreamStats;
  11173. RTCMediaStreamStats.check = checkRTCMediaStreamStats;
  11174. },{"./RTCStats":70,"inherits":"inherits","kurento-client":"kurento-client"}],66:[function(require,module,exports){
  11175. /* Autogenerated with Kurento Idl */
  11176. /*
  11177. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  11178. *
  11179. * Licensed under the Apache License, Version 2.0 (the "License");
  11180. * you may not use this file except in compliance with the License.
  11181. * You may obtain a copy of the License at
  11182. *
  11183. * http://www.apache.org/licenses/LICENSE-2.0
  11184. *
  11185. * Unless required by applicable law or agreed to in writing, software
  11186. * distributed under the License is distributed on an "AS IS" BASIS,
  11187. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11188. * See the License for the specific language governing permissions and
  11189. * limitations under the License.
  11190. */
  11191. var inherits = require('inherits');
  11192. var kurentoClient = require('kurento-client');
  11193. var checkType = kurentoClient.checkType;
  11194. var ChecktypeError = checkType.ChecktypeError;
  11195. var RTCStats = require('./RTCStats');
  11196. /**
  11197. * Statistics related to the media stream.
  11198. *
  11199. * @constructor module:core/complexTypes.RTCMediaStreamTrackStats
  11200. *
  11201. * @property {external:String} trackIdentifier
  11202. * Represents the track.id property.
  11203. * @property {external:Boolean} remoteSource
  11204. * true indicates that this is a remote source. false in other case.
  11205. * @property {external:String} ssrcIds
  11206. * Synchronized sources.
  11207. * @property {external:int64} frameWidth
  11208. * Only makes sense for video media streams and represents the width of the
  11209. * video frame for this SSRC.
  11210. * @property {external:int64} frameHeight
  11211. * Only makes sense for video media streams and represents the height of the
  11212. * video frame for this SSRC.
  11213. * @property {external:double} framesPerSecond
  11214. * Only valid for video. It represents the nominal FPS value.
  11215. * @property {external:int64} framesSent
  11216. * Only valid for video. It represents the total number of frames sent for this
  11217. * @property {external:int64} framesReceived
  11218. * Only valid for video and when remoteSource is set to true. It represents the
  11219. * @property {external:int64} framesDecoded
  11220. * Only valid for video. It represents the total number of frames correctly
  11221. * decoded for this SSRC.
  11222. * @property {external:int64} framesDropped
  11223. * Only valid for video. The total number of frames dropped predecode or
  11224. * dropped because the frame missed its display deadline.
  11225. * @property {external:int64} framesCorrupted
  11226. * Only valid for video. The total number of corrupted frames that have been
  11227. * detected.
  11228. * @property {external:double} audioLevel
  11229. * Only valid for audio, and the value is between 0..1 (linear), where 1.0
  11230. * represents 0 dBov.
  11231. * @property {external:double} echoReturnLoss
  11232. * Only present on audio tracks sourced from a microphone where echo
  11233. * cancellation is applied. Calculated in decibels.
  11234. * @property {external:double} echoReturnLossEnhancement
  11235. * Only present on audio tracks sourced from a microphone where echo
  11236. * cancellation is applied.
  11237. * @extends module:core.RTCStats
  11238. */
  11239. function RTCMediaStreamTrackStats(rTCMediaStreamTrackStatsDict){
  11240. if(!(this instanceof RTCMediaStreamTrackStats))
  11241. return new RTCMediaStreamTrackStats(rTCMediaStreamTrackStatsDict)
  11242. rTCMediaStreamTrackStatsDict = rTCMediaStreamTrackStatsDict || {}
  11243. // Check rTCMediaStreamTrackStatsDict has the required fields
  11244. //
  11245. // checkType('String', 'rTCMediaStreamTrackStatsDict.trackIdentifier', rTCMediaStreamTrackStatsDict.trackIdentifier, {required: true});
  11246. //
  11247. // checkType('boolean', 'rTCMediaStreamTrackStatsDict.remoteSource', rTCMediaStreamTrackStatsDict.remoteSource, {required: true});
  11248. //
  11249. // checkType('String', 'rTCMediaStreamTrackStatsDict.ssrcIds', rTCMediaStreamTrackStatsDict.ssrcIds, {isArray: true, required: true});
  11250. //
  11251. // checkType('int64', 'rTCMediaStreamTrackStatsDict.frameWidth', rTCMediaStreamTrackStatsDict.frameWidth, {required: true});
  11252. //
  11253. // checkType('int64', 'rTCMediaStreamTrackStatsDict.frameHeight', rTCMediaStreamTrackStatsDict.frameHeight, {required: true});
  11254. //
  11255. // checkType('double', 'rTCMediaStreamTrackStatsDict.framesPerSecond', rTCMediaStreamTrackStatsDict.framesPerSecond, {required: true});
  11256. //
  11257. // checkType('int64', 'rTCMediaStreamTrackStatsDict.framesSent', rTCMediaStreamTrackStatsDict.framesSent, {required: true});
  11258. //
  11259. // checkType('int64', 'rTCMediaStreamTrackStatsDict.framesReceived', rTCMediaStreamTrackStatsDict.framesReceived, {required: true});
  11260. //
  11261. // checkType('int64', 'rTCMediaStreamTrackStatsDict.framesDecoded', rTCMediaStreamTrackStatsDict.framesDecoded, {required: true});
  11262. //
  11263. // checkType('int64', 'rTCMediaStreamTrackStatsDict.framesDropped', rTCMediaStreamTrackStatsDict.framesDropped, {required: true});
  11264. //
  11265. // checkType('int64', 'rTCMediaStreamTrackStatsDict.framesCorrupted', rTCMediaStreamTrackStatsDict.framesCorrupted, {required: true});
  11266. //
  11267. // checkType('double', 'rTCMediaStreamTrackStatsDict.audioLevel', rTCMediaStreamTrackStatsDict.audioLevel, {required: true});
  11268. //
  11269. // checkType('double', 'rTCMediaStreamTrackStatsDict.echoReturnLoss', rTCMediaStreamTrackStatsDict.echoReturnLoss, {required: true});
  11270. //
  11271. // checkType('double', 'rTCMediaStreamTrackStatsDict.echoReturnLossEnhancement', rTCMediaStreamTrackStatsDict.echoReturnLossEnhancement, {required: true});
  11272. //
  11273. // Init parent class
  11274. RTCMediaStreamTrackStats.super_.call(this, rTCMediaStreamTrackStatsDict)
  11275. // Set object properties
  11276. Object.defineProperties(this, {
  11277. trackIdentifier: {
  11278. writable: true,
  11279. enumerable: true,
  11280. value: rTCMediaStreamTrackStatsDict.trackIdentifier
  11281. },
  11282. remoteSource: {
  11283. writable: true,
  11284. enumerable: true,
  11285. value: rTCMediaStreamTrackStatsDict.remoteSource
  11286. },
  11287. ssrcIds: {
  11288. writable: true,
  11289. enumerable: true,
  11290. value: rTCMediaStreamTrackStatsDict.ssrcIds
  11291. },
  11292. frameWidth: {
  11293. writable: true,
  11294. enumerable: true,
  11295. value: rTCMediaStreamTrackStatsDict.frameWidth
  11296. },
  11297. frameHeight: {
  11298. writable: true,
  11299. enumerable: true,
  11300. value: rTCMediaStreamTrackStatsDict.frameHeight
  11301. },
  11302. framesPerSecond: {
  11303. writable: true,
  11304. enumerable: true,
  11305. value: rTCMediaStreamTrackStatsDict.framesPerSecond
  11306. },
  11307. framesSent: {
  11308. writable: true,
  11309. enumerable: true,
  11310. value: rTCMediaStreamTrackStatsDict.framesSent
  11311. },
  11312. framesReceived: {
  11313. writable: true,
  11314. enumerable: true,
  11315. value: rTCMediaStreamTrackStatsDict.framesReceived
  11316. },
  11317. framesDecoded: {
  11318. writable: true,
  11319. enumerable: true,
  11320. value: rTCMediaStreamTrackStatsDict.framesDecoded
  11321. },
  11322. framesDropped: {
  11323. writable: true,
  11324. enumerable: true,
  11325. value: rTCMediaStreamTrackStatsDict.framesDropped
  11326. },
  11327. framesCorrupted: {
  11328. writable: true,
  11329. enumerable: true,
  11330. value: rTCMediaStreamTrackStatsDict.framesCorrupted
  11331. },
  11332. audioLevel: {
  11333. writable: true,
  11334. enumerable: true,
  11335. value: rTCMediaStreamTrackStatsDict.audioLevel
  11336. },
  11337. echoReturnLoss: {
  11338. writable: true,
  11339. enumerable: true,
  11340. value: rTCMediaStreamTrackStatsDict.echoReturnLoss
  11341. },
  11342. echoReturnLossEnhancement: {
  11343. writable: true,
  11344. enumerable: true,
  11345. value: rTCMediaStreamTrackStatsDict.echoReturnLossEnhancement
  11346. }
  11347. })
  11348. }
  11349. inherits(RTCMediaStreamTrackStats, RTCStats)
  11350. // Private identifiers to allow re-construction of the complexType on the server
  11351. // They need to be enumerable so JSON.stringify() can access to them
  11352. Object.defineProperties(RTCMediaStreamTrackStats.prototype, {
  11353. __module__: {
  11354. enumerable: true,
  11355. value: "kurento"
  11356. },
  11357. __type__: {
  11358. enumerable: true,
  11359. value: "RTCMediaStreamTrackStats"
  11360. }
  11361. })
  11362. /**
  11363. * Checker for {@link module:core/complexTypes.RTCMediaStreamTrackStats}
  11364. *
  11365. * @memberof module:core/complexTypes
  11366. *
  11367. * @param {external:String} key
  11368. * @param {module:core/complexTypes.RTCMediaStreamTrackStats} value
  11369. */
  11370. function checkRTCMediaStreamTrackStats(key, value)
  11371. {
  11372. if(!(value instanceof RTCMediaStreamTrackStats))
  11373. throw ChecktypeError(key, RTCMediaStreamTrackStats, value);
  11374. };
  11375. module.exports = RTCMediaStreamTrackStats;
  11376. RTCMediaStreamTrackStats.check = checkRTCMediaStreamTrackStats;
  11377. },{"./RTCStats":70,"inherits":"inherits","kurento-client":"kurento-client"}],67:[function(require,module,exports){
  11378. /* Autogenerated with Kurento Idl */
  11379. /*
  11380. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  11381. *
  11382. * Licensed under the Apache License, Version 2.0 (the "License");
  11383. * you may not use this file except in compliance with the License.
  11384. * You may obtain a copy of the License at
  11385. *
  11386. * http://www.apache.org/licenses/LICENSE-2.0
  11387. *
  11388. * Unless required by applicable law or agreed to in writing, software
  11389. * distributed under the License is distributed on an "AS IS" BASIS,
  11390. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11391. * See the License for the specific language governing permissions and
  11392. * limitations under the License.
  11393. */
  11394. var inherits = require('inherits');
  11395. var kurentoClient = require('kurento-client');
  11396. var checkType = kurentoClient.checkType;
  11397. var ChecktypeError = checkType.ChecktypeError;
  11398. var RTCRTPStreamStats = require('./RTCRTPStreamStats');
  11399. /**
  11400. * Statistics that represents the measurement metrics for the outgoing media
  11401. * stream.
  11402. *
  11403. * @constructor module:core/complexTypes.RTCOutboundRTPStreamStats
  11404. *
  11405. * @property {external:int64} packetsSent
  11406. * Total number of RTP packets sent for this SSRC.
  11407. * @property {external:int64} bytesSent
  11408. * Total number of bytes sent for this SSRC.
  11409. * @property {external:double} targetBitrate
  11410. * Presently configured bitrate target of this SSRC, in bits per second.
  11411. * @property {external:double} roundTripTime
  11412. * Estimated round trip time (seconds) for this SSRC based on the RTCP
  11413. * timestamp.
  11414. * @extends module:core.RTCRTPStreamStats
  11415. */
  11416. function RTCOutboundRTPStreamStats(rTCOutboundRTPStreamStatsDict){
  11417. if(!(this instanceof RTCOutboundRTPStreamStats))
  11418. return new RTCOutboundRTPStreamStats(rTCOutboundRTPStreamStatsDict)
  11419. rTCOutboundRTPStreamStatsDict = rTCOutboundRTPStreamStatsDict || {}
  11420. // Check rTCOutboundRTPStreamStatsDict has the required fields
  11421. //
  11422. // checkType('int64', 'rTCOutboundRTPStreamStatsDict.packetsSent', rTCOutboundRTPStreamStatsDict.packetsSent, {required: true});
  11423. //
  11424. // checkType('int64', 'rTCOutboundRTPStreamStatsDict.bytesSent', rTCOutboundRTPStreamStatsDict.bytesSent, {required: true});
  11425. //
  11426. // checkType('double', 'rTCOutboundRTPStreamStatsDict.targetBitrate', rTCOutboundRTPStreamStatsDict.targetBitrate, {required: true});
  11427. //
  11428. // checkType('double', 'rTCOutboundRTPStreamStatsDict.roundTripTime', rTCOutboundRTPStreamStatsDict.roundTripTime, {required: true});
  11429. //
  11430. // Init parent class
  11431. RTCOutboundRTPStreamStats.super_.call(this, rTCOutboundRTPStreamStatsDict)
  11432. // Set object properties
  11433. Object.defineProperties(this, {
  11434. packetsSent: {
  11435. writable: true,
  11436. enumerable: true,
  11437. value: rTCOutboundRTPStreamStatsDict.packetsSent
  11438. },
  11439. bytesSent: {
  11440. writable: true,
  11441. enumerable: true,
  11442. value: rTCOutboundRTPStreamStatsDict.bytesSent
  11443. },
  11444. targetBitrate: {
  11445. writable: true,
  11446. enumerable: true,
  11447. value: rTCOutboundRTPStreamStatsDict.targetBitrate
  11448. },
  11449. roundTripTime: {
  11450. writable: true,
  11451. enumerable: true,
  11452. value: rTCOutboundRTPStreamStatsDict.roundTripTime
  11453. }
  11454. })
  11455. }
  11456. inherits(RTCOutboundRTPStreamStats, RTCRTPStreamStats)
  11457. // Private identifiers to allow re-construction of the complexType on the server
  11458. // They need to be enumerable so JSON.stringify() can access to them
  11459. Object.defineProperties(RTCOutboundRTPStreamStats.prototype, {
  11460. __module__: {
  11461. enumerable: true,
  11462. value: "kurento"
  11463. },
  11464. __type__: {
  11465. enumerable: true,
  11466. value: "RTCOutboundRTPStreamStats"
  11467. }
  11468. })
  11469. /**
  11470. * Checker for {@link module:core/complexTypes.RTCOutboundRTPStreamStats}
  11471. *
  11472. * @memberof module:core/complexTypes
  11473. *
  11474. * @param {external:String} key
  11475. * @param {module:core/complexTypes.RTCOutboundRTPStreamStats} value
  11476. */
  11477. function checkRTCOutboundRTPStreamStats(key, value)
  11478. {
  11479. if(!(value instanceof RTCOutboundRTPStreamStats))
  11480. throw ChecktypeError(key, RTCOutboundRTPStreamStats, value);
  11481. };
  11482. module.exports = RTCOutboundRTPStreamStats;
  11483. RTCOutboundRTPStreamStats.check = checkRTCOutboundRTPStreamStats;
  11484. },{"./RTCRTPStreamStats":69,"inherits":"inherits","kurento-client":"kurento-client"}],68:[function(require,module,exports){
  11485. /* Autogenerated with Kurento Idl */
  11486. /*
  11487. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  11488. *
  11489. * Licensed under the Apache License, Version 2.0 (the "License");
  11490. * you may not use this file except in compliance with the License.
  11491. * You may obtain a copy of the License at
  11492. *
  11493. * http://www.apache.org/licenses/LICENSE-2.0
  11494. *
  11495. * Unless required by applicable law or agreed to in writing, software
  11496. * distributed under the License is distributed on an "AS IS" BASIS,
  11497. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11498. * See the License for the specific language governing permissions and
  11499. * limitations under the License.
  11500. */
  11501. var inherits = require('inherits');
  11502. var kurentoClient = require('kurento-client');
  11503. var checkType = kurentoClient.checkType;
  11504. var ChecktypeError = checkType.ChecktypeError;
  11505. var RTCStats = require('./RTCStats');
  11506. /**
  11507. * Statistics related to the peer connection.
  11508. *
  11509. * @constructor module:core/complexTypes.RTCPeerConnectionStats
  11510. *
  11511. * @property {external:int64} dataChannelsOpened
  11512. * Represents the number of unique datachannels opened.
  11513. * @property {external:int64} dataChannelsClosed
  11514. * Represents the number of unique datachannels closed.
  11515. * @extends module:core.RTCStats
  11516. */
  11517. function RTCPeerConnectionStats(rTCPeerConnectionStatsDict){
  11518. if(!(this instanceof RTCPeerConnectionStats))
  11519. return new RTCPeerConnectionStats(rTCPeerConnectionStatsDict)
  11520. rTCPeerConnectionStatsDict = rTCPeerConnectionStatsDict || {}
  11521. // Check rTCPeerConnectionStatsDict has the required fields
  11522. //
  11523. // checkType('int64', 'rTCPeerConnectionStatsDict.dataChannelsOpened', rTCPeerConnectionStatsDict.dataChannelsOpened, {required: true});
  11524. //
  11525. // checkType('int64', 'rTCPeerConnectionStatsDict.dataChannelsClosed', rTCPeerConnectionStatsDict.dataChannelsClosed, {required: true});
  11526. //
  11527. // Init parent class
  11528. RTCPeerConnectionStats.super_.call(this, rTCPeerConnectionStatsDict)
  11529. // Set object properties
  11530. Object.defineProperties(this, {
  11531. dataChannelsOpened: {
  11532. writable: true,
  11533. enumerable: true,
  11534. value: rTCPeerConnectionStatsDict.dataChannelsOpened
  11535. },
  11536. dataChannelsClosed: {
  11537. writable: true,
  11538. enumerable: true,
  11539. value: rTCPeerConnectionStatsDict.dataChannelsClosed
  11540. }
  11541. })
  11542. }
  11543. inherits(RTCPeerConnectionStats, RTCStats)
  11544. // Private identifiers to allow re-construction of the complexType on the server
  11545. // They need to be enumerable so JSON.stringify() can access to them
  11546. Object.defineProperties(RTCPeerConnectionStats.prototype, {
  11547. __module__: {
  11548. enumerable: true,
  11549. value: "kurento"
  11550. },
  11551. __type__: {
  11552. enumerable: true,
  11553. value: "RTCPeerConnectionStats"
  11554. }
  11555. })
  11556. /**
  11557. * Checker for {@link module:core/complexTypes.RTCPeerConnectionStats}
  11558. *
  11559. * @memberof module:core/complexTypes
  11560. *
  11561. * @param {external:String} key
  11562. * @param {module:core/complexTypes.RTCPeerConnectionStats} value
  11563. */
  11564. function checkRTCPeerConnectionStats(key, value)
  11565. {
  11566. if(!(value instanceof RTCPeerConnectionStats))
  11567. throw ChecktypeError(key, RTCPeerConnectionStats, value);
  11568. };
  11569. module.exports = RTCPeerConnectionStats;
  11570. RTCPeerConnectionStats.check = checkRTCPeerConnectionStats;
  11571. },{"./RTCStats":70,"inherits":"inherits","kurento-client":"kurento-client"}],69:[function(require,module,exports){
  11572. /* Autogenerated with Kurento Idl */
  11573. /*
  11574. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  11575. *
  11576. * Licensed under the Apache License, Version 2.0 (the "License");
  11577. * you may not use this file except in compliance with the License.
  11578. * You may obtain a copy of the License at
  11579. *
  11580. * http://www.apache.org/licenses/LICENSE-2.0
  11581. *
  11582. * Unless required by applicable law or agreed to in writing, software
  11583. * distributed under the License is distributed on an "AS IS" BASIS,
  11584. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11585. * See the License for the specific language governing permissions and
  11586. * limitations under the License.
  11587. */
  11588. var inherits = require('inherits');
  11589. var kurentoClient = require('kurento-client');
  11590. var checkType = kurentoClient.checkType;
  11591. var ChecktypeError = checkType.ChecktypeError;
  11592. var RTCStats = require('./RTCStats');
  11593. /**
  11594. * Statistics for the RTP stream
  11595. *
  11596. * @constructor module:core/complexTypes.RTCRTPStreamStats
  11597. *
  11598. * @property {external:String} ssrc
  11599. * The synchronized source SSRC
  11600. * @property {external:String} associateStatsId
  11601. * The associateStatsId is used for looking up the corresponding (local/remote)
  11602. * @property {external:Boolean} isRemote
  11603. * false indicates that the statistics are measured locally, while true
  11604. * indicates that the measurements were done at the remote endpoint and
  11605. * reported in an RTCP RR/XR.
  11606. * @property {external:String} mediaTrackId
  11607. * Track identifier.
  11608. * @property {external:String} transportId
  11609. * It is a unique identifier that is associated to the object that was
  11610. * inspected to produce the RTCTransportStats associated with this RTP stream.
  11611. * @property {external:String} codecId
  11612. * The codec identifier
  11613. * @property {external:int64} firCount
  11614. * Count the total number of Full Intra Request (FIR) packets received by the
  11615. * sender. This metric is only valid for video and is sent by receiver.
  11616. * @property {external:int64} pliCount
  11617. * Count the total number of Packet Loss Indication (PLI) packets received by
  11618. * the sender and is sent by receiver.
  11619. * @property {external:int64} nackCount
  11620. * Count the total number of Negative ACKnowledgement (NACK) packets received
  11621. * by the sender and is sent by receiver.
  11622. * @property {external:int64} sliCount
  11623. * Count the total number of Slice Loss Indication (SLI) packets received by
  11624. * the sender. This metric is only valid for video and is sent by receiver.
  11625. * @property {external:int64} remb
  11626. * The Receiver Estimated Maximum Bitrate (REMB). This metric is only valid for
  11627. * @property {external:int64} packetsLost
  11628. * Total number of RTP packets lost for this SSRC.
  11629. * @property {external:double} fractionLost
  11630. * The fraction packet loss reported for this SSRC.
  11631. * @extends module:core.RTCStats
  11632. */
  11633. function RTCRTPStreamStats(rTCRTPStreamStatsDict){
  11634. if(!(this instanceof RTCRTPStreamStats))
  11635. return new RTCRTPStreamStats(rTCRTPStreamStatsDict)
  11636. rTCRTPStreamStatsDict = rTCRTPStreamStatsDict || {}
  11637. // Check rTCRTPStreamStatsDict has the required fields
  11638. //
  11639. // checkType('String', 'rTCRTPStreamStatsDict.ssrc', rTCRTPStreamStatsDict.ssrc, {required: true});
  11640. //
  11641. // checkType('String', 'rTCRTPStreamStatsDict.associateStatsId', rTCRTPStreamStatsDict.associateStatsId, {required: true});
  11642. //
  11643. // checkType('boolean', 'rTCRTPStreamStatsDict.isRemote', rTCRTPStreamStatsDict.isRemote, {required: true});
  11644. //
  11645. // checkType('String', 'rTCRTPStreamStatsDict.mediaTrackId', rTCRTPStreamStatsDict.mediaTrackId, {required: true});
  11646. //
  11647. // checkType('String', 'rTCRTPStreamStatsDict.transportId', rTCRTPStreamStatsDict.transportId, {required: true});
  11648. //
  11649. // checkType('String', 'rTCRTPStreamStatsDict.codecId', rTCRTPStreamStatsDict.codecId, {required: true});
  11650. //
  11651. // checkType('int64', 'rTCRTPStreamStatsDict.firCount', rTCRTPStreamStatsDict.firCount, {required: true});
  11652. //
  11653. // checkType('int64', 'rTCRTPStreamStatsDict.pliCount', rTCRTPStreamStatsDict.pliCount, {required: true});
  11654. //
  11655. // checkType('int64', 'rTCRTPStreamStatsDict.nackCount', rTCRTPStreamStatsDict.nackCount, {required: true});
  11656. //
  11657. // checkType('int64', 'rTCRTPStreamStatsDict.sliCount', rTCRTPStreamStatsDict.sliCount, {required: true});
  11658. //
  11659. // checkType('int64', 'rTCRTPStreamStatsDict.remb', rTCRTPStreamStatsDict.remb, {required: true});
  11660. //
  11661. // checkType('int64', 'rTCRTPStreamStatsDict.packetsLost', rTCRTPStreamStatsDict.packetsLost, {required: true});
  11662. //
  11663. // checkType('double', 'rTCRTPStreamStatsDict.fractionLost', rTCRTPStreamStatsDict.fractionLost, {required: true});
  11664. //
  11665. // Init parent class
  11666. RTCRTPStreamStats.super_.call(this, rTCRTPStreamStatsDict)
  11667. // Set object properties
  11668. Object.defineProperties(this, {
  11669. ssrc: {
  11670. writable: true,
  11671. enumerable: true,
  11672. value: rTCRTPStreamStatsDict.ssrc
  11673. },
  11674. associateStatsId: {
  11675. writable: true,
  11676. enumerable: true,
  11677. value: rTCRTPStreamStatsDict.associateStatsId
  11678. },
  11679. isRemote: {
  11680. writable: true,
  11681. enumerable: true,
  11682. value: rTCRTPStreamStatsDict.isRemote
  11683. },
  11684. mediaTrackId: {
  11685. writable: true,
  11686. enumerable: true,
  11687. value: rTCRTPStreamStatsDict.mediaTrackId
  11688. },
  11689. transportId: {
  11690. writable: true,
  11691. enumerable: true,
  11692. value: rTCRTPStreamStatsDict.transportId
  11693. },
  11694. codecId: {
  11695. writable: true,
  11696. enumerable: true,
  11697. value: rTCRTPStreamStatsDict.codecId
  11698. },
  11699. firCount: {
  11700. writable: true,
  11701. enumerable: true,
  11702. value: rTCRTPStreamStatsDict.firCount
  11703. },
  11704. pliCount: {
  11705. writable: true,
  11706. enumerable: true,
  11707. value: rTCRTPStreamStatsDict.pliCount
  11708. },
  11709. nackCount: {
  11710. writable: true,
  11711. enumerable: true,
  11712. value: rTCRTPStreamStatsDict.nackCount
  11713. },
  11714. sliCount: {
  11715. writable: true,
  11716. enumerable: true,
  11717. value: rTCRTPStreamStatsDict.sliCount
  11718. },
  11719. remb: {
  11720. writable: true,
  11721. enumerable: true,
  11722. value: rTCRTPStreamStatsDict.remb
  11723. },
  11724. packetsLost: {
  11725. writable: true,
  11726. enumerable: true,
  11727. value: rTCRTPStreamStatsDict.packetsLost
  11728. },
  11729. fractionLost: {
  11730. writable: true,
  11731. enumerable: true,
  11732. value: rTCRTPStreamStatsDict.fractionLost
  11733. }
  11734. })
  11735. }
  11736. inherits(RTCRTPStreamStats, RTCStats)
  11737. // Private identifiers to allow re-construction of the complexType on the server
  11738. // They need to be enumerable so JSON.stringify() can access to them
  11739. Object.defineProperties(RTCRTPStreamStats.prototype, {
  11740. __module__: {
  11741. enumerable: true,
  11742. value: "kurento"
  11743. },
  11744. __type__: {
  11745. enumerable: true,
  11746. value: "RTCRTPStreamStats"
  11747. }
  11748. })
  11749. /**
  11750. * Checker for {@link module:core/complexTypes.RTCRTPStreamStats}
  11751. *
  11752. * @memberof module:core/complexTypes
  11753. *
  11754. * @param {external:String} key
  11755. * @param {module:core/complexTypes.RTCRTPStreamStats} value
  11756. */
  11757. function checkRTCRTPStreamStats(key, value)
  11758. {
  11759. if(!(value instanceof RTCRTPStreamStats))
  11760. throw ChecktypeError(key, RTCRTPStreamStats, value);
  11761. };
  11762. module.exports = RTCRTPStreamStats;
  11763. RTCRTPStreamStats.check = checkRTCRTPStreamStats;
  11764. },{"./RTCStats":70,"inherits":"inherits","kurento-client":"kurento-client"}],70:[function(require,module,exports){
  11765. /* Autogenerated with Kurento Idl */
  11766. /*
  11767. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  11768. *
  11769. * Licensed under the Apache License, Version 2.0 (the "License");
  11770. * you may not use this file except in compliance with the License.
  11771. * You may obtain a copy of the License at
  11772. *
  11773. * http://www.apache.org/licenses/LICENSE-2.0
  11774. *
  11775. * Unless required by applicable law or agreed to in writing, software
  11776. * distributed under the License is distributed on an "AS IS" BASIS,
  11777. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11778. * See the License for the specific language governing permissions and
  11779. * limitations under the License.
  11780. */
  11781. var inherits = require('inherits');
  11782. var kurentoClient = require('kurento-client');
  11783. var checkType = kurentoClient.checkType;
  11784. var ChecktypeError = checkType.ChecktypeError;
  11785. var Stats = require('./Stats');
  11786. /**
  11787. * An RTCStats dictionary represents the stats gathered.
  11788. *
  11789. * @constructor module:core/complexTypes.RTCStats
  11790. *
  11791. * @extends module:core.Stats
  11792. */
  11793. function RTCStats(rTCStatsDict){
  11794. if(!(this instanceof RTCStats))
  11795. return new RTCStats(rTCStatsDict)
  11796. rTCStatsDict = rTCStatsDict || {}
  11797. // Check rTCStatsDict has the required fields
  11798. //
  11799. // Init parent class
  11800. RTCStats.super_.call(this, rTCStatsDict)
  11801. // Set object properties
  11802. Object.defineProperties(this, {
  11803. })
  11804. }
  11805. inherits(RTCStats, Stats)
  11806. // Private identifiers to allow re-construction of the complexType on the server
  11807. // They need to be enumerable so JSON.stringify() can access to them
  11808. Object.defineProperties(RTCStats.prototype, {
  11809. __module__: {
  11810. enumerable: true,
  11811. value: "kurento"
  11812. },
  11813. __type__: {
  11814. enumerable: true,
  11815. value: "RTCStats"
  11816. }
  11817. })
  11818. /**
  11819. * Checker for {@link module:core/complexTypes.RTCStats}
  11820. *
  11821. * @memberof module:core/complexTypes
  11822. *
  11823. * @param {external:String} key
  11824. * @param {module:core/complexTypes.RTCStats} value
  11825. */
  11826. function checkRTCStats(key, value)
  11827. {
  11828. if(!(value instanceof RTCStats))
  11829. throw ChecktypeError(key, RTCStats, value);
  11830. };
  11831. module.exports = RTCStats;
  11832. RTCStats.check = checkRTCStats;
  11833. },{"./Stats":77,"inherits":"inherits","kurento-client":"kurento-client"}],71:[function(require,module,exports){
  11834. /* Autogenerated with Kurento Idl */
  11835. /*
  11836. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  11837. *
  11838. * Licensed under the Apache License, Version 2.0 (the "License");
  11839. * you may not use this file except in compliance with the License.
  11840. * You may obtain a copy of the License at
  11841. *
  11842. * http://www.apache.org/licenses/LICENSE-2.0
  11843. *
  11844. * Unless required by applicable law or agreed to in writing, software
  11845. * distributed under the License is distributed on an "AS IS" BASIS,
  11846. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11847. * See the License for the specific language governing permissions and
  11848. * limitations under the License.
  11849. */
  11850. var kurentoClient = require('kurento-client');
  11851. /**
  11852. * Represents the state of the checklist for the local and remote candidates in
  11853. * a pair.
  11854. *
  11855. * @typedef core/complexTypes.RTCStatsIceCandidatePairState
  11856. *
  11857. * @type {(frozen|waiting|inprogress|failed|succeeded|cancelled)}
  11858. */
  11859. /**
  11860. * Checker for {@link module:core/complexTypes.RTCStatsIceCandidatePairState}
  11861. *
  11862. * @memberof module:core/complexTypes
  11863. *
  11864. * @param {external:String} key
  11865. * @param {module:core/complexTypes.RTCStatsIceCandidatePairState} value
  11866. */
  11867. function checkRTCStatsIceCandidatePairState(key, value)
  11868. {
  11869. if(typeof value != 'string')
  11870. throw SyntaxError(key+' param should be a String, not '+typeof value);
  11871. if(!value.match('frozen|waiting|inprogress|failed|succeeded|cancelled'))
  11872. throw SyntaxError(key+' param is not one of [frozen|waiting|inprogress|failed|succeeded|cancelled] ('+value+')');
  11873. };
  11874. module.exports = checkRTCStatsIceCandidatePairState;
  11875. },{"kurento-client":"kurento-client"}],72:[function(require,module,exports){
  11876. /* Autogenerated with Kurento Idl */
  11877. /*
  11878. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  11879. *
  11880. * Licensed under the Apache License, Version 2.0 (the "License");
  11881. * you may not use this file except in compliance with the License.
  11882. * You may obtain a copy of the License at
  11883. *
  11884. * http://www.apache.org/licenses/LICENSE-2.0
  11885. *
  11886. * Unless required by applicable law or agreed to in writing, software
  11887. * distributed under the License is distributed on an "AS IS" BASIS,
  11888. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11889. * See the License for the specific language governing permissions and
  11890. * limitations under the License.
  11891. */
  11892. var kurentoClient = require('kurento-client');
  11893. /**
  11894. * Types of candidates
  11895. *
  11896. * @typedef core/complexTypes.RTCStatsIceCandidateType
  11897. *
  11898. * @type {(host|serverreflexive|peerreflexive|relayed)}
  11899. */
  11900. /**
  11901. * Checker for {@link module:core/complexTypes.RTCStatsIceCandidateType}
  11902. *
  11903. * @memberof module:core/complexTypes
  11904. *
  11905. * @param {external:String} key
  11906. * @param {module:core/complexTypes.RTCStatsIceCandidateType} value
  11907. */
  11908. function checkRTCStatsIceCandidateType(key, value)
  11909. {
  11910. if(typeof value != 'string')
  11911. throw SyntaxError(key+' param should be a String, not '+typeof value);
  11912. if(!value.match('host|serverreflexive|peerreflexive|relayed'))
  11913. throw SyntaxError(key+' param is not one of [host|serverreflexive|peerreflexive|relayed] ('+value+')');
  11914. };
  11915. module.exports = checkRTCStatsIceCandidateType;
  11916. },{"kurento-client":"kurento-client"}],73:[function(require,module,exports){
  11917. /* Autogenerated with Kurento Idl */
  11918. /*
  11919. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  11920. *
  11921. * Licensed under the Apache License, Version 2.0 (the "License");
  11922. * you may not use this file except in compliance with the License.
  11923. * You may obtain a copy of the License at
  11924. *
  11925. * http://www.apache.org/licenses/LICENSE-2.0
  11926. *
  11927. * Unless required by applicable law or agreed to in writing, software
  11928. * distributed under the License is distributed on an "AS IS" BASIS,
  11929. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11930. * See the License for the specific language governing permissions and
  11931. * limitations under the License.
  11932. */
  11933. var inherits = require('inherits');
  11934. var kurentoClient = require('kurento-client');
  11935. var checkType = kurentoClient.checkType;
  11936. var ChecktypeError = checkType.ChecktypeError;
  11937. var RTCStats = require('./RTCStats');
  11938. /**
  11939. * Statistics related to RTC data channels.
  11940. *
  11941. * @constructor module:core/complexTypes.RTCTransportStats
  11942. *
  11943. * @property {external:int64} bytesSent
  11944. * Represents the total number of payload bytes sent on this PeerConnection,
  11945. * i.e., not including headers or padding.
  11946. * @property {external:int64} bytesReceived
  11947. * Represents the total number of bytes received on this PeerConnection, i.e.,
  11948. * not including headers or padding.
  11949. * @property {external:String} rtcpTransportStatsId
  11950. * If RTP and RTCP are not multiplexed, this is the id of the transport that
  11951. * gives stats for the RTCP component, and this record has only the RTP
  11952. * component stats.
  11953. * @property {external:Boolean} activeConnection
  11954. * Set to true when transport is active.
  11955. * @property {external:String} selectedCandidatePairId
  11956. * It is a unique identifier that is associated to the object that was
  11957. * inspected to produce the RTCIceCandidatePairStats associated with this
  11958. * transport.
  11959. * @property {external:String} localCertificateId
  11960. * For components where DTLS is negotiated, give local certificate.
  11961. * @property {external:String} remoteCertificateId
  11962. * For components where DTLS is negotiated, give remote certificate.
  11963. * @extends module:core.RTCStats
  11964. */
  11965. function RTCTransportStats(rTCTransportStatsDict){
  11966. if(!(this instanceof RTCTransportStats))
  11967. return new RTCTransportStats(rTCTransportStatsDict)
  11968. rTCTransportStatsDict = rTCTransportStatsDict || {}
  11969. // Check rTCTransportStatsDict has the required fields
  11970. //
  11971. // checkType('int64', 'rTCTransportStatsDict.bytesSent', rTCTransportStatsDict.bytesSent, {required: true});
  11972. //
  11973. // checkType('int64', 'rTCTransportStatsDict.bytesReceived', rTCTransportStatsDict.bytesReceived, {required: true});
  11974. //
  11975. // checkType('String', 'rTCTransportStatsDict.rtcpTransportStatsId', rTCTransportStatsDict.rtcpTransportStatsId, {required: true});
  11976. //
  11977. // checkType('boolean', 'rTCTransportStatsDict.activeConnection', rTCTransportStatsDict.activeConnection, {required: true});
  11978. //
  11979. // checkType('String', 'rTCTransportStatsDict.selectedCandidatePairId', rTCTransportStatsDict.selectedCandidatePairId, {required: true});
  11980. //
  11981. // checkType('String', 'rTCTransportStatsDict.localCertificateId', rTCTransportStatsDict.localCertificateId, {required: true});
  11982. //
  11983. // checkType('String', 'rTCTransportStatsDict.remoteCertificateId', rTCTransportStatsDict.remoteCertificateId, {required: true});
  11984. //
  11985. // Init parent class
  11986. RTCTransportStats.super_.call(this, rTCTransportStatsDict)
  11987. // Set object properties
  11988. Object.defineProperties(this, {
  11989. bytesSent: {
  11990. writable: true,
  11991. enumerable: true,
  11992. value: rTCTransportStatsDict.bytesSent
  11993. },
  11994. bytesReceived: {
  11995. writable: true,
  11996. enumerable: true,
  11997. value: rTCTransportStatsDict.bytesReceived
  11998. },
  11999. rtcpTransportStatsId: {
  12000. writable: true,
  12001. enumerable: true,
  12002. value: rTCTransportStatsDict.rtcpTransportStatsId
  12003. },
  12004. activeConnection: {
  12005. writable: true,
  12006. enumerable: true,
  12007. value: rTCTransportStatsDict.activeConnection
  12008. },
  12009. selectedCandidatePairId: {
  12010. writable: true,
  12011. enumerable: true,
  12012. value: rTCTransportStatsDict.selectedCandidatePairId
  12013. },
  12014. localCertificateId: {
  12015. writable: true,
  12016. enumerable: true,
  12017. value: rTCTransportStatsDict.localCertificateId
  12018. },
  12019. remoteCertificateId: {
  12020. writable: true,
  12021. enumerable: true,
  12022. value: rTCTransportStatsDict.remoteCertificateId
  12023. }
  12024. })
  12025. }
  12026. inherits(RTCTransportStats, RTCStats)
  12027. // Private identifiers to allow re-construction of the complexType on the server
  12028. // They need to be enumerable so JSON.stringify() can access to them
  12029. Object.defineProperties(RTCTransportStats.prototype, {
  12030. __module__: {
  12031. enumerable: true,
  12032. value: "kurento"
  12033. },
  12034. __type__: {
  12035. enumerable: true,
  12036. value: "RTCTransportStats"
  12037. }
  12038. })
  12039. /**
  12040. * Checker for {@link module:core/complexTypes.RTCTransportStats}
  12041. *
  12042. * @memberof module:core/complexTypes
  12043. *
  12044. * @param {external:String} key
  12045. * @param {module:core/complexTypes.RTCTransportStats} value
  12046. */
  12047. function checkRTCTransportStats(key, value)
  12048. {
  12049. if(!(value instanceof RTCTransportStats))
  12050. throw ChecktypeError(key, RTCTransportStats, value);
  12051. };
  12052. module.exports = RTCTransportStats;
  12053. RTCTransportStats.check = checkRTCTransportStats;
  12054. },{"./RTCStats":70,"inherits":"inherits","kurento-client":"kurento-client"}],74:[function(require,module,exports){
  12055. /* Autogenerated with Kurento Idl */
  12056. /*
  12057. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  12058. *
  12059. * Licensed under the Apache License, Version 2.0 (the "License");
  12060. * you may not use this file except in compliance with the License.
  12061. * You may obtain a copy of the License at
  12062. *
  12063. * http://www.apache.org/licenses/LICENSE-2.0
  12064. *
  12065. * Unless required by applicable law or agreed to in writing, software
  12066. * distributed under the License is distributed on an "AS IS" BASIS,
  12067. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12068. * See the License for the specific language governing permissions and
  12069. * limitations under the License.
  12070. */
  12071. var inherits = require('inherits');
  12072. var kurentoClient = require('kurento-client');
  12073. var checkType = kurentoClient.checkType;
  12074. var ChecktypeError = checkType.ChecktypeError;
  12075. var ComplexType = require('./ComplexType');
  12076. /**
  12077. * Defines values for parameters of congestion control
  12078. *
  12079. * @constructor module:core/complexTypes.RembParams
  12080. *
  12081. * @property {external:Integer} packetsRecvIntervalTop
  12082. * Size of the RTP packets history to smooth fraction-lost.
  12083. * Units: num of packets
  12084. * @property {external:Number} exponentialFactor
  12085. * Factor used to increase exponentially the next REMB when it is below the
  12086. * threshold.
  12087. * REMB[i+1] = REMB[i] * (1 + exponentialFactor)
  12088. * @property {external:Integer} linealFactorMin
  12089. * Set the min of the factor used to increase linearly the next REMB when it is
  12090. * Units: bps (bits per second).
  12091. * REMB[i+1] = REMB[i] + MIN (linealFactorMin, linealFactor)
  12092. * @property {external:Number} linealFactorGrade
  12093. * Determine the value of the next linearFactor based on the threshold and the
  12094. * current REMB. Taking into account that the frequency of updating is 500ms,
  12095. * the default value makes that the last REMB is reached in 60secs.
  12096. * linealFactor = (REMB - TH) / linealFactorGrade
  12097. * @property {external:Number} decrementFactor
  12098. * Determine how much is decreased the current REMB when too losses are
  12099. * detected.
  12100. * REMB[i+1] = REMB[i] * decrementFactor
  12101. * @property {external:Number} thresholdFactor
  12102. * Determine the next threshold (TH) when too losses are detected.
  12103. * TH[i+1] = REMB[i] * thresholdFactor
  12104. * @property {external:Integer} upLosses
  12105. * Max fraction-lost to no determine too losses. This value is the denominator
  12106. * of the fraction N/256, so the default value is about 4% of losses (12/256)
  12107. * @property {external:Integer} rembOnConnect
  12108. * Initial local REMB bandwidth estimation that gets propagated when a new
  12109. * endpoint is connected.
  12110. * <p>
  12111. * The REMB congestion control algorithm works by gradually increasing the
  12112. * output
  12113. * video bitrate, until the available bandwidth is fully used or the maximum
  12114. * send
  12115. * bitrate has been reached. This is a slow, progressive change, which starts
  12116. * 300 kbps by default. You can change the default starting point of REMB
  12117. * estimations, by setting this parameter.
  12118. * </p>
  12119. * <p>
  12120. * <b>WARNING</b>: If you set this parameter to a high value that is
  12121. * <i>higher than the network capacity</i>, then all endpoints will start
  12122. * already
  12123. * in a congested state, providing very bad video quality until the
  12124. * congestion
  12125. * control algorithm is able to recover from the situation. Network
  12126. * congestion is
  12127. * very unpredictable, so be careful when changing this parameter; for most
  12128. * use
  12129. * cases it is safer to just start with a low initial value and allow the
  12130. * REMB
  12131. * algorithm to raise until the optimum bitrate is reached.
  12132. * </p>
  12133. * <ul>
  12134. * <li>Unit: bps (bits per second).</li>
  12135. * <li>Default: 300000 (300 kbps).</li>
  12136. * </ul>
  12137. */
  12138. function RembParams(rembParamsDict){
  12139. if(!(this instanceof RembParams))
  12140. return new RembParams(rembParamsDict)
  12141. rembParamsDict = rembParamsDict || {}
  12142. // Check rembParamsDict has the required fields
  12143. //
  12144. // checkType('int', 'rembParamsDict.packetsRecvIntervalTop', rembParamsDict.packetsRecvIntervalTop);
  12145. //
  12146. // checkType('float', 'rembParamsDict.exponentialFactor', rembParamsDict.exponentialFactor);
  12147. //
  12148. // checkType('int', 'rembParamsDict.linealFactorMin', rembParamsDict.linealFactorMin);
  12149. //
  12150. // checkType('float', 'rembParamsDict.linealFactorGrade', rembParamsDict.linealFactorGrade);
  12151. //
  12152. // checkType('float', 'rembParamsDict.decrementFactor', rembParamsDict.decrementFactor);
  12153. //
  12154. // checkType('float', 'rembParamsDict.thresholdFactor', rembParamsDict.thresholdFactor);
  12155. //
  12156. // checkType('int', 'rembParamsDict.upLosses', rembParamsDict.upLosses);
  12157. //
  12158. // checkType('int', 'rembParamsDict.rembOnConnect', rembParamsDict.rembOnConnect);
  12159. //
  12160. // Init parent class
  12161. RembParams.super_.call(this, rembParamsDict)
  12162. // Set object properties
  12163. Object.defineProperties(this, {
  12164. packetsRecvIntervalTop: {
  12165. writable: true,
  12166. enumerable: true,
  12167. value: rembParamsDict.packetsRecvIntervalTop
  12168. },
  12169. exponentialFactor: {
  12170. writable: true,
  12171. enumerable: true,
  12172. value: rembParamsDict.exponentialFactor
  12173. },
  12174. linealFactorMin: {
  12175. writable: true,
  12176. enumerable: true,
  12177. value: rembParamsDict.linealFactorMin
  12178. },
  12179. linealFactorGrade: {
  12180. writable: true,
  12181. enumerable: true,
  12182. value: rembParamsDict.linealFactorGrade
  12183. },
  12184. decrementFactor: {
  12185. writable: true,
  12186. enumerable: true,
  12187. value: rembParamsDict.decrementFactor
  12188. },
  12189. thresholdFactor: {
  12190. writable: true,
  12191. enumerable: true,
  12192. value: rembParamsDict.thresholdFactor
  12193. },
  12194. upLosses: {
  12195. writable: true,
  12196. enumerable: true,
  12197. value: rembParamsDict.upLosses
  12198. },
  12199. rembOnConnect: {
  12200. writable: true,
  12201. enumerable: true,
  12202. value: rembParamsDict.rembOnConnect
  12203. }
  12204. })
  12205. }
  12206. inherits(RembParams, ComplexType)
  12207. // Private identifiers to allow re-construction of the complexType on the server
  12208. // They need to be enumerable so JSON.stringify() can access to them
  12209. Object.defineProperties(RembParams.prototype, {
  12210. __module__: {
  12211. enumerable: true,
  12212. value: "kurento"
  12213. },
  12214. __type__: {
  12215. enumerable: true,
  12216. value: "RembParams"
  12217. }
  12218. })
  12219. /**
  12220. * Checker for {@link module:core/complexTypes.RembParams}
  12221. *
  12222. * @memberof module:core/complexTypes
  12223. *
  12224. * @param {external:String} key
  12225. * @param {module:core/complexTypes.RembParams} value
  12226. */
  12227. function checkRembParams(key, value)
  12228. {
  12229. if(!(value instanceof RembParams))
  12230. throw ChecktypeError(key, RembParams, value);
  12231. };
  12232. module.exports = RembParams;
  12233. RembParams.check = checkRembParams;
  12234. },{"./ComplexType":44,"inherits":"inherits","kurento-client":"kurento-client"}],75:[function(require,module,exports){
  12235. /* Autogenerated with Kurento Idl */
  12236. /*
  12237. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  12238. *
  12239. * Licensed under the Apache License, Version 2.0 (the "License");
  12240. * you may not use this file except in compliance with the License.
  12241. * You may obtain a copy of the License at
  12242. *
  12243. * http://www.apache.org/licenses/LICENSE-2.0
  12244. *
  12245. * Unless required by applicable law or agreed to in writing, software
  12246. * distributed under the License is distributed on an "AS IS" BASIS,
  12247. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12248. * See the License for the specific language governing permissions and
  12249. * limitations under the License.
  12250. */
  12251. var inherits = require('inherits');
  12252. var kurentoClient = require('kurento-client');
  12253. var checkType = kurentoClient.checkType;
  12254. var ChecktypeError = checkType.ChecktypeError;
  12255. var ComplexType = require('./ComplexType');
  12256. /**
  12257. * Description of the mediaserver
  12258. *
  12259. * @constructor module:core/complexTypes.ServerInfo
  12260. *
  12261. * @property {external:String} version
  12262. * MediaServer version
  12263. * @property {module:core/complexTypes.ModuleInfo} modules
  12264. * Descriptor of all modules loaded by the server
  12265. * @property {module:core/complexTypes.ServerType} type
  12266. * Describes the type of mediaserver
  12267. * @property {external:String} capabilities
  12268. * Describes the capabilities that this server supports
  12269. */
  12270. function ServerInfo(serverInfoDict){
  12271. if(!(this instanceof ServerInfo))
  12272. return new ServerInfo(serverInfoDict)
  12273. serverInfoDict = serverInfoDict || {}
  12274. // Check serverInfoDict has the required fields
  12275. //
  12276. // checkType('String', 'serverInfoDict.version', serverInfoDict.version, {required: true});
  12277. //
  12278. // checkType('ModuleInfo', 'serverInfoDict.modules', serverInfoDict.modules, {isArray: true, required: true});
  12279. //
  12280. // checkType('ServerType', 'serverInfoDict.type', serverInfoDict.type, {required: true});
  12281. //
  12282. // checkType('String', 'serverInfoDict.capabilities', serverInfoDict.capabilities, {isArray: true, required: true});
  12283. //
  12284. // Init parent class
  12285. ServerInfo.super_.call(this, serverInfoDict)
  12286. // Set object properties
  12287. Object.defineProperties(this, {
  12288. version: {
  12289. writable: true,
  12290. enumerable: true,
  12291. value: serverInfoDict.version
  12292. },
  12293. modules: {
  12294. writable: true,
  12295. enumerable: true,
  12296. value: serverInfoDict.modules
  12297. },
  12298. type: {
  12299. writable: true,
  12300. enumerable: true,
  12301. value: serverInfoDict.type
  12302. },
  12303. capabilities: {
  12304. writable: true,
  12305. enumerable: true,
  12306. value: serverInfoDict.capabilities
  12307. }
  12308. })
  12309. }
  12310. inherits(ServerInfo, ComplexType)
  12311. // Private identifiers to allow re-construction of the complexType on the server
  12312. // They need to be enumerable so JSON.stringify() can access to them
  12313. Object.defineProperties(ServerInfo.prototype, {
  12314. __module__: {
  12315. enumerable: true,
  12316. value: "kurento"
  12317. },
  12318. __type__: {
  12319. enumerable: true,
  12320. value: "ServerInfo"
  12321. }
  12322. })
  12323. /**
  12324. * Checker for {@link module:core/complexTypes.ServerInfo}
  12325. *
  12326. * @memberof module:core/complexTypes
  12327. *
  12328. * @param {external:String} key
  12329. * @param {module:core/complexTypes.ServerInfo} value
  12330. */
  12331. function checkServerInfo(key, value)
  12332. {
  12333. if(!(value instanceof ServerInfo))
  12334. throw ChecktypeError(key, ServerInfo, value);
  12335. };
  12336. module.exports = ServerInfo;
  12337. ServerInfo.check = checkServerInfo;
  12338. },{"./ComplexType":44,"inherits":"inherits","kurento-client":"kurento-client"}],76:[function(require,module,exports){
  12339. /* Autogenerated with Kurento Idl */
  12340. /*
  12341. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  12342. *
  12343. * Licensed under the Apache License, Version 2.0 (the "License");
  12344. * you may not use this file except in compliance with the License.
  12345. * You may obtain a copy of the License at
  12346. *
  12347. * http://www.apache.org/licenses/LICENSE-2.0
  12348. *
  12349. * Unless required by applicable law or agreed to in writing, software
  12350. * distributed under the License is distributed on an "AS IS" BASIS,
  12351. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12352. * See the License for the specific language governing permissions and
  12353. * limitations under the License.
  12354. */
  12355. var kurentoClient = require('kurento-client');
  12356. /**
  12357. * Indicates if the server is a real media server or a proxy
  12358. *
  12359. * @typedef core/complexTypes.ServerType
  12360. *
  12361. * @type {(KMS|KCS)}
  12362. */
  12363. /**
  12364. * Checker for {@link module:core/complexTypes.ServerType}
  12365. *
  12366. * @memberof module:core/complexTypes
  12367. *
  12368. * @param {external:String} key
  12369. * @param {module:core/complexTypes.ServerType} value
  12370. */
  12371. function checkServerType(key, value)
  12372. {
  12373. if(typeof value != 'string')
  12374. throw SyntaxError(key+' param should be a String, not '+typeof value);
  12375. if(!value.match('KMS|KCS'))
  12376. throw SyntaxError(key+' param is not one of [KMS|KCS] ('+value+')');
  12377. };
  12378. module.exports = checkServerType;
  12379. },{"kurento-client":"kurento-client"}],77:[function(require,module,exports){
  12380. /* Autogenerated with Kurento Idl */
  12381. /*
  12382. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  12383. *
  12384. * Licensed under the Apache License, Version 2.0 (the "License");
  12385. * you may not use this file except in compliance with the License.
  12386. * You may obtain a copy of the License at
  12387. *
  12388. * http://www.apache.org/licenses/LICENSE-2.0
  12389. *
  12390. * Unless required by applicable law or agreed to in writing, software
  12391. * distributed under the License is distributed on an "AS IS" BASIS,
  12392. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12393. * See the License for the specific language governing permissions and
  12394. * limitations under the License.
  12395. */
  12396. var inherits = require('inherits');
  12397. var kurentoClient = require('kurento-client');
  12398. var checkType = kurentoClient.checkType;
  12399. var ChecktypeError = checkType.ChecktypeError;
  12400. var ComplexType = require('./ComplexType');
  12401. /**
  12402. * A dictionary that represents the stats gathered.
  12403. *
  12404. * @constructor module:core/complexTypes.Stats
  12405. *
  12406. * @property {external:String} id
  12407. * A unique id that is associated with the object that was inspected to produce
  12408. * @property {module:core/complexTypes.StatsType} type
  12409. * The type of this object.
  12410. * @property {external:double} timestamp
  12411. * [DEPRECATED: Use timestampMillis] The timestamp associated with this object:
  12412. * @property {external:int64} timestampMillis
  12413. * The timestamp associated with this event: Milliseconds elapsed since the
  12414. * UNIX Epoch (Jan 1, 1970, UTC).
  12415. */
  12416. function Stats(statsDict){
  12417. if(!(this instanceof Stats))
  12418. return new Stats(statsDict)
  12419. statsDict = statsDict || {}
  12420. // Check statsDict has the required fields
  12421. //
  12422. // checkType('String', 'statsDict.id', statsDict.id, {required: true});
  12423. //
  12424. // checkType('StatsType', 'statsDict.type', statsDict.type, {required: true});
  12425. //
  12426. // checkType('double', 'statsDict.timestamp', statsDict.timestamp, {required: true});
  12427. //
  12428. // checkType('int64', 'statsDict.timestampMillis', statsDict.timestampMillis, {required: true});
  12429. //
  12430. // Init parent class
  12431. Stats.super_.call(this, statsDict)
  12432. // Set object properties
  12433. Object.defineProperties(this, {
  12434. id: {
  12435. writable: true,
  12436. enumerable: true,
  12437. value: statsDict.id
  12438. },
  12439. type: {
  12440. writable: true,
  12441. enumerable: true,
  12442. value: statsDict.type
  12443. },
  12444. timestamp: {
  12445. writable: true,
  12446. enumerable: true,
  12447. value: statsDict.timestamp
  12448. },
  12449. timestampMillis: {
  12450. writable: true,
  12451. enumerable: true,
  12452. value: statsDict.timestampMillis
  12453. }
  12454. })
  12455. }
  12456. inherits(Stats, ComplexType)
  12457. // Private identifiers to allow re-construction of the complexType on the server
  12458. // They need to be enumerable so JSON.stringify() can access to them
  12459. Object.defineProperties(Stats.prototype, {
  12460. __module__: {
  12461. enumerable: true,
  12462. value: "kurento"
  12463. },
  12464. __type__: {
  12465. enumerable: true,
  12466. value: "Stats"
  12467. }
  12468. })
  12469. /**
  12470. * Checker for {@link module:core/complexTypes.Stats}
  12471. *
  12472. * @memberof module:core/complexTypes
  12473. *
  12474. * @param {external:String} key
  12475. * @param {module:core/complexTypes.Stats} value
  12476. */
  12477. function checkStats(key, value)
  12478. {
  12479. if(!(value instanceof Stats))
  12480. throw ChecktypeError(key, Stats, value);
  12481. };
  12482. module.exports = Stats;
  12483. Stats.check = checkStats;
  12484. },{"./ComplexType":44,"inherits":"inherits","kurento-client":"kurento-client"}],78:[function(require,module,exports){
  12485. /* Autogenerated with Kurento Idl */
  12486. /*
  12487. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  12488. *
  12489. * Licensed under the Apache License, Version 2.0 (the "License");
  12490. * you may not use this file except in compliance with the License.
  12491. * You may obtain a copy of the License at
  12492. *
  12493. * http://www.apache.org/licenses/LICENSE-2.0
  12494. *
  12495. * Unless required by applicable law or agreed to in writing, software
  12496. * distributed under the License is distributed on an "AS IS" BASIS,
  12497. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12498. * See the License for the specific language governing permissions and
  12499. * limitations under the License.
  12500. */
  12501. var kurentoClient = require('kurento-client');
  12502. /**
  12503. * The type of the object.
  12504. *
  12505. * @typedef core/complexTypes.StatsType
  12506. *
  12507. * @type {(inboundrtp|outboundrtp|session|datachannel|track|transport|candidatepair|localcandidate|remotecandidate|element|endpoint)}
  12508. */
  12509. /**
  12510. * Checker for {@link module:core/complexTypes.StatsType}
  12511. *
  12512. * @memberof module:core/complexTypes
  12513. *
  12514. * @param {external:String} key
  12515. * @param {module:core/complexTypes.StatsType} value
  12516. */
  12517. function checkStatsType(key, value)
  12518. {
  12519. if(typeof value != 'string')
  12520. throw SyntaxError(key+' param should be a String, not '+typeof value);
  12521. if(!value.match('inboundrtp|outboundrtp|session|datachannel|track|transport|candidatepair|localcandidate|remotecandidate|element|endpoint'))
  12522. throw SyntaxError(key+' param is not one of [inboundrtp|outboundrtp|session|datachannel|track|transport|candidatepair|localcandidate|remotecandidate|element|endpoint] ('+value+')');
  12523. };
  12524. module.exports = checkStatsType;
  12525. },{"kurento-client":"kurento-client"}],79:[function(require,module,exports){
  12526. /* Autogenerated with Kurento Idl */
  12527. /*
  12528. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  12529. *
  12530. * Licensed under the Apache License, Version 2.0 (the "License");
  12531. * you may not use this file except in compliance with the License.
  12532. * You may obtain a copy of the License at
  12533. *
  12534. * http://www.apache.org/licenses/LICENSE-2.0
  12535. *
  12536. * Unless required by applicable law or agreed to in writing, software
  12537. * distributed under the License is distributed on an "AS IS" BASIS,
  12538. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12539. * See the License for the specific language governing permissions and
  12540. * limitations under the License.
  12541. */
  12542. var inherits = require('inherits');
  12543. var kurentoClient = require('kurento-client');
  12544. var checkType = kurentoClient.checkType;
  12545. var ChecktypeError = checkType.ChecktypeError;
  12546. var ComplexType = require('./ComplexType');
  12547. /**
  12548. * Pair key-value with info about a MediaObject
  12549. *
  12550. * @constructor module:core/complexTypes.Tag
  12551. *
  12552. * @property {external:String} key
  12553. * Tag key
  12554. * @property {external:String} value
  12555. * Tag Value
  12556. */
  12557. function Tag(tagDict){
  12558. if(!(this instanceof Tag))
  12559. return new Tag(tagDict)
  12560. tagDict = tagDict || {}
  12561. // Check tagDict has the required fields
  12562. //
  12563. // checkType('String', 'tagDict.key', tagDict.key, {required: true});
  12564. //
  12565. // checkType('String', 'tagDict.value', tagDict.value, {required: true});
  12566. //
  12567. // Init parent class
  12568. Tag.super_.call(this, tagDict)
  12569. // Set object properties
  12570. Object.defineProperties(this, {
  12571. key: {
  12572. writable: true,
  12573. enumerable: true,
  12574. value: tagDict.key
  12575. },
  12576. value: {
  12577. writable: true,
  12578. enumerable: true,
  12579. value: tagDict.value
  12580. }
  12581. })
  12582. }
  12583. inherits(Tag, ComplexType)
  12584. // Private identifiers to allow re-construction of the complexType on the server
  12585. // They need to be enumerable so JSON.stringify() can access to them
  12586. Object.defineProperties(Tag.prototype, {
  12587. __module__: {
  12588. enumerable: true,
  12589. value: "kurento"
  12590. },
  12591. __type__: {
  12592. enumerable: true,
  12593. value: "Tag"
  12594. }
  12595. })
  12596. /**
  12597. * Checker for {@link module:core/complexTypes.Tag}
  12598. *
  12599. * @memberof module:core/complexTypes
  12600. *
  12601. * @param {external:String} key
  12602. * @param {module:core/complexTypes.Tag} value
  12603. */
  12604. function checkTag(key, value)
  12605. {
  12606. if(!(value instanceof Tag))
  12607. throw ChecktypeError(key, Tag, value);
  12608. };
  12609. module.exports = Tag;
  12610. Tag.check = checkTag;
  12611. },{"./ComplexType":44,"inherits":"inherits","kurento-client":"kurento-client"}],80:[function(require,module,exports){
  12612. /* Autogenerated with Kurento Idl */
  12613. /*
  12614. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  12615. *
  12616. * Licensed under the Apache License, Version 2.0 (the "License");
  12617. * you may not use this file except in compliance with the License.
  12618. * You may obtain a copy of the License at
  12619. *
  12620. * http://www.apache.org/licenses/LICENSE-2.0
  12621. *
  12622. * Unless required by applicable law or agreed to in writing, software
  12623. * distributed under the License is distributed on an "AS IS" BASIS,
  12624. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12625. * See the License for the specific language governing permissions and
  12626. * limitations under the License.
  12627. */
  12628. var kurentoClient = require('kurento-client');
  12629. /**
  12630. * State of the endpoint
  12631. *
  12632. * @typedef core/complexTypes.UriEndpointState
  12633. *
  12634. * @type {(STOP|START|PAUSE)}
  12635. */
  12636. /**
  12637. * Checker for {@link module:core/complexTypes.UriEndpointState}
  12638. *
  12639. * @memberof module:core/complexTypes
  12640. *
  12641. * @param {external:String} key
  12642. * @param {module:core/complexTypes.UriEndpointState} value
  12643. */
  12644. function checkUriEndpointState(key, value)
  12645. {
  12646. if(typeof value != 'string')
  12647. throw SyntaxError(key+' param should be a String, not '+typeof value);
  12648. if(!value.match('STOP|START|PAUSE'))
  12649. throw SyntaxError(key+' param is not one of [STOP|START|PAUSE] ('+value+')');
  12650. };
  12651. module.exports = checkUriEndpointState;
  12652. },{"kurento-client":"kurento-client"}],81:[function(require,module,exports){
  12653. /* Autogenerated with Kurento Idl */
  12654. /*
  12655. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  12656. *
  12657. * Licensed under the Apache License, Version 2.0 (the "License");
  12658. * you may not use this file except in compliance with the License.
  12659. * You may obtain a copy of the License at
  12660. *
  12661. * http://www.apache.org/licenses/LICENSE-2.0
  12662. *
  12663. * Unless required by applicable law or agreed to in writing, software
  12664. * distributed under the License is distributed on an "AS IS" BASIS,
  12665. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12666. * See the License for the specific language governing permissions and
  12667. * limitations under the License.
  12668. */
  12669. var inherits = require('inherits');
  12670. var kurentoClient = require('kurento-client');
  12671. var checkType = kurentoClient.checkType;
  12672. var ChecktypeError = checkType.ChecktypeError;
  12673. var ComplexType = require('./ComplexType');
  12674. /**
  12675. * Format for video media
  12676. *
  12677. * @constructor module:core/complexTypes.VideoCaps
  12678. *
  12679. * @property {module:core/complexTypes.VideoCodec} codec
  12680. * Video codec
  12681. * @property {module:core/complexTypes.Fraction} framerate
  12682. * Framerate
  12683. */
  12684. function VideoCaps(videoCapsDict){
  12685. if(!(this instanceof VideoCaps))
  12686. return new VideoCaps(videoCapsDict)
  12687. videoCapsDict = videoCapsDict || {}
  12688. // Check videoCapsDict has the required fields
  12689. //
  12690. // checkType('VideoCodec', 'videoCapsDict.codec', videoCapsDict.codec, {required: true});
  12691. //
  12692. // checkType('Fraction', 'videoCapsDict.framerate', videoCapsDict.framerate, {required: true});
  12693. //
  12694. // Init parent class
  12695. VideoCaps.super_.call(this, videoCapsDict)
  12696. // Set object properties
  12697. Object.defineProperties(this, {
  12698. codec: {
  12699. writable: true,
  12700. enumerable: true,
  12701. value: videoCapsDict.codec
  12702. },
  12703. framerate: {
  12704. writable: true,
  12705. enumerable: true,
  12706. value: videoCapsDict.framerate
  12707. }
  12708. })
  12709. }
  12710. inherits(VideoCaps, ComplexType)
  12711. // Private identifiers to allow re-construction of the complexType on the server
  12712. // They need to be enumerable so JSON.stringify() can access to them
  12713. Object.defineProperties(VideoCaps.prototype, {
  12714. __module__: {
  12715. enumerable: true,
  12716. value: "kurento"
  12717. },
  12718. __type__: {
  12719. enumerable: true,
  12720. value: "VideoCaps"
  12721. }
  12722. })
  12723. /**
  12724. * Checker for {@link module:core/complexTypes.VideoCaps}
  12725. *
  12726. * @memberof module:core/complexTypes
  12727. *
  12728. * @param {external:String} key
  12729. * @param {module:core/complexTypes.VideoCaps} value
  12730. */
  12731. function checkVideoCaps(key, value)
  12732. {
  12733. if(!(value instanceof VideoCaps))
  12734. throw ChecktypeError(key, VideoCaps, value);
  12735. };
  12736. module.exports = VideoCaps;
  12737. VideoCaps.check = checkVideoCaps;
  12738. },{"./ComplexType":44,"inherits":"inherits","kurento-client":"kurento-client"}],82:[function(require,module,exports){
  12739. /* Autogenerated with Kurento Idl */
  12740. /*
  12741. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  12742. *
  12743. * Licensed under the Apache License, Version 2.0 (the "License");
  12744. * you may not use this file except in compliance with the License.
  12745. * You may obtain a copy of the License at
  12746. *
  12747. * http://www.apache.org/licenses/LICENSE-2.0
  12748. *
  12749. * Unless required by applicable law or agreed to in writing, software
  12750. * distributed under the License is distributed on an "AS IS" BASIS,
  12751. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12752. * See the License for the specific language governing permissions and
  12753. * limitations under the License.
  12754. */
  12755. var kurentoClient = require('kurento-client');
  12756. /**
  12757. * Codec used for transmission of video.
  12758. *
  12759. * @typedef core/complexTypes.VideoCodec
  12760. *
  12761. * @type {(VP8|H264|RAW)}
  12762. */
  12763. /**
  12764. * Checker for {@link module:core/complexTypes.VideoCodec}
  12765. *
  12766. * @memberof module:core/complexTypes
  12767. *
  12768. * @param {external:String} key
  12769. * @param {module:core/complexTypes.VideoCodec} value
  12770. */
  12771. function checkVideoCodec(key, value)
  12772. {
  12773. if(typeof value != 'string')
  12774. throw SyntaxError(key+' param should be a String, not '+typeof value);
  12775. if(!value.match('VP8|H264|RAW'))
  12776. throw SyntaxError(key+' param is not one of [VP8|H264|RAW] ('+value+')');
  12777. };
  12778. module.exports = checkVideoCodec;
  12779. },{"kurento-client":"kurento-client"}],83:[function(require,module,exports){
  12780. /* Autogenerated with Kurento Idl */
  12781. /*
  12782. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  12783. *
  12784. * Licensed under the Apache License, Version 2.0 (the "License");
  12785. * you may not use this file except in compliance with the License.
  12786. * You may obtain a copy of the License at
  12787. *
  12788. * http://www.apache.org/licenses/LICENSE-2.0
  12789. *
  12790. * Unless required by applicable law or agreed to in writing, software
  12791. * distributed under the License is distributed on an "AS IS" BASIS,
  12792. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12793. * See the License for the specific language governing permissions and
  12794. * limitations under the License.
  12795. */
  12796. /**
  12797. * Media API for the Kurento Web SDK
  12798. *
  12799. * @module core/complexTypes
  12800. *
  12801. * @copyright 2013-2015 Kurento (http://kurento.org/)
  12802. * @license ALv2
  12803. */
  12804. var ComplexType = require('./ComplexType');
  12805. var AudioCaps = require('./AudioCaps');
  12806. var AudioCodec = require('./AudioCodec');
  12807. var CodecConfiguration = require('./CodecConfiguration');
  12808. var ConnectionState = require('./ConnectionState');
  12809. var ElementConnectionData = require('./ElementConnectionData');
  12810. var ElementStats = require('./ElementStats');
  12811. var EndpointStats = require('./EndpointStats');
  12812. var FilterType = require('./FilterType');
  12813. var Fraction = require('./Fraction');
  12814. var GstreamerDotDetails = require('./GstreamerDotDetails');
  12815. var MediaFlowState = require('./MediaFlowState');
  12816. var MediaLatencyStat = require('./MediaLatencyStat');
  12817. var MediaState = require('./MediaState');
  12818. var MediaTranscodingState = require('./MediaTranscodingState');
  12819. var MediaType = require('./MediaType');
  12820. var ModuleInfo = require('./ModuleInfo');
  12821. var RembParams = require('./RembParams');
  12822. var RTCCertificateStats = require('./RTCCertificateStats');
  12823. var RTCCodec = require('./RTCCodec');
  12824. var RTCDataChannelState = require('./RTCDataChannelState');
  12825. var RTCDataChannelStats = require('./RTCDataChannelStats');
  12826. var RTCIceCandidateAttributes = require('./RTCIceCandidateAttributes');
  12827. var RTCIceCandidatePairStats = require('./RTCIceCandidatePairStats');
  12828. var RTCInboundRTPStreamStats = require('./RTCInboundRTPStreamStats');
  12829. var RTCMediaStreamStats = require('./RTCMediaStreamStats');
  12830. var RTCMediaStreamTrackStats = require('./RTCMediaStreamTrackStats');
  12831. var RTCOutboundRTPStreamStats = require('./RTCOutboundRTPStreamStats');
  12832. var RTCPeerConnectionStats = require('./RTCPeerConnectionStats');
  12833. var RTCRTPStreamStats = require('./RTCRTPStreamStats');
  12834. var RTCStats = require('./RTCStats');
  12835. var RTCStatsIceCandidatePairState = require('./RTCStatsIceCandidatePairState');
  12836. var RTCStatsIceCandidateType = require('./RTCStatsIceCandidateType');
  12837. var RTCTransportStats = require('./RTCTransportStats');
  12838. var ServerInfo = require('./ServerInfo');
  12839. var ServerType = require('./ServerType');
  12840. var Stats = require('./Stats');
  12841. var StatsType = require('./StatsType');
  12842. var Tag = require('./Tag');
  12843. var UriEndpointState = require('./UriEndpointState');
  12844. var VideoCaps = require('./VideoCaps');
  12845. var VideoCodec = require('./VideoCodec');
  12846. exports.ComplexType = ComplexType;
  12847. exports.AudioCaps = AudioCaps;
  12848. exports.AudioCodec = AudioCodec;
  12849. exports.CodecConfiguration = CodecConfiguration;
  12850. exports.ConnectionState = ConnectionState;
  12851. exports.ElementConnectionData = ElementConnectionData;
  12852. exports.ElementStats = ElementStats;
  12853. exports.EndpointStats = EndpointStats;
  12854. exports.FilterType = FilterType;
  12855. exports.Fraction = Fraction;
  12856. exports.GstreamerDotDetails = GstreamerDotDetails;
  12857. exports.MediaFlowState = MediaFlowState;
  12858. exports.MediaLatencyStat = MediaLatencyStat;
  12859. exports.MediaState = MediaState;
  12860. exports.MediaTranscodingState = MediaTranscodingState;
  12861. exports.MediaType = MediaType;
  12862. exports.ModuleInfo = ModuleInfo;
  12863. exports.RembParams = RembParams;
  12864. exports.RTCCertificateStats = RTCCertificateStats;
  12865. exports.RTCCodec = RTCCodec;
  12866. exports.RTCDataChannelState = RTCDataChannelState;
  12867. exports.RTCDataChannelStats = RTCDataChannelStats;
  12868. exports.RTCIceCandidateAttributes = RTCIceCandidateAttributes;
  12869. exports.RTCIceCandidatePairStats = RTCIceCandidatePairStats;
  12870. exports.RTCInboundRTPStreamStats = RTCInboundRTPStreamStats;
  12871. exports.RTCMediaStreamStats = RTCMediaStreamStats;
  12872. exports.RTCMediaStreamTrackStats = RTCMediaStreamTrackStats;
  12873. exports.RTCOutboundRTPStreamStats = RTCOutboundRTPStreamStats;
  12874. exports.RTCPeerConnectionStats = RTCPeerConnectionStats;
  12875. exports.RTCRTPStreamStats = RTCRTPStreamStats;
  12876. exports.RTCStats = RTCStats;
  12877. exports.RTCStatsIceCandidatePairState = RTCStatsIceCandidatePairState;
  12878. exports.RTCStatsIceCandidateType = RTCStatsIceCandidateType;
  12879. exports.RTCTransportStats = RTCTransportStats;
  12880. exports.ServerInfo = ServerInfo;
  12881. exports.ServerType = ServerType;
  12882. exports.Stats = Stats;
  12883. exports.StatsType = StatsType;
  12884. exports.Tag = Tag;
  12885. exports.UriEndpointState = UriEndpointState;
  12886. exports.VideoCaps = VideoCaps;
  12887. exports.VideoCodec = VideoCodec;
  12888. },{"./AudioCaps":41,"./AudioCodec":42,"./CodecConfiguration":43,"./ComplexType":44,"./ConnectionState":45,"./ElementConnectionData":46,"./ElementStats":47,"./EndpointStats":48,"./FilterType":49,"./Fraction":50,"./GstreamerDotDetails":51,"./MediaFlowState":52,"./MediaLatencyStat":53,"./MediaState":54,"./MediaTranscodingState":55,"./MediaType":56,"./ModuleInfo":57,"./RTCCertificateStats":58,"./RTCCodec":59,"./RTCDataChannelState":60,"./RTCDataChannelStats":61,"./RTCIceCandidateAttributes":62,"./RTCIceCandidatePairStats":63,"./RTCInboundRTPStreamStats":64,"./RTCMediaStreamStats":65,"./RTCMediaStreamTrackStats":66,"./RTCOutboundRTPStreamStats":67,"./RTCPeerConnectionStats":68,"./RTCRTPStreamStats":69,"./RTCStats":70,"./RTCStatsIceCandidatePairState":71,"./RTCStatsIceCandidateType":72,"./RTCTransportStats":73,"./RembParams":74,"./ServerInfo":75,"./ServerType":76,"./Stats":77,"./StatsType":78,"./Tag":79,"./UriEndpointState":80,"./VideoCaps":81,"./VideoCodec":82}],84:[function(require,module,exports){
  12889. /* Autogenerated with Kurento Idl */
  12890. /*
  12891. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  12892. *
  12893. * Licensed under the Apache License, Version 2.0 (the "License");
  12894. * you may not use this file except in compliance with the License.
  12895. * You may obtain a copy of the License at
  12896. *
  12897. * http://www.apache.org/licenses/LICENSE-2.0
  12898. *
  12899. * Unless required by applicable law or agreed to in writing, software
  12900. * distributed under the License is distributed on an "AS IS" BASIS,
  12901. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12902. * See the License for the specific language governing permissions and
  12903. * limitations under the License.
  12904. */
  12905. var inherits = require('inherits');
  12906. var kurentoClient = require('kurento-client');
  12907. var disguise = kurentoClient.disguise;
  12908. var checkType = kurentoClient.checkType;
  12909. var ChecktypeError = checkType.ChecktypeError;
  12910. var Transaction = kurentoClient.TransactionsManager.Transaction;
  12911. var Hub = require('kurento-client-core').abstracts.Hub;
  12912. function noop(error, result) {
  12913. if (error) console.trace(error);
  12914. return result
  12915. };
  12916. /**
  12917. * Create for the given pipeline
  12918. *
  12919. * @classdesc
  12920. * A {@link module:core/abstracts.Hub Hub} that mixes the {@link
  12921. * module:elements.AlphaBlending#MediaType.AUDIO} stream of its connected
  12922. * sources and constructs one output with {@link
  12923. * module:elements.AlphaBlending#MediaType.VIDEO} streams of its connected
  12924. * sources into its sink
  12925. *
  12926. * @extends module:core/abstracts.Hub
  12927. *
  12928. * @constructor module:elements.AlphaBlending
  12929. */
  12930. function AlphaBlending(){
  12931. AlphaBlending.super_.call(this);
  12932. };
  12933. inherits(AlphaBlending, Hub);
  12934. //
  12935. // Public methods
  12936. //
  12937. /**
  12938. * Sets the source port that will be the master entry to the mixer
  12939. *
  12940. * @alias module:elements.AlphaBlending.setMaster
  12941. *
  12942. * @param {module:core.HubPort} source
  12943. * The reference to the HubPort setting as master port
  12944. *
  12945. * @param {external:Integer} zOrder
  12946. * The order in z to draw the master image
  12947. *
  12948. * @param {module:elements.AlphaBlending~setMasterCallback} [callback]
  12949. *
  12950. * @return {external:Promise}
  12951. */
  12952. AlphaBlending.prototype.setMaster = function(source, zOrder, callback){
  12953. var transaction = (arguments[0] instanceof Transaction)
  12954. ? Array.prototype.shift.apply(arguments)
  12955. : undefined;
  12956. //
  12957. // checkType('HubPort', 'source', source, {required: true});
  12958. //
  12959. // checkType('int', 'zOrder', zOrder, {required: true});
  12960. //
  12961. var params = {
  12962. source: source,
  12963. zOrder: zOrder
  12964. };
  12965. callback = (callback || noop).bind(this)
  12966. return disguise(this._invoke(transaction, 'setMaster', params, callback), this)
  12967. };
  12968. /**
  12969. * @callback module:elements.AlphaBlending~setMasterCallback
  12970. * @param {external:Error} error
  12971. */
  12972. /**
  12973. * Configure the blending mode of one port.
  12974. *
  12975. * @alias module:elements.AlphaBlending.setPortProperties
  12976. *
  12977. * @param {external:Number} relativeX
  12978. * The x position relative to the master port. Values from 0 to 1 are accepted.
  12979. *
  12980. * @param {external:Number} relativeY
  12981. * The y position relative to the master port. Values from 0 to 1 are accepted.
  12982. *
  12983. * @param {external:Integer} zOrder
  12984. * The order in z to draw the images. The greatest value of z is in the top.
  12985. *
  12986. * @param {external:Number} relativeWidth
  12987. * The image width relative to the master port width. Values from 0 to 1 are
  12988. * accepted.
  12989. *
  12990. * @param {external:Number} relativeHeight
  12991. * The image height relative to the master port height. Values from 0 to 1 are
  12992. * accepted.
  12993. *
  12994. * @param {module:core.HubPort} port
  12995. * The reference to the confingured port.
  12996. *
  12997. * @param {module:elements.AlphaBlending~setPortPropertiesCallback} [callback]
  12998. *
  12999. * @return {external:Promise}
  13000. */
  13001. AlphaBlending.prototype.setPortProperties = function(relativeX, relativeY, zOrder, relativeWidth, relativeHeight, port, callback){
  13002. var transaction = (arguments[0] instanceof Transaction)
  13003. ? Array.prototype.shift.apply(arguments)
  13004. : undefined;
  13005. //
  13006. // checkType('float', 'relativeX', relativeX, {required: true});
  13007. //
  13008. // checkType('float', 'relativeY', relativeY, {required: true});
  13009. //
  13010. // checkType('int', 'zOrder', zOrder, {required: true});
  13011. //
  13012. // checkType('float', 'relativeWidth', relativeWidth, {required: true});
  13013. //
  13014. // checkType('float', 'relativeHeight', relativeHeight, {required: true});
  13015. //
  13016. // checkType('HubPort', 'port', port, {required: true});
  13017. //
  13018. var params = {
  13019. relativeX: relativeX,
  13020. relativeY: relativeY,
  13021. zOrder: zOrder,
  13022. relativeWidth: relativeWidth,
  13023. relativeHeight: relativeHeight,
  13024. port: port
  13025. };
  13026. callback = (callback || noop).bind(this)
  13027. return disguise(this._invoke(transaction, 'setPortProperties', params, callback), this)
  13028. };
  13029. /**
  13030. * @callback module:elements.AlphaBlending~setPortPropertiesCallback
  13031. * @param {external:Error} error
  13032. */
  13033. /**
  13034. * @alias module:elements.AlphaBlending.constructorParams
  13035. *
  13036. * @property {module:core.MediaPipeline} mediaPipeline
  13037. * the {@link module:core.MediaPipeline MediaPipeline} to which the dispatcher
  13038. * belongs
  13039. */
  13040. AlphaBlending.constructorParams = {
  13041. mediaPipeline: {
  13042. type: 'kurento.MediaPipeline',
  13043. required: true
  13044. }
  13045. };
  13046. /**
  13047. * @alias module:elements.AlphaBlending.events
  13048. *
  13049. * @extends module:core/abstracts.Hub.events
  13050. */
  13051. AlphaBlending.events = Hub.events;
  13052. /**
  13053. * Checker for {@link module:elements.AlphaBlending}
  13054. *
  13055. * @memberof module:elements
  13056. *
  13057. * @param {external:String} key
  13058. * @param {module:elements.AlphaBlending} value
  13059. */
  13060. function checkAlphaBlending(key, value)
  13061. {
  13062. if(!(value instanceof AlphaBlending))
  13063. throw ChecktypeError(key, AlphaBlending, value);
  13064. };
  13065. module.exports = AlphaBlending;
  13066. AlphaBlending.check = checkAlphaBlending;
  13067. },{"inherits":"inherits","kurento-client":"kurento-client","kurento-client-core":"kurento-client-core"}],85:[function(require,module,exports){
  13068. /* Autogenerated with Kurento Idl */
  13069. /*
  13070. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  13071. *
  13072. * Licensed under the Apache License, Version 2.0 (the "License");
  13073. * you may not use this file except in compliance with the License.
  13074. * You may obtain a copy of the License at
  13075. *
  13076. * http://www.apache.org/licenses/LICENSE-2.0
  13077. *
  13078. * Unless required by applicable law or agreed to in writing, software
  13079. * distributed under the License is distributed on an "AS IS" BASIS,
  13080. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13081. * See the License for the specific language governing permissions and
  13082. * limitations under the License.
  13083. */
  13084. var inherits = require('inherits');
  13085. var kurentoClient = require('kurento-client');
  13086. var disguise = kurentoClient.disguise;
  13087. var ChecktypeError = kurentoClient.checkType.ChecktypeError;
  13088. var Hub = require('kurento-client-core').abstracts.Hub;
  13089. /**
  13090. * Create for the given pipeline
  13091. *
  13092. * @classdesc
  13093. * A {@link module:core/abstracts.Hub Hub} that mixes the {@link
  13094. * module:elements.Composite#MediaType.AUDIO} stream of its connected sources
  13095. * and constructs a grid with the {@link
  13096. * module:elements.Composite#MediaType.VIDEO} streams of its connected sources
  13097. * into its sink
  13098. *
  13099. * @extends module:core/abstracts.Hub
  13100. *
  13101. * @constructor module:elements.Composite
  13102. */
  13103. function Composite(){
  13104. Composite.super_.call(this);
  13105. };
  13106. inherits(Composite, Hub);
  13107. /**
  13108. * @alias module:elements.Composite.constructorParams
  13109. *
  13110. * @property {module:core.MediaPipeline} mediaPipeline
  13111. * the {@link module:core.MediaPipeline MediaPipeline} to which the dispatcher
  13112. * belongs
  13113. */
  13114. Composite.constructorParams = {
  13115. mediaPipeline: {
  13116. type: 'kurento.MediaPipeline',
  13117. required: true
  13118. }
  13119. };
  13120. /**
  13121. * @alias module:elements.Composite.events
  13122. *
  13123. * @extends module:core/abstracts.Hub.events
  13124. */
  13125. Composite.events = Hub.events;
  13126. /**
  13127. * Checker for {@link module:elements.Composite}
  13128. *
  13129. * @memberof module:elements
  13130. *
  13131. * @param {external:String} key
  13132. * @param {module:elements.Composite} value
  13133. */
  13134. function checkComposite(key, value)
  13135. {
  13136. if(!(value instanceof Composite))
  13137. throw ChecktypeError(key, Composite, value);
  13138. };
  13139. module.exports = Composite;
  13140. Composite.check = checkComposite;
  13141. },{"inherits":"inherits","kurento-client":"kurento-client","kurento-client-core":"kurento-client-core"}],86:[function(require,module,exports){
  13142. /* Autogenerated with Kurento Idl */
  13143. /*
  13144. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  13145. *
  13146. * Licensed under the Apache License, Version 2.0 (the "License");
  13147. * you may not use this file except in compliance with the License.
  13148. * You may obtain a copy of the License at
  13149. *
  13150. * http://www.apache.org/licenses/LICENSE-2.0
  13151. *
  13152. * Unless required by applicable law or agreed to in writing, software
  13153. * distributed under the License is distributed on an "AS IS" BASIS,
  13154. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13155. * See the License for the specific language governing permissions and
  13156. * limitations under the License.
  13157. */
  13158. var inherits = require('inherits');
  13159. var kurentoClient = require('kurento-client');
  13160. var disguise = kurentoClient.disguise;
  13161. var checkType = kurentoClient.checkType;
  13162. var ChecktypeError = checkType.ChecktypeError;
  13163. var Transaction = kurentoClient.TransactionsManager.Transaction;
  13164. var Hub = require('kurento-client-core').abstracts.Hub;
  13165. function noop(error, result) {
  13166. if (error) console.trace(error);
  13167. return result
  13168. };
  13169. /**
  13170. * Create a {@link module:elements.Dispatcher Dispatcher} belonging to the given
  13171. *
  13172. * @classdesc
  13173. * A {@link module:core/abstracts.Hub Hub} that allows routing between
  13174. * arbitrary port pairs
  13175. *
  13176. * @extends module:core/abstracts.Hub
  13177. *
  13178. * @constructor module:elements.Dispatcher
  13179. */
  13180. function Dispatcher(){
  13181. Dispatcher.super_.call(this);
  13182. };
  13183. inherits(Dispatcher, Hub);
  13184. //
  13185. // Public methods
  13186. //
  13187. /**
  13188. * Connects each corresponding {@link MediaType} of the given source port with
  13189. * the sink port.
  13190. *
  13191. * @alias module:elements.Dispatcher.connect
  13192. *
  13193. * @param {module:core.HubPort} source
  13194. * Source port to be connected
  13195. *
  13196. * @param {module:core.HubPort} sink
  13197. * Sink port to be connected
  13198. *
  13199. * @param {module:elements.Dispatcher~connectCallback} [callback]
  13200. *
  13201. * @return {external:Promise}
  13202. */
  13203. Dispatcher.prototype.connect = function(source, sink, callback){
  13204. var transaction = (arguments[0] instanceof Transaction)
  13205. ? Array.prototype.shift.apply(arguments)
  13206. : undefined;
  13207. //
  13208. // checkType('HubPort', 'source', source, {required: true});
  13209. //
  13210. // checkType('HubPort', 'sink', sink, {required: true});
  13211. //
  13212. var params = {
  13213. source: source,
  13214. sink: sink
  13215. };
  13216. callback = (callback || noop).bind(this)
  13217. return disguise(this._invoke(transaction, 'connect', params, callback), this)
  13218. };
  13219. /**
  13220. * @callback module:elements.Dispatcher~connectCallback
  13221. * @param {external:Error} error
  13222. */
  13223. /**
  13224. * @alias module:elements.Dispatcher.constructorParams
  13225. *
  13226. * @property {module:core.MediaPipeline} mediaPipeline
  13227. * the {@link module:core.MediaPipeline MediaPipeline} to which the dispatcher
  13228. * belongs
  13229. */
  13230. Dispatcher.constructorParams = {
  13231. mediaPipeline: {
  13232. type: 'kurento.MediaPipeline',
  13233. required: true
  13234. }
  13235. };
  13236. /**
  13237. * @alias module:elements.Dispatcher.events
  13238. *
  13239. * @extends module:core/abstracts.Hub.events
  13240. */
  13241. Dispatcher.events = Hub.events;
  13242. /**
  13243. * Checker for {@link module:elements.Dispatcher}
  13244. *
  13245. * @memberof module:elements
  13246. *
  13247. * @param {external:String} key
  13248. * @param {module:elements.Dispatcher} value
  13249. */
  13250. function checkDispatcher(key, value)
  13251. {
  13252. if(!(value instanceof Dispatcher))
  13253. throw ChecktypeError(key, Dispatcher, value);
  13254. };
  13255. module.exports = Dispatcher;
  13256. Dispatcher.check = checkDispatcher;
  13257. },{"inherits":"inherits","kurento-client":"kurento-client","kurento-client-core":"kurento-client-core"}],87:[function(require,module,exports){
  13258. /* Autogenerated with Kurento Idl */
  13259. /*
  13260. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  13261. *
  13262. * Licensed under the Apache License, Version 2.0 (the "License");
  13263. * you may not use this file except in compliance with the License.
  13264. * You may obtain a copy of the License at
  13265. *
  13266. * http://www.apache.org/licenses/LICENSE-2.0
  13267. *
  13268. * Unless required by applicable law or agreed to in writing, software
  13269. * distributed under the License is distributed on an "AS IS" BASIS,
  13270. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13271. * See the License for the specific language governing permissions and
  13272. * limitations under the License.
  13273. */
  13274. var inherits = require('inherits');
  13275. var kurentoClient = require('kurento-client');
  13276. var disguise = kurentoClient.disguise;
  13277. var checkType = kurentoClient.checkType;
  13278. var ChecktypeError = checkType.ChecktypeError;
  13279. var Transaction = kurentoClient.TransactionsManager.Transaction;
  13280. var Hub = require('kurento-client-core').abstracts.Hub;
  13281. function noop(error, result) {
  13282. if (error) console.trace(error);
  13283. return result
  13284. };
  13285. /**
  13286. * Create a {@link module:elements.DispatcherOneToMany DispatcherOneToMany}
  13287. * belonging to the given pipeline.
  13288. *
  13289. * @classdesc
  13290. * A {@link module:core/abstracts.Hub Hub} that sends a given source to all the
  13291. *
  13292. * @extends module:core/abstracts.Hub
  13293. *
  13294. * @constructor module:elements.DispatcherOneToMany
  13295. */
  13296. function DispatcherOneToMany(){
  13297. DispatcherOneToMany.super_.call(this);
  13298. };
  13299. inherits(DispatcherOneToMany, Hub);
  13300. //
  13301. // Public methods
  13302. //
  13303. /**
  13304. * Remove the source port and stop the media pipeline.
  13305. *
  13306. * @alias module:elements.DispatcherOneToMany.removeSource
  13307. *
  13308. * @param {module:elements.DispatcherOneToMany~removeSourceCallback} [callback]
  13309. *
  13310. * @return {external:Promise}
  13311. */
  13312. DispatcherOneToMany.prototype.removeSource = function(callback){
  13313. var transaction = (arguments[0] instanceof Transaction)
  13314. ? Array.prototype.shift.apply(arguments)
  13315. : undefined;
  13316. var usePromise = false;
  13317. if (callback == undefined) {
  13318. usePromise = true;
  13319. }
  13320. if(!arguments.length) callback = undefined;
  13321. callback = (callback || noop).bind(this)
  13322. return disguise(this._invoke(transaction, 'removeSource', callback), this)
  13323. };
  13324. /**
  13325. * @callback module:elements.DispatcherOneToMany~removeSourceCallback
  13326. * @param {external:Error} error
  13327. */
  13328. /**
  13329. * Sets the source port that will be connected to the sinks of every {@link
  13330. * module:core.HubPort HubPort} of the dispatcher
  13331. *
  13332. * @alias module:elements.DispatcherOneToMany.setSource
  13333. *
  13334. * @param {module:core.HubPort} source
  13335. * source to be broadcasted
  13336. *
  13337. * @param {module:elements.DispatcherOneToMany~setSourceCallback} [callback]
  13338. *
  13339. * @return {external:Promise}
  13340. */
  13341. DispatcherOneToMany.prototype.setSource = function(source, callback){
  13342. var transaction = (arguments[0] instanceof Transaction)
  13343. ? Array.prototype.shift.apply(arguments)
  13344. : undefined;
  13345. //
  13346. // checkType('HubPort', 'source', source, {required: true});
  13347. //
  13348. var params = {
  13349. source: source
  13350. };
  13351. callback = (callback || noop).bind(this)
  13352. return disguise(this._invoke(transaction, 'setSource', params, callback), this)
  13353. };
  13354. /**
  13355. * @callback module:elements.DispatcherOneToMany~setSourceCallback
  13356. * @param {external:Error} error
  13357. */
  13358. /**
  13359. * @alias module:elements.DispatcherOneToMany.constructorParams
  13360. *
  13361. * @property {module:core.MediaPipeline} mediaPipeline
  13362. * the {@link module:core.MediaPipeline MediaPipeline} to which the dispatcher
  13363. * belongs
  13364. */
  13365. DispatcherOneToMany.constructorParams = {
  13366. mediaPipeline: {
  13367. type: 'kurento.MediaPipeline',
  13368. required: true
  13369. }
  13370. };
  13371. /**
  13372. * @alias module:elements.DispatcherOneToMany.events
  13373. *
  13374. * @extends module:core/abstracts.Hub.events
  13375. */
  13376. DispatcherOneToMany.events = Hub.events;
  13377. /**
  13378. * Checker for {@link module:elements.DispatcherOneToMany}
  13379. *
  13380. * @memberof module:elements
  13381. *
  13382. * @param {external:String} key
  13383. * @param {module:elements.DispatcherOneToMany} value
  13384. */
  13385. function checkDispatcherOneToMany(key, value)
  13386. {
  13387. if(!(value instanceof DispatcherOneToMany))
  13388. throw ChecktypeError(key, DispatcherOneToMany, value);
  13389. };
  13390. module.exports = DispatcherOneToMany;
  13391. DispatcherOneToMany.check = checkDispatcherOneToMany;
  13392. },{"inherits":"inherits","kurento-client":"kurento-client","kurento-client-core":"kurento-client-core"}],88:[function(require,module,exports){
  13393. /* Autogenerated with Kurento Idl */
  13394. /*
  13395. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  13396. *
  13397. * Licensed under the Apache License, Version 2.0 (the "License");
  13398. * you may not use this file except in compliance with the License.
  13399. * You may obtain a copy of the License at
  13400. *
  13401. * http://www.apache.org/licenses/LICENSE-2.0
  13402. *
  13403. * Unless required by applicable law or agreed to in writing, software
  13404. * distributed under the License is distributed on an "AS IS" BASIS,
  13405. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13406. * See the License for the specific language governing permissions and
  13407. * limitations under the License.
  13408. */
  13409. var inherits = require('inherits');
  13410. var kurentoClient = require('kurento-client');
  13411. var disguise = kurentoClient.disguise;
  13412. var ChecktypeError = kurentoClient.checkType.ChecktypeError;
  13413. var HttpEndpoint = require('./abstracts/HttpEndpoint');
  13414. /**
  13415. * Builder for the {@link module:elements.HttpPostEndpoint HttpPostEndpoint}.
  13416. *
  13417. * @classdesc
  13418. * An {@link module:elements.HttpPostEndpoint HttpPostEndpoint} contains SINK
  13419. * pads for AUDIO and VIDEO, which provide access to an HTTP file upload
  13420. * function
  13421. * This type of endpoint provide unidirectional communications. Its
  13422. * :rom:cls:`MediaSources <MediaSource>` are accessed through the <a
  13423. * href="http://www.kurento.org/docs/current/glossary.html#term-http">HTTP</a>
  13424. *
  13425. * @extends module:elements/abstracts.HttpEndpoint
  13426. *
  13427. * @constructor module:elements.HttpPostEndpoint
  13428. *
  13429. * @fires {@link module:elements#event:EndOfStream EndOfStream}
  13430. */
  13431. function HttpPostEndpoint(){
  13432. HttpPostEndpoint.super_.call(this);
  13433. };
  13434. inherits(HttpPostEndpoint, HttpEndpoint);
  13435. /**
  13436. * @alias module:elements.HttpPostEndpoint.constructorParams
  13437. *
  13438. * @property {external:Integer} [disconnectionTimeout]
  13439. * This is the time that an http endpoint will wait for a reconnection, in case
  13440. *
  13441. * @property {module:core.MediaPipeline} mediaPipeline
  13442. * the {@link module:core.MediaPipeline MediaPipeline} to which the endpoint
  13443. * belongs
  13444. *
  13445. * @property {external:Boolean} [useEncodedMedia]
  13446. * Feed the input media as-is to the Media Pipeline, instead of first decoding
  13447. * it.
  13448. * <p>
  13449. * When this property is not enabled, the input media gets always
  13450. * </p>
  13451. * <p>
  13452. * When this property is enabled, the explained behavior gets
  13453. * disabled. Instead, The endpoint will provide any input media
  13454. * directly to the Media Pipeline, without prior decoding.
  13455. * Enabling this mode of operation could have a severe effect on
  13456. * stability, because lost video keyframes will not be
  13457. * regenerated; however, avoiding a full cycle of decoding and
  13458. * encoding can be very useful for certain applications, because
  13459. * it improves performance by greatly reducing the CPU processing
  13460. * </p>
  13461. * <p>
  13462. * Keep in mind that if this property is enabled, the original
  13463. * source media MUST already have an encoding format which is
  13464. * compatible with the destination target. For example: given a
  13465. * pipeline which uses this endpoint to read a file and then
  13466. * streams it to a WebRTC browser such as Chrome, then the file
  13467. * must already be encoded with a VP8 or H.264 codec profile
  13468. * which Chrome is able to decode. Note that for this example,
  13469. * most browsers don't support ANY combination of H.264 encoding
  13470. * options; instead, they tend to support only a very specific
  13471. * subset of the codec features (also known as 'profiles').
  13472. * </p>
  13473. * <p>
  13474. * We strongly recommend to avoid using this option, because
  13475. * correct behavior cannot be guaranteed.
  13476. * </p>
  13477. */
  13478. HttpPostEndpoint.constructorParams = {
  13479. disconnectionTimeout: {
  13480. type: 'int' },
  13481. mediaPipeline: {
  13482. type: 'kurento.MediaPipeline',
  13483. required: true
  13484. },
  13485. useEncodedMedia: {
  13486. type: 'boolean' }
  13487. };
  13488. /**
  13489. * @alias module:elements.HttpPostEndpoint.events
  13490. *
  13491. * @extends module:elements/abstracts.HttpEndpoint.events
  13492. */
  13493. HttpPostEndpoint.events = HttpEndpoint.events.concat(['EndOfStream']);
  13494. /**
  13495. * Checker for {@link module:elements.HttpPostEndpoint}
  13496. *
  13497. * @memberof module:elements
  13498. *
  13499. * @param {external:String} key
  13500. * @param {module:elements.HttpPostEndpoint} value
  13501. */
  13502. function checkHttpPostEndpoint(key, value)
  13503. {
  13504. if(!(value instanceof HttpPostEndpoint))
  13505. throw ChecktypeError(key, HttpPostEndpoint, value);
  13506. };
  13507. module.exports = HttpPostEndpoint;
  13508. HttpPostEndpoint.check = checkHttpPostEndpoint;
  13509. },{"./abstracts/HttpEndpoint":94,"inherits":"inherits","kurento-client":"kurento-client"}],89:[function(require,module,exports){
  13510. /* Autogenerated with Kurento Idl */
  13511. /*
  13512. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  13513. *
  13514. * Licensed under the Apache License, Version 2.0 (the "License");
  13515. * you may not use this file except in compliance with the License.
  13516. * You may obtain a copy of the License at
  13517. *
  13518. * http://www.apache.org/licenses/LICENSE-2.0
  13519. *
  13520. * Unless required by applicable law or agreed to in writing, software
  13521. * distributed under the License is distributed on an "AS IS" BASIS,
  13522. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13523. * See the License for the specific language governing permissions and
  13524. * limitations under the License.
  13525. */
  13526. var inherits = require('inherits');
  13527. var kurentoClient = require('kurento-client');
  13528. var disguise = kurentoClient.disguise;
  13529. var checkType = kurentoClient.checkType;
  13530. var ChecktypeError = checkType.ChecktypeError;
  13531. var Transaction = kurentoClient.TransactionsManager.Transaction;
  13532. var Hub = require('kurento-client-core').abstracts.Hub;
  13533. function noop(error, result) {
  13534. if (error) console.trace(error);
  13535. return result
  13536. };
  13537. /**
  13538. * Create a {@link module:elements.Mixer Mixer} belonging to the given pipeline.
  13539. *
  13540. * @classdesc
  13541. * A {@link module:core/abstracts.Hub Hub} that allows routing of video between
  13542. *
  13543. * @extends module:core/abstracts.Hub
  13544. *
  13545. * @constructor module:elements.Mixer
  13546. */
  13547. function Mixer(){
  13548. Mixer.super_.call(this);
  13549. };
  13550. inherits(Mixer, Hub);
  13551. //
  13552. // Public methods
  13553. //
  13554. /**
  13555. * Connects each corresponding {@link MediaType} of the given source port with
  13556. * the sink port.
  13557. *
  13558. * @alias module:elements.Mixer.connect
  13559. *
  13560. * @param {external:MediaType} media
  13561. * The sort of media stream to be connected
  13562. *
  13563. * @param {module:core.HubPort} source
  13564. * Source port to be connected
  13565. *
  13566. * @param {module:core.HubPort} sink
  13567. * Sink port to be connected
  13568. *
  13569. * @param {module:elements.Mixer~connectCallback} [callback]
  13570. *
  13571. * @return {external:Promise}
  13572. */
  13573. Mixer.prototype.connect = function(media, source, sink, callback){
  13574. var transaction = (arguments[0] instanceof Transaction)
  13575. ? Array.prototype.shift.apply(arguments)
  13576. : undefined;
  13577. //
  13578. // checkType('MediaType', 'media', media, {required: true});
  13579. //
  13580. // checkType('HubPort', 'source', source, {required: true});
  13581. //
  13582. // checkType('HubPort', 'sink', sink, {required: true});
  13583. //
  13584. var params = {
  13585. media: media,
  13586. source: source,
  13587. sink: sink
  13588. };
  13589. callback = (callback || noop).bind(this)
  13590. return disguise(this._invoke(transaction, 'connect', params, callback), this)
  13591. };
  13592. /**
  13593. * @callback module:elements.Mixer~connectCallback
  13594. * @param {external:Error} error
  13595. */
  13596. /**
  13597. * Disonnects each corresponding {@link MediaType} of the given source port from
  13598. *
  13599. * @alias module:elements.Mixer.disconnect
  13600. *
  13601. * @param {external:MediaType} media
  13602. * The sort of media stream to be disconnected
  13603. *
  13604. * @param {module:core.HubPort} source
  13605. * Audio source port to be disconnected
  13606. *
  13607. * @param {module:core.HubPort} sink
  13608. * Audio sink port to be disconnected
  13609. *
  13610. * @param {module:elements.Mixer~disconnectCallback} [callback]
  13611. *
  13612. * @return {external:Promise}
  13613. */
  13614. Mixer.prototype.disconnect = function(media, source, sink, callback){
  13615. var transaction = (arguments[0] instanceof Transaction)
  13616. ? Array.prototype.shift.apply(arguments)
  13617. : undefined;
  13618. //
  13619. // checkType('MediaType', 'media', media, {required: true});
  13620. //
  13621. // checkType('HubPort', 'source', source, {required: true});
  13622. //
  13623. // checkType('HubPort', 'sink', sink, {required: true});
  13624. //
  13625. var params = {
  13626. media: media,
  13627. source: source,
  13628. sink: sink
  13629. };
  13630. callback = (callback || noop).bind(this)
  13631. return disguise(this._invoke(transaction, 'disconnect', params, callback), this)
  13632. };
  13633. /**
  13634. * @callback module:elements.Mixer~disconnectCallback
  13635. * @param {external:Error} error
  13636. */
  13637. /**
  13638. * @alias module:elements.Mixer.constructorParams
  13639. *
  13640. * @property {module:core.MediaPipeline} mediaPipeline
  13641. * the {@link module:core.MediaPipeline MediaPipeline} to which the Mixer
  13642. * belongs
  13643. */
  13644. Mixer.constructorParams = {
  13645. mediaPipeline: {
  13646. type: 'kurento.MediaPipeline',
  13647. required: true
  13648. }
  13649. };
  13650. /**
  13651. * @alias module:elements.Mixer.events
  13652. *
  13653. * @extends module:core/abstracts.Hub.events
  13654. */
  13655. Mixer.events = Hub.events;
  13656. /**
  13657. * Checker for {@link module:elements.Mixer}
  13658. *
  13659. * @memberof module:elements
  13660. *
  13661. * @param {external:String} key
  13662. * @param {module:elements.Mixer} value
  13663. */
  13664. function checkMixer(key, value)
  13665. {
  13666. if(!(value instanceof Mixer))
  13667. throw ChecktypeError(key, Mixer, value);
  13668. };
  13669. module.exports = Mixer;
  13670. Mixer.check = checkMixer;
  13671. },{"inherits":"inherits","kurento-client":"kurento-client","kurento-client-core":"kurento-client-core"}],90:[function(require,module,exports){
  13672. /* Autogenerated with Kurento Idl */
  13673. /*
  13674. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  13675. *
  13676. * Licensed under the Apache License, Version 2.0 (the "License");
  13677. * you may not use this file except in compliance with the License.
  13678. * You may obtain a copy of the License at
  13679. *
  13680. * http://www.apache.org/licenses/LICENSE-2.0
  13681. *
  13682. * Unless required by applicable law or agreed to in writing, software
  13683. * distributed under the License is distributed on an "AS IS" BASIS,
  13684. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13685. * See the License for the specific language governing permissions and
  13686. * limitations under the License.
  13687. */
  13688. var inherits = require('inherits');
  13689. var kurentoClient = require('kurento-client');
  13690. var disguise = kurentoClient.disguise;
  13691. var checkType = kurentoClient.checkType;
  13692. var ChecktypeError = checkType.ChecktypeError;
  13693. var Transaction = kurentoClient.TransactionsManager.Transaction;
  13694. var UriEndpoint = require('kurento-client-core').abstracts.UriEndpoint;
  13695. function noop(error, result) {
  13696. if (error) console.trace(error);
  13697. return result
  13698. };
  13699. /**
  13700. * Create a PlayerEndpoint
  13701. *
  13702. * @classdesc
  13703. * <p>
  13704. * Retrieves content from seekable or non-seekable sources, and injects
  13705. * them into <a
  13706. * href="http://www.kurento.org/docs/current/glossary.html#term-kms">KMS</a>,
  13707. * <ul>
  13708. * <li>
  13709. * Files: Mounted in the local file system.
  13710. * <ul><li>file:///path/to/file</li></ul>
  13711. * </li>
  13712. * <li>
  13713. * RTSP: Those of IP cameras would be a good example.
  13714. * <ul>
  13715. * <li>rtsp://<server-ip></li>
  13716. * <li>rtsp://username:password@<server-ip></li>
  13717. * </ul>
  13718. * </li>
  13719. * <li>
  13720. * HTTP: Any file available in an HTTP server
  13721. * <ul>
  13722. * <li>http(s)://<server-ip>/path/to/file</li>
  13723. * <li>http(s)://username:password@<server-ip>/path/to/file</li>
  13724. * </ul>
  13725. * </li>
  13726. * </ul>
  13727. * </p>
  13728. * <p>
  13729. * For the player to stream the contents of the file, the server must
  13730. * have access to the resource. In case of local files, the user running
  13731. * the process must have read permissions over the file. For network
  13732. * resources, the path to the resource must be accessible: IP and port
  13733. * access not blocked, correct credentials, etc.The resource location
  13734. * can’t be changed after the player is created, and a new player should
  13735. * be created for streaming a different resource.
  13736. * </p>
  13737. * <p>
  13738. * The list of valid operations is
  13739. * <ul>
  13740. * <li>*play*: starts streaming media. If invoked after pause, it will
  13741. * resume playback.</li>
  13742. * <li>*stop*: stops streaming media. If play is invoked afterwards,
  13743. * the file will be streamed from the beginning.</li>
  13744. * <li>*pause*: pauses media streaming. Play must be invoked in order
  13745. * to resume playback.</li>
  13746. * <li>*seek*: If the source supports “jumps” in the timeline, then the
  13747. * <ul>
  13748. * <li>*setPosition*: allows to set the position in the file.</li>
  13749. * <li>*getPosition*: returns the current position being
  13750. * streamed.</li>
  13751. * </ul>
  13752. * </li>
  13753. * </ul>
  13754. * </p>
  13755. * <p>
  13756. * <h2>Events fired:</h2>
  13757. * <ul><li>EndOfStreamEvent: If the file is streamed
  13758. * completely.</li></ul>
  13759. * </p>
  13760. *
  13761. * @extends module:core/abstracts.UriEndpoint
  13762. *
  13763. * @constructor module:elements.PlayerEndpoint
  13764. *
  13765. * @fires {@link module:elements#event:EndOfStream EndOfStream}
  13766. */
  13767. function PlayerEndpoint(){
  13768. PlayerEndpoint.super_.call(this);
  13769. };
  13770. inherits(PlayerEndpoint, UriEndpoint);
  13771. //
  13772. // Public properties
  13773. //
  13774. /**
  13775. * Returns the GStreamer DOT string for this element's private pipeline
  13776. *
  13777. * @alias module:elements.PlayerEndpoint#getElementGstreamerDot
  13778. *
  13779. * @param {module:elements.PlayerEndpoint~getElementGstreamerDotCallback} [callback]
  13780. *
  13781. * @return {external:Promise}
  13782. */
  13783. PlayerEndpoint.prototype.getElementGstreamerDot = function(callback){
  13784. var transaction = (arguments[0] instanceof Transaction)
  13785. ? Array.prototype.shift.apply(arguments)
  13786. : undefined;
  13787. var usePromise = false;
  13788. if (callback == undefined) {
  13789. usePromise = true;
  13790. }
  13791. if(!arguments.length) callback = undefined;
  13792. callback = (callback || noop).bind(this)
  13793. return disguise(this._invoke(transaction, 'getElementGstreamerDot', callback), this)
  13794. };
  13795. /**
  13796. * @callback module:elements.PlayerEndpoint~getElementGstreamerDotCallback
  13797. * @param {external:Error} error
  13798. * @param {external:String} result
  13799. */
  13800. /**
  13801. * Get or set the actual position of the video in ms. <hr/><b>Note</b> Setting
  13802. * the position only works for seekable videos
  13803. *
  13804. * @alias module:elements.PlayerEndpoint#getPosition
  13805. *
  13806. * @param {module:elements.PlayerEndpoint~getPositionCallback} [callback]
  13807. *
  13808. * @return {external:Promise}
  13809. */
  13810. PlayerEndpoint.prototype.getPosition = function(callback){
  13811. var transaction = (arguments[0] instanceof Transaction)
  13812. ? Array.prototype.shift.apply(arguments)
  13813. : undefined;
  13814. var usePromise = false;
  13815. if (callback == undefined) {
  13816. usePromise = true;
  13817. }
  13818. if(!arguments.length) callback = undefined;
  13819. callback = (callback || noop).bind(this)
  13820. return disguise(this._invoke(transaction, 'getPosition', callback), this)
  13821. };
  13822. /**
  13823. * @callback module:elements.PlayerEndpoint~getPositionCallback
  13824. * @param {external:Error} error
  13825. * @param {external:int64} result
  13826. */
  13827. /**
  13828. * Get or set the actual position of the video in ms. <hr/><b>Note</b> Setting
  13829. * the position only works for seekable videos
  13830. *
  13831. * @alias module:elements.PlayerEndpoint#setPosition
  13832. *
  13833. * @param {external:int64} position
  13834. * @param {module:elements.PlayerEndpoint~setPositionCallback} [callback]
  13835. *
  13836. * @return {external:Promise}
  13837. */
  13838. PlayerEndpoint.prototype.setPosition = function(position, callback){
  13839. var transaction = (arguments[0] instanceof Transaction)
  13840. ? Array.prototype.shift.apply(arguments)
  13841. : undefined;
  13842. //
  13843. // checkType('int64', 'position', position, {required: true});
  13844. //
  13845. var params = {
  13846. position: position
  13847. };
  13848. callback = (callback || noop).bind(this)
  13849. return disguise(this._invoke(transaction, 'setPosition', params, callback), this)
  13850. };
  13851. /**
  13852. * @callback module:elements.PlayerEndpoint~setPositionCallback
  13853. * @param {external:Error} error
  13854. */
  13855. /**
  13856. * Returns info about the source being played
  13857. *
  13858. * @alias module:elements.PlayerEndpoint#getVideoInfo
  13859. *
  13860. * @param {module:elements.PlayerEndpoint~getVideoInfoCallback} [callback]
  13861. *
  13862. * @return {external:Promise}
  13863. */
  13864. PlayerEndpoint.prototype.getVideoInfo = function(callback){
  13865. var transaction = (arguments[0] instanceof Transaction)
  13866. ? Array.prototype.shift.apply(arguments)
  13867. : undefined;
  13868. var usePromise = false;
  13869. if (callback == undefined) {
  13870. usePromise = true;
  13871. }
  13872. if(!arguments.length) callback = undefined;
  13873. callback = (callback || noop).bind(this)
  13874. return disguise(this._invoke(transaction, 'getVideoInfo', callback), this)
  13875. };
  13876. /**
  13877. * @callback module:elements.PlayerEndpoint~getVideoInfoCallback
  13878. * @param {external:Error} error
  13879. * @param {module:elements/complexTypes.VideoInfo} result
  13880. */
  13881. //
  13882. // Public methods
  13883. //
  13884. /**
  13885. * Starts reproducing the media, sending it to the :rom:cls:`MediaSource`. If
  13886. * the endpoint
  13887. * has been connected to other endpoints, those will start receiving
  13888. * media.
  13889. *
  13890. * @alias module:elements.PlayerEndpoint.play
  13891. *
  13892. * @param {module:elements.PlayerEndpoint~playCallback} [callback]
  13893. *
  13894. * @return {external:Promise}
  13895. */
  13896. PlayerEndpoint.prototype.play = function(callback){
  13897. var transaction = (arguments[0] instanceof Transaction)
  13898. ? Array.prototype.shift.apply(arguments)
  13899. : undefined;
  13900. var usePromise = false;
  13901. if (callback == undefined) {
  13902. usePromise = true;
  13903. }
  13904. if(!arguments.length) callback = undefined;
  13905. callback = (callback || noop).bind(this)
  13906. return disguise(this._invoke(transaction, 'play', callback), this)
  13907. };
  13908. /**
  13909. * @callback module:elements.PlayerEndpoint~playCallback
  13910. * @param {external:Error} error
  13911. */
  13912. /**
  13913. * @alias module:elements.PlayerEndpoint.constructorParams
  13914. *
  13915. * @property {module:core.MediaPipeline} mediaPipeline
  13916. * The {@link module:core.MediaPipeline MediaPipeline} this PlayerEndpoint
  13917. * belongs to.
  13918. *
  13919. * @property {external:Integer} [networkCache]
  13920. * When using RTSP sources: Amount of milliseconds to buffer
  13921. *
  13922. * @property {external:String} uri
  13923. * URI pointing to the video. It has to be accessible to the KMS process.
  13924. * <ul>
  13925. * <li>Local resources: The user running the Kurento Media
  13926. * Server must have read permission over the file.</li>
  13927. * <li>Remote resources: Must be accessible from the server
  13928. * where the media server is running.</li>
  13929. * </ul>
  13930. *
  13931. * @property {external:Boolean} [useEncodedMedia]
  13932. * Feed the input media as-is to the Media Pipeline, instead of first decoding
  13933. * it.
  13934. * <p>
  13935. * When this property is not enabled, the input media gets always
  13936. * </p>
  13937. * <p>
  13938. * When this property is enabled, the explained behavior gets
  13939. * disabled. Instead, The endpoint will provide any input media
  13940. * directly to the Media Pipeline, without prior decoding.
  13941. * Enabling this mode of operation could have a severe effect on
  13942. * stability, because lost video keyframes will not be
  13943. * regenerated; however, avoiding a full cycle of decoding and
  13944. * encoding can be very useful for certain applications, because
  13945. * it improves performance by greatly reducing the CPU processing
  13946. * </p>
  13947. * <p>
  13948. * Keep in mind that if this property is enabled, the original
  13949. * source media MUST already have an encoding format which is
  13950. * compatible with the destination target. For example: given a
  13951. * pipeline which uses this endpoint to read a file and then
  13952. * streams it to a WebRTC browser such as Chrome, then the file
  13953. * must already be encoded with a VP8 or H.264 codec profile
  13954. * which Chrome is able to decode. Note that for this example,
  13955. * most browsers don't support ANY combination of H.264 encoding
  13956. * options; instead, they tend to support only a very specific
  13957. * subset of the codec features (also known as 'profiles').
  13958. * </p>
  13959. * <p>
  13960. * We strongly recommend to avoid using this option, because
  13961. * correct behavior cannot be guaranteed.
  13962. * </p>
  13963. */
  13964. PlayerEndpoint.constructorParams = {
  13965. mediaPipeline: {
  13966. type: 'kurento.MediaPipeline',
  13967. required: true
  13968. },
  13969. networkCache: {
  13970. type: 'int' },
  13971. uri: {
  13972. type: 'String',
  13973. required: true
  13974. },
  13975. useEncodedMedia: {
  13976. type: 'boolean' }
  13977. };
  13978. /**
  13979. * @alias module:elements.PlayerEndpoint.events
  13980. *
  13981. * @extends module:core/abstracts.UriEndpoint.events
  13982. */
  13983. PlayerEndpoint.events = UriEndpoint.events.concat(['EndOfStream']);
  13984. /**
  13985. * Checker for {@link module:elements.PlayerEndpoint}
  13986. *
  13987. * @memberof module:elements
  13988. *
  13989. * @param {external:String} key
  13990. * @param {module:elements.PlayerEndpoint} value
  13991. */
  13992. function checkPlayerEndpoint(key, value)
  13993. {
  13994. if(!(value instanceof PlayerEndpoint))
  13995. throw ChecktypeError(key, PlayerEndpoint, value);
  13996. };
  13997. module.exports = PlayerEndpoint;
  13998. PlayerEndpoint.check = checkPlayerEndpoint;
  13999. },{"inherits":"inherits","kurento-client":"kurento-client","kurento-client-core":"kurento-client-core"}],91:[function(require,module,exports){
  14000. /* Autogenerated with Kurento Idl */
  14001. /*
  14002. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  14003. *
  14004. * Licensed under the Apache License, Version 2.0 (the "License");
  14005. * you may not use this file except in compliance with the License.
  14006. * You may obtain a copy of the License at
  14007. *
  14008. * http://www.apache.org/licenses/LICENSE-2.0
  14009. *
  14010. * Unless required by applicable law or agreed to in writing, software
  14011. * distributed under the License is distributed on an "AS IS" BASIS,
  14012. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14013. * See the License for the specific language governing permissions and
  14014. * limitations under the License.
  14015. */
  14016. var inherits = require('inherits');
  14017. var kurentoClient = require('kurento-client');
  14018. var disguise = kurentoClient.disguise;
  14019. var checkType = kurentoClient.checkType;
  14020. var ChecktypeError = checkType.ChecktypeError;
  14021. var Transaction = kurentoClient.TransactionsManager.Transaction;
  14022. var UriEndpoint = require('kurento-client-core').abstracts.UriEndpoint;
  14023. function noop(error, result) {
  14024. if (error) console.trace(error);
  14025. return result
  14026. };
  14027. /**
  14028. *
  14029. * @classdesc
  14030. * Provides the functionality to store contents.
  14031. * <p>
  14032. * The Recorder can store media in local files or in a network resource. It
  14033. * receives a media stream from another {@link
  14034. * module:core/abstracts.MediaElement MediaElement} (i.e. the
  14035. * source), and stores it in the designated location.
  14036. * </p>
  14037. * <p>
  14038. * The following information has to be provided in order to create a
  14039. * RecorderEndpoint, and cannot be changed afterwards:
  14040. * </p>
  14041. * <ul>
  14042. * <li>
  14043. * <strong>Destination URI</strong>, where media will be stored. These
  14044. * formats
  14045. * are supported:
  14046. * <ul>
  14047. * <li>
  14048. * File: A file path that exists in the local file system.
  14049. * <ul>
  14050. * <li><code>file:///path/to/file</code></li>
  14051. * </ul>
  14052. * </li>
  14053. * <li>
  14054. * HTTP: Method PUT used against a remote server.
  14055. * <ul>
  14056. * <li><code>http(s)://{server-ip}/path/to/file</code></li>
  14057. * <li>
  14058. * <code>
  14059. * http(s)://{username}:{password}@{server-ip}/path/to/file
  14060. * </code>
  14061. * </li>
  14062. * </ul>
  14063. * </li>
  14064. * </ul>
  14065. * </li>
  14066. * <li>
  14067. * Relative URIs (with no schema) are supported. They are completed by
  14068. * prepending a default URI defined by property <i>defaultPath</i>. This
  14069. * property is defined in the configuration file
  14070. * <i>/etc/kurento/modules/kurento/UriEndpoint.conf.ini</i>, and the
  14071. * default
  14072. * value is <code>file:///var/lib/kurento/</code>
  14073. * </li>
  14074. * <li>
  14075. * The <stron>Media Profile</stron> ({@link
  14076. * module:elements.RecorderEndpoint#MediaProfileSpecType}) used for
  14077. * storage. This will determine the video and audio encoding. See below for
  14078. * more details about Media Profile.
  14079. * </li>
  14080. * <li>
  14081. * Optionally, the user can select if the endpoint will stop processing
  14082. * once
  14083. * the <strong>EndOfStream</strong> event is detected.
  14084. * </li>
  14085. * </ul>
  14086. * <p>
  14087. * <strong>
  14088. * RecorderEndpoint requires access to the resource where stream is going
  14089. * to be
  14090. * recorded
  14091. * </strong>
  14092. * . Otherwise, the media server won't be able to store any information, and
  14093. * an
  14094. * {@link ErrorEvent} will be fired. Please note that if you haven't
  14095. * subscribed to
  14096. * that type of event, you can be left wondering why your media is not being
  14097. * saved, while the error message was ignored.
  14098. * </p>
  14099. * <ul>
  14100. * <li>
  14101. * To write local files (if you use <code>file://</code>), the user running
  14102. * media server (by default, user <code>kurento</code>) needs to have write
  14103. * permissions for the requested path.
  14104. * </li>
  14105. * <li>
  14106. * To save into an HTTP server, the server must be accessible through the
  14107. * network, and also have the correct access rights.
  14108. * </li>
  14109. * </ul>
  14110. * <p>
  14111. * The media profile is quite an important parameter, as it will determine
  14112. * whether the server needs to perform on-the-fly transcoding of the media.
  14113. * If
  14114. * the input stream codec if not compatible with the selected media profile,
  14115. * the
  14116. * media will be transcoded into a suitable format. This will result in a
  14117. * higher
  14118. * CPU load and will impact overall performance of the media server.
  14119. * </p>
  14120. * <p>
  14121. * For example: Say that your pipeline will receive <b>VP8</b>-encoded video
  14122. * from
  14123. * WebRTC, and sends it to a RecorderEndpoint; depending on the format
  14124. * selected...
  14125. * </p>
  14126. * <ul>
  14127. * <li>
  14128. * WEBM: The input codec is the same as the recording format, so no
  14129. * transcoding
  14130. * will take place.
  14131. * </li>
  14132. * <li>
  14133. * MP4: The media server will have to transcode from <b>VP8</b> to
  14134. * <b>H264</b>.
  14135. * This will raise the CPU load in the system.
  14136. * </li>
  14137. * <li>
  14138. * MKV: Again, video must be transcoded from <b>VP8</b> to <b>H264</b>,
  14139. * which
  14140. * means more CPU load.
  14141. * </li>
  14142. * </ul>
  14143. * <p>
  14144. * From this you can see how selecting the correct format for your
  14145. * application is
  14146. * a very important decision.
  14147. * </p>
  14148. * <p>
  14149. * Recording will start as soon as the user invokes the
  14150. * <code>record</code> method. The recorder will then store, in the location
  14151. * indicated, the media that the source is sending to the endpoint. If no
  14152. * media
  14153. * is being received, or no endpoint has been connected, then the destination
  14154. * will be empty. The recorder starts storing information into the file as
  14155. * soon
  14156. * as it gets it.
  14157. * </p>
  14158. * <p>
  14159. * Stopping the recording process is done through the
  14160. * <code>stopAndWait</code> method, which will return only after all the
  14161. * information was stored correctly. If the file is empty, this means that no
  14162. * media arrived at the recorder.
  14163. * </p>
  14164. * <p>
  14165. * When another endpoint is connected to the recorder, by default both AUDIO
  14166. * and
  14167. * VIDEO media types are expected, unless specified otherwise when invoking
  14168. * the
  14169. * connect method. Failing to provide both types, will result in teh
  14170. * recording
  14171. * buffering the received media: it won't be written to the file until the
  14172. * recording is stopped. This is due to the recorder waiting for the other
  14173. * type
  14174. * of media to arrive, so they are synchronized.
  14175. * </p>
  14176. * <p>
  14177. * The source endpoint can be hot-swapped, while the recording is taking
  14178. * place.
  14179. * The recorded file will then contain different feeds. When switching video
  14180. * sources, if the new video has different size, the recorder will retain the
  14181. * size of the previous source. If the source is disconnected, the last frame
  14182. * recorded will be shown for the duration of the disconnection, or until the
  14183. * recording is stopped.
  14184. * </p>
  14185. * <p>
  14186. * <strong>
  14187. * It is recommended to start recording only after media arrives
  14188. * </strong>
  14189. * . For this, you may use the <code>MediaFlowInStateChange</code> and
  14190. * <code>MediaFlowOutStateChange</code>
  14191. * events of your endpoints, and synchronize the recording with the moment
  14192. * media
  14193. * comes into the Recorder. For example:
  14194. * </p>
  14195. * <ol>
  14196. * <li>
  14197. * When the remote video arrives to KMS, your WebRtcEndpoint will start
  14198. * generating packets into the Kurento Pipeline, and it will trigger a
  14199. * <code>MediaFlowOutStateChange</code> event.
  14200. * </li>
  14201. * <li>
  14202. * When video packets arrive from the WebRtcEndpoint to the
  14203. * RecorderEndpoint,
  14204. * the RecorderEndpoint will raise a <code>MediaFlowInStateChange</code>
  14205. * event.
  14206. * </li>
  14207. * <li>
  14208. * You should only start recording when RecorderEndpoint has notified a
  14209. * <code>MediaFlowInStateChange</code> for ALL streams (so, if you record
  14210. * AUDIO+VIDEO, your application must receive a
  14211. * <code>MediaFlowInStateChange</code> event for audio, and another
  14212. * <code>MediaFlowInStateChange</code> event for video).
  14213. * </li>
  14214. * </ol>
  14215. *
  14216. * @extends module:core/abstracts.UriEndpoint
  14217. *
  14218. * @constructor module:elements.RecorderEndpoint
  14219. *
  14220. * @fires {@link module:elements#event:Paused Paused}
  14221. * @fires {@link module:elements#event:Recording Recording}
  14222. * @fires {@link module:elements#event:Stopped Stopped}
  14223. */
  14224. function RecorderEndpoint(){
  14225. RecorderEndpoint.super_.call(this);
  14226. };
  14227. inherits(RecorderEndpoint, UriEndpoint);
  14228. //
  14229. // Public methods
  14230. //
  14231. /**
  14232. * Starts storing media received through the sink pad.
  14233. *
  14234. * @alias module:elements.RecorderEndpoint.record
  14235. *
  14236. * @param {module:elements.RecorderEndpoint~recordCallback} [callback]
  14237. *
  14238. * @return {external:Promise}
  14239. */
  14240. RecorderEndpoint.prototype.record = function(callback){
  14241. var transaction = (arguments[0] instanceof Transaction)
  14242. ? Array.prototype.shift.apply(arguments)
  14243. : undefined;
  14244. var usePromise = false;
  14245. if (callback == undefined) {
  14246. usePromise = true;
  14247. }
  14248. if(!arguments.length) callback = undefined;
  14249. callback = (callback || noop).bind(this)
  14250. return disguise(this._invoke(transaction, 'record', callback), this)
  14251. };
  14252. /**
  14253. * @callback module:elements.RecorderEndpoint~recordCallback
  14254. * @param {external:Error} error
  14255. */
  14256. /**
  14257. * Stops recording and does not return until all the content has been written to
  14258. *
  14259. * @alias module:elements.RecorderEndpoint.stopAndWait
  14260. *
  14261. * @param {module:elements.RecorderEndpoint~stopAndWaitCallback} [callback]
  14262. *
  14263. * @return {external:Promise}
  14264. */
  14265. RecorderEndpoint.prototype.stopAndWait = function(callback){
  14266. var transaction = (arguments[0] instanceof Transaction)
  14267. ? Array.prototype.shift.apply(arguments)
  14268. : undefined;
  14269. var usePromise = false;
  14270. if (callback == undefined) {
  14271. usePromise = true;
  14272. }
  14273. if(!arguments.length) callback = undefined;
  14274. callback = (callback || noop).bind(this)
  14275. return disguise(this._invoke(transaction, 'stopAndWait', callback), this)
  14276. };
  14277. /**
  14278. * @callback module:elements.RecorderEndpoint~stopAndWaitCallback
  14279. * @param {external:Error} error
  14280. */
  14281. /**
  14282. * @alias module:elements.RecorderEndpoint.constructorParams
  14283. *
  14284. * @property {module:core.MediaPipeline} mediaPipeline
  14285. * the {@link module:core.MediaPipeline MediaPipeline} to which the endpoint
  14286. * belongs
  14287. *
  14288. * @property {module:elements/complexTypes.MediaProfileSpecType} [mediaProfile]
  14289. * Sets the media profile used for recording. If the profile is different than
  14290. * the one being recieved at the sink pad, media will be trnascoded, resulting
  14291. * in a higher CPU load. For instance, when recording a VP8 encoded video from
  14292. * a WebRTC endpoint in MP4, the load is higher that when recording in WEBM.
  14293. *
  14294. * @property {external:Boolean} [stopOnEndOfStream]
  14295. * Forces the recorder endpoint to finish processing data when an <a
  14296. * href="http://www.kurento.org/docs/current/glossary.html#term-eos">EOS</a> is
  14297. *
  14298. * @property {external:String} uri
  14299. * URI where the recording will be stored. It has to be accessible to the KMS
  14300. * process.
  14301. * <ul>
  14302. * <li>Local server resources: The user running the Kurento
  14303. * Media Server must have write permission over the file.</li>
  14304. * <li>Network resources: Must be accessible from the server
  14305. * where the media server is running.</li>
  14306. * </ul>
  14307. */
  14308. RecorderEndpoint.constructorParams = {
  14309. mediaPipeline: {
  14310. type: 'kurento.MediaPipeline',
  14311. required: true
  14312. },
  14313. mediaProfile: {
  14314. type: 'kurento.MediaProfileSpecType' },
  14315. stopOnEndOfStream: {
  14316. type: 'boolean' },
  14317. uri: {
  14318. type: 'String',
  14319. required: true
  14320. }
  14321. };
  14322. /**
  14323. * @alias module:elements.RecorderEndpoint.events
  14324. *
  14325. * @extends module:core/abstracts.UriEndpoint.events
  14326. */
  14327. RecorderEndpoint.events = UriEndpoint.events.concat(['Paused', 'Recording', 'Stopped']);
  14328. /**
  14329. * Checker for {@link module:elements.RecorderEndpoint}
  14330. *
  14331. * @memberof module:elements
  14332. *
  14333. * @param {external:String} key
  14334. * @param {module:elements.RecorderEndpoint} value
  14335. */
  14336. function checkRecorderEndpoint(key, value)
  14337. {
  14338. if(!(value instanceof RecorderEndpoint))
  14339. throw ChecktypeError(key, RecorderEndpoint, value);
  14340. };
  14341. module.exports = RecorderEndpoint;
  14342. RecorderEndpoint.check = checkRecorderEndpoint;
  14343. },{"inherits":"inherits","kurento-client":"kurento-client","kurento-client-core":"kurento-client-core"}],92:[function(require,module,exports){
  14344. /* Autogenerated with Kurento Idl */
  14345. /*
  14346. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  14347. *
  14348. * Licensed under the Apache License, Version 2.0 (the "License");
  14349. * you may not use this file except in compliance with the License.
  14350. * You may obtain a copy of the License at
  14351. *
  14352. * http://www.apache.org/licenses/LICENSE-2.0
  14353. *
  14354. * Unless required by applicable law or agreed to in writing, software
  14355. * distributed under the License is distributed on an "AS IS" BASIS,
  14356. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14357. * See the License for the specific language governing permissions and
  14358. * limitations under the License.
  14359. */
  14360. var inherits = require('inherits');
  14361. var kurentoClient = require('kurento-client');
  14362. var disguise = kurentoClient.disguise;
  14363. var ChecktypeError = kurentoClient.checkType.ChecktypeError;
  14364. var BaseRtpEndpoint = require('kurento-client-core').abstracts.BaseRtpEndpoint;
  14365. /**
  14366. * Builder for the {@link module:elements.RtpEndpoint RtpEndpoint}
  14367. *
  14368. * @classdesc
  14369. * Endpoint that provides bidirectional content delivery capabilities with
  14370. * remote networked peers through RTP or SRTP protocol. An {@link
  14371. * module:elements.RtpEndpoint RtpEndpoint} contains paired sink and source
  14372. * :rom:cls:`MediaPad` for audio and video. This endpoint inherits from {@link
  14373. * module:core/abstracts.BaseRtpEndpoint BaseRtpEndpoint}.
  14374. * </p>
  14375. * <p>
  14376. * In order to establish an RTP/SRTP communication, peers engage in an
  14377. * SDP negotiation process, where one of the peers (the offerer) sends an
  14378. * <ul style='list-style-type:circle'>
  14379. * <li>
  14380. * As offerer: The negotiation process is initiated by the media
  14381. * server
  14382. * <ul>
  14383. * <li>KMS generates the SDP offer through the generateOffer
  14384. * method. This offer must then be sent to the remote peer (the
  14385. * offeree) through the signaling channel, for processing.</li>
  14386. * <li>The remote peer process the Offer, and generates an Answer
  14387. * to this offer. The Answer is sent back to the media server.</li>
  14388. * <li>Upon receiving the Answer, the endpoint must invoke the
  14389. * processAnswer method.</li>
  14390. * </ul>
  14391. * </li>
  14392. * <li>
  14393. * As offeree: The negotiation process is initiated by the remote
  14394. * peer
  14395. * <ul>
  14396. * <li>The remote peer, acting as offerer, generates an SDP offer
  14397. * and sends it to the WebRTC endpoint in Kurento.</li>
  14398. * <li>The endpoint will process the Offer invoking the
  14399. * processOffer method. The result of this method will be a string,
  14400. * <li>The SDP Answer must be sent back to the offerer, so it can
  14401. * be processed.</li>
  14402. * </ul>
  14403. * </li>
  14404. * </ul>
  14405. * </p>
  14406. * <p>
  14407. * In case of unidirectional connections (i.e. only one peer is going to
  14408. * send media), the process is more simple, as only the emitter needs to
  14409. * process an SDP. On top of the information about media codecs and
  14410. * types, the SDP must contain the IP of the remote peer, and the port
  14411. * where it will be listening. This way, the SDP can be mangled without
  14412. * needing to go through the exchange process, as the receiving peer does
  14413. * </p>
  14414. * <p>
  14415. * The user can set some bandwidth limits that will be used during the
  14416. * negotiation process.
  14417. * The default bandwidth range of the endpoint is 100kbps-500kbps, but it
  14418. * <ul style='list-style-type:circle'>
  14419. * <li>
  14420. * Input bandwidth control mechanism: Configuration interval used to
  14421. * inform remote peer the range of bitrates that can be pushed into
  14422. * this RtpEndpoint object. These values are announced in the SDP.
  14423. * <ul>
  14424. * <li>
  14425. * setMaxVideoRecvBandwidth: sets Max bitrate limits expected for
  14426. * </li>
  14427. * <li>
  14428. * setMaxAudioRecvBandwidth: sets Max bitrate limits expected for
  14429. * </li>
  14430. * </ul>
  14431. * </li>
  14432. * <li>
  14433. * Output bandwidth control mechanism: Configuration interval used to
  14434. * <ul>
  14435. * <li>
  14436. * setMaxVideoSendBandwidth: sets Max bitrate limits for video
  14437. * sent to remote peer.
  14438. * </li>
  14439. * <li>
  14440. * setMinVideoSendBandwidth: sets Min bitrate limits for audio
  14441. * sent to remote peer.
  14442. * </li>
  14443. * </ul>
  14444. * </li>
  14445. * </ul>
  14446. * All bandwidth control parameters must be changed before the SDP
  14447. * negotiation takes place, and can't be modified afterwards.
  14448. * TODO: What happens if the b=as tag form the SDP has a lower value than
  14449. * </p>
  14450. * <p>
  14451. * Take into consideration that setting a too high upper limit for the
  14452. * output bandwidth can be a reason for the local network connection to
  14453. * be overflooded.
  14454. * </p>
  14455. *
  14456. * @extends module:core/abstracts.BaseRtpEndpoint
  14457. *
  14458. * @constructor module:elements.RtpEndpoint
  14459. *
  14460. * @fires {@link module:elements#event:OnKeySoftLimit OnKeySoftLimit}
  14461. */
  14462. function RtpEndpoint(){
  14463. RtpEndpoint.super_.call(this);
  14464. };
  14465. inherits(RtpEndpoint, BaseRtpEndpoint);
  14466. /**
  14467. * @alias module:elements.RtpEndpoint.constructorParams
  14468. *
  14469. * @property {module:elements/complexTypes.SDES} [crypto]
  14470. * SDES-type param. If present, this parameter indicates that the communication
  14471. *
  14472. * @property {module:core.MediaPipeline} mediaPipeline
  14473. * the {@link module:core.MediaPipeline MediaPipeline} to which the endpoint
  14474. * belongs
  14475. *
  14476. * @property {external:Boolean} [useIpv6]
  14477. * This configures the endpoint to use IPv6 instead of IPv4.
  14478. */
  14479. RtpEndpoint.constructorParams = {
  14480. crypto: {
  14481. type: 'kurento.SDES' },
  14482. mediaPipeline: {
  14483. type: 'kurento.MediaPipeline',
  14484. required: true
  14485. },
  14486. useIpv6: {
  14487. type: 'boolean' }
  14488. };
  14489. /**
  14490. * @alias module:elements.RtpEndpoint.events
  14491. *
  14492. * @extends module:core/abstracts.BaseRtpEndpoint.events
  14493. */
  14494. RtpEndpoint.events = BaseRtpEndpoint.events.concat(['OnKeySoftLimit']);
  14495. /**
  14496. * Checker for {@link module:elements.RtpEndpoint}
  14497. *
  14498. * @memberof module:elements
  14499. *
  14500. * @param {external:String} key
  14501. * @param {module:elements.RtpEndpoint} value
  14502. */
  14503. function checkRtpEndpoint(key, value)
  14504. {
  14505. if(!(value instanceof RtpEndpoint))
  14506. throw ChecktypeError(key, RtpEndpoint, value);
  14507. };
  14508. module.exports = RtpEndpoint;
  14509. RtpEndpoint.check = checkRtpEndpoint;
  14510. },{"inherits":"inherits","kurento-client":"kurento-client","kurento-client-core":"kurento-client-core"}],93:[function(require,module,exports){
  14511. /* Autogenerated with Kurento Idl */
  14512. /*
  14513. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  14514. *
  14515. * Licensed under the Apache License, Version 2.0 (the "License");
  14516. * you may not use this file except in compliance with the License.
  14517. * You may obtain a copy of the License at
  14518. *
  14519. * http://www.apache.org/licenses/LICENSE-2.0
  14520. *
  14521. * Unless required by applicable law or agreed to in writing, software
  14522. * distributed under the License is distributed on an "AS IS" BASIS,
  14523. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14524. * See the License for the specific language governing permissions and
  14525. * limitations under the License.
  14526. */
  14527. var inherits = require('inherits');
  14528. var kurentoClient = require('kurento-client');
  14529. var disguise = kurentoClient.disguise;
  14530. var checkType = kurentoClient.checkType;
  14531. var ChecktypeError = checkType.ChecktypeError;
  14532. var Transaction = kurentoClient.TransactionsManager.Transaction;
  14533. var BaseRtpEndpoint = require('kurento-client-core').abstracts.BaseRtpEndpoint;
  14534. function noop(error, result) {
  14535. if (error) console.trace(error);
  14536. return result
  14537. };
  14538. /**
  14539. * Builder for the {@link module:elements.WebRtcEndpoint WebRtcEndpoint}
  14540. *
  14541. * @classdesc
  14542. * Control interface for Kurento WebRTC endpoint.
  14543. * <p>
  14544. * This endpoint is one side of a peer-to-peer WebRTC communication, being
  14545. * the
  14546. * other peer a WebRTC capable browser -using the RTCPeerConnection API-, a
  14547. * native WebRTC app or even another Kurento Media Server.
  14548. * </p>
  14549. * <p>
  14550. * In order to establish a WebRTC communication, peers engage in an SDP
  14551. * negotiation process, where one of the peers (the offerer) sends an offer,
  14552. * while the other peer (the offeree) responds with an answer. This endpoint
  14553. * can
  14554. * function in both situations
  14555. * </p>
  14556. * <ul>
  14557. * <li>
  14558. * As offerer: The negotiation process is initiated by the media server
  14559. * <ul>
  14560. * <li>
  14561. * KMS generates the SDP offer through the
  14562. * <code>generateOffer</code> method. This <i>offer</i> must then be
  14563. * sent
  14564. * to the remote peer (the offeree) through the signaling channel, for
  14565. * processing.
  14566. * </li>
  14567. * <li>
  14568. * The remote peer processes the <i>offer</i>, and generates an
  14569. * <i>answer</i>. The <i>answer</i> is sent back to the media server.
  14570. * </li>
  14571. * <li>
  14572. * Upon receiving the <i>answer</i>, the endpoint must invoke the
  14573. * <code>processAnswer</code> method.
  14574. * </li>
  14575. * </ul>
  14576. * </li>
  14577. * <li>
  14578. * As offeree: The negotiation process is initiated by the remote peer
  14579. * <ul>
  14580. * <li>
  14581. * The remote peer, acting as offerer, generates an SDP <i>offer</i>
  14582. * and
  14583. * sends it to the WebRTC endpoint in Kurento.
  14584. * </li>
  14585. * <li>
  14586. * The endpoint will process the <i>offer</i> invoking the
  14587. * <code>processOffer</code> method. The result of this method will be
  14588. * a
  14589. * string, containing an SDP <i>answer</i>.
  14590. * </li>
  14591. * <li>
  14592. * The SDP <i>answer</i> must be sent back to the offerer, so it can be
  14593. * processed.
  14594. * </li>
  14595. * </ul>
  14596. * </li>
  14597. * </ul>
  14598. * <p>
  14599. * SDPs are sent without ICE candidates, following the Trickle ICE
  14600. * optimization.
  14601. * Once the SDP negotiation is completed, both peers proceed with the ICE
  14602. * discovery process, intended to set up a bidirectional media connection.
  14603. * During
  14604. * this process, each peer
  14605. * </p>
  14606. * <ul>
  14607. * <li>
  14608. * Discovers ICE candidates for itself, containing pairs of IPs and ports.
  14609. * </li>
  14610. * <li>
  14611. * ICE candidates are sent via the signaling channel as they are
  14612. * discovered, to
  14613. * the remote peer for probing.
  14614. * </li>
  14615. * <li>
  14616. * ICE connectivity checks are run as soon as the new candidate
  14617. * description,
  14618. * from the remote peer, is available.
  14619. * </li>
  14620. * </ul>
  14621. * <p>
  14622. * Once a suitable pair of candidates (one for each peer) is discovered, the
  14623. * media session can start. The harvesting process in Kurento, begins with
  14624. * the
  14625. * invocation of the <code>gatherCandidates</code> method. Since the whole
  14626. * Trickle ICE purpose is to speed-up connectivity, candidates are generated
  14627. * asynchronously. Therefore, in order to capture the candidates, the user
  14628. * must
  14629. * subscribe to the event <code>IceCandidateFound</code>. It is important
  14630. * that
  14631. * the event listener is bound before invoking <code>gatherCandidates</code>,
  14632. * otherwise a suitable candidate might be lost, and connection might not be
  14633. * established.
  14634. * </p>
  14635. * <p>
  14636. * It's important to keep in mind that WebRTC connection is an asynchronous
  14637. * process, when designing interactions between different MediaElements. For
  14638. * example, it would be pointless to start recording before media is flowing.
  14639. * order to be notified of state changes, the application can subscribe to
  14640. * events
  14641. * generated by the WebRtcEndpoint. Following is a full list of events
  14642. * generated
  14643. * by WebRtcEndpoint:
  14644. * </p>
  14645. * <ul>
  14646. * <li>
  14647. * <code>IceComponentStateChange</code>: This event informs only about
  14648. * changes
  14649. * in the ICE connection state. Possible values are:
  14650. * <ul>
  14651. * <li><code>DISCONNECTED</code>: No activity scheduled</li>
  14652. * <li><code>GATHERING</code>: Gathering local candidates</li>
  14653. * <li><code>CONNECTING</code>: Establishing connectivity</li>
  14654. * <li><code>CONNECTED</code>: At least one working candidate pair</li>
  14655. * <li>
  14656. * <code>READY</code>: ICE concluded, candidate pair selection is now
  14657. * final
  14658. * </li>
  14659. * <li>
  14660. * <code>FAILED</code>: Connectivity checks have been completed, but
  14661. * media
  14662. * connection was not established
  14663. * </li>
  14664. * </ul>
  14665. * The transitions between states are covered in RFC5245. It could be said
  14666. * that
  14667. * it's network-only, as it only takes into account the state of the
  14668. * network
  14669. * connection, ignoring other higher level stuff, like DTLS handshake, RTCP
  14670. * flow, etc. This implies that, while the component state is
  14671. * <code>CONNECTED</code>, there might be no media flowing between the
  14672. * peers.
  14673. * This makes this event useful only to receive low-level information about
  14674. * connection between peers. Even more, while other events might leave a
  14675. * graceful period of time before firing, this event fires immediately
  14676. * after
  14677. * the state change is detected.
  14678. * </li>
  14679. * <li>
  14680. * <code>IceCandidateFound</code>: Raised when a new candidate is
  14681. * discovered.
  14682. * ICE candidates must be sent to the remote peer of the connection.
  14683. * Failing to
  14684. * do so for some or all of the candidates might render the connection
  14685. * unusable.
  14686. * </li>
  14687. * <li>
  14688. * <code>IceGatheringDone</code>: Raised when the ICE harvesting process is
  14689. * completed. This means that all candidates have already been discovered.
  14690. * </li>
  14691. * <li>
  14692. * <code>NewCandidatePairSelected</code>: Raised when a new ICE candidate
  14693. * pair
  14694. * gets selected. The pair contains both local and remote candidates being
  14695. * used
  14696. * for a component. This event can be raised during a media session, if a
  14697. * new
  14698. * pair of candidates with higher priority in the link are found.
  14699. * </li>
  14700. * <li><code>DataChannelOpen</code>: Raised when a data channel is open.</li>
  14701. * <li><code>DataChannelClose</code>: Raised when a data channel is
  14702. * closed.</li>
  14703. * </ul>
  14704. * <p>
  14705. * Registering to any of above events requires the application to provide a
  14706. * callback function. Each event provides different information, so it is
  14707. * recommended to consult the signature of the event listeners.
  14708. * </p>
  14709. * <p>
  14710. * Flow control and congestion management is one of the most important
  14711. * features
  14712. * of WebRTC. WebRTC connections start with the lowest bandwidth configured
  14713. * and
  14714. * slowly ramps up to the maximum available bandwidth, or to the higher limit
  14715. * the exploration range in case no bandwidth limitation is detected. Notice
  14716. * that
  14717. * WebRtcEndpoints in Kurento are designed in a way that multiple WebRTC
  14718. * connections fed by the same stream share quality. When a new connection is
  14719. * added, as it requires to start with low bandwidth, it will cause the rest
  14720. * of
  14721. * connections to experience a transient period of degraded quality, until it
  14722. * stabilizes its bitrate. This doesn't apply when transcoding is involved.
  14723. * Transcoders will adjust their output bitrate based in bandwidth
  14724. * requirements,
  14725. * but it won't affect the original stream. If an incoming WebRTC stream
  14726. * needs to
  14727. * be transcoded, for whatever reason, all WebRtcEndpoints fed from
  14728. * transcoder
  14729. * output will share a separate quality than the ones connected directly to
  14730. * the
  14731. * original stream.
  14732. * </p>
  14733. * <p>
  14734. * The default bandwidth range of the endpoint is
  14735. * <strong>[100 kbps, 500 kbps]</strong>, but it can be changed separately
  14736. * for
  14737. * input/output directions and for audio/video streams.
  14738. * </p>
  14739. * <p>
  14740. * <strong>
  14741. * Check the extended documentation of these parameters in
  14742. * {@link module:core/abstracts.SdpEndpoint SdpEndpoint}, {@link
  14743. * module:core/abstracts.BaseRtpEndpoint BaseRtpEndpoint}, and
  14744. * {@link module:core/complexTypes.RembParams RembParams}.
  14745. * </strong>
  14746. * </p>
  14747. * <ul>
  14748. * <li>
  14749. * Input bandwidth: Configuration value used to inform remote peers about
  14750. * the
  14751. * bitrate that can be pushed into this endpoint.
  14752. * <ul>
  14753. * <li>
  14754. * <strong>{get,set}MinVideoRecvBandwidth</strong>: Minimum bitrate
  14755. * requested on the received video stream.
  14756. * </li>
  14757. * <li>
  14758. * <strong>{get,set}Max{Audio,Video}RecvBandwidth</strong>: Maximum
  14759. * bitrate
  14760. * expected for the received stream.
  14761. * </li>
  14762. * </ul>
  14763. * </li>
  14764. * <li>
  14765. * Output bandwidth: Configuration values used to control bitrate of the
  14766. * output
  14767. * video stream sent to remote peers. It is important to keep in mind that
  14768. * pushed bitrate depends on network and remote peer capabilities. Remote
  14769. * peers
  14770. * can also announce bandwidth limitation in their SDPs (through the
  14771. * <code>b={modifier}:{value}</code> tag). Kurento will always enforce
  14772. * bitrate
  14773. * limitations specified by the remote peer over internal configurations.
  14774. * <ul>
  14775. * <li>
  14776. * <strong>{get,set}MinVideoSendBandwidth</strong>: Minimum video
  14777. * bitrate
  14778. * sent to remote peer.
  14779. * </li>
  14780. * <li>
  14781. * <strong>{get,set}MaxVideoSendBandwidth</strong>: Maximum video
  14782. * bitrate
  14783. * sent to remote peer.
  14784. * </li>
  14785. * <li>
  14786. * <strong>RembParams.rembOnConnect</strong>: Initial local REMB
  14787. * bandwidth
  14788. * estimation that gets propagated when a new endpoint is connected.
  14789. * </li>
  14790. * </ul>
  14791. * </li>
  14792. * </ul>
  14793. * <p>
  14794. * <strong>
  14795. * All bandwidth control parameters must be changed before the SDP
  14796. * negotiation
  14797. * takes place, and can't be changed afterwards.
  14798. * </strong>
  14799. * </p>
  14800. * <p>
  14801. * DataChannels allow other media elements that make use of the DataPad, to
  14802. * send
  14803. * arbitrary data. For instance, if there is a filter that publishes event
  14804. * information, it'll be sent to the remote peer through the channel. There
  14805. * is no
  14806. * API available for programmers to make use of this feature in the
  14807. * WebRtcElement. DataChannels can be configured to provide the following:
  14808. * </p>
  14809. * <ul>
  14810. * <li>
  14811. * Reliable or partially reliable delivery of sent messages
  14812. * </li>
  14813. * <li>
  14814. * In-order or out-of-order delivery of sent messages
  14815. * </li>
  14816. * </ul>
  14817. * <p>
  14818. * Unreliable, out-of-order delivery is equivalent to raw UDP semantics. The
  14819. * message may make it, or it may not, and order is not important. However,
  14820. * the
  14821. * channel can be configured to be <i>partially reliable</i> by specifying
  14822. * the
  14823. * maximum number of retransmissions or setting a time limit for
  14824. * retransmissions:
  14825. * the WebRTC stack will handle the acknowledgments and timeouts.
  14826. * </p>
  14827. * <p>
  14828. * The possibility to create DataChannels in a WebRtcEndpoint must be
  14829. * explicitly
  14830. * enabled when creating the endpoint, as this feature is disabled by
  14831. * default. If
  14832. * this is the case, they can be created invoking the createDataChannel
  14833. * method.
  14834. * The arguments for this method, all of them optional, provide the necessary
  14835. * configuration:
  14836. * </p>
  14837. * <ul>
  14838. * <li>
  14839. * <code>label</code>: assigns a label to the DataChannel. This can help
  14840. * identify each possible channel separately.
  14841. * </li>
  14842. * <li>
  14843. * <code>ordered</code>: specifies if the DataChannel guarantees order,
  14844. * which
  14845. * is the default mode. If maxPacketLifetime and maxRetransmits have not
  14846. * been
  14847. * set, this enables reliable mode.
  14848. * </li>
  14849. * <li>
  14850. * <code>maxPacketLifeTime</code>: The time window in milliseconds, during
  14851. * which transmissions and retransmissions may take place in unreliable
  14852. * mode.
  14853. * This forces unreliable mode, even if <code>ordered</code> has been
  14854. * activated.
  14855. * </li>
  14856. * <li>
  14857. * <code>maxRetransmits</code>: maximum number of retransmissions that are
  14858. * attempted in unreliable mode. This forces unreliable mode, even if
  14859. * <code>ordered</code> has been activated.
  14860. * </li>
  14861. * <li>
  14862. * <code>Protocol</code>: Name of the subprotocol used for data
  14863. * communication.
  14864. * </li>
  14865. * </ul>
  14866. *
  14867. * @extends module:core/abstracts.BaseRtpEndpoint
  14868. *
  14869. * @constructor module:elements.WebRtcEndpoint
  14870. *
  14871. * @fires {@link module:elements#event:DataChannelClose DataChannelClose}
  14872. * @fires {@link module:elements#event:DataChannelOpen DataChannelOpen}
  14873. * @fires {@link module:elements#event:IceCandidateFound IceCandidateFound}
  14874. * @fires {@link module:elements#event:IceComponentStateChange IceComponentStateChange}
  14875. * @fires {@link module:elements#event:IceGatheringDone IceGatheringDone}
  14876. * @fires {@link module:elements#event:NewCandidatePairSelected NewCandidatePairSelected}
  14877. * @fires {@link module:elements#event:OnDataChannelClosed OnDataChannelClosed}
  14878. * @fires {@link module:elements#event:OnDataChannelOpened OnDataChannelOpened}
  14879. * @fires {@link module:elements#event:OnIceCandidate OnIceCandidate}
  14880. * @fires {@link module:elements#event:OnIceComponentStateChanged OnIceComponentStateChanged}
  14881. * @fires {@link module:elements#event:OnIceGatheringDone OnIceGatheringDone}
  14882. */
  14883. function WebRtcEndpoint(){
  14884. WebRtcEndpoint.super_.call(this);
  14885. };
  14886. inherits(WebRtcEndpoint, BaseRtpEndpoint);
  14887. //
  14888. // Public properties
  14889. //
  14890. /**
  14891. * External IP address of the media server.
  14892. * <p>
  14893. * This setting is normally NOT needed. Only use it if you know what you're
  14894. * doing, and understand 100% WHY you want it. For the majority of cases, you
  14895. * should prefer configuring STUN or TURN servers over using this setting.
  14896. * </p>
  14897. * <p>
  14898. * This setting implements a hack that will mangle all local ICE candidates so
  14899. * that their candidate address is replaced with the provided external
  14900. * address,
  14901. * even for candidates of type 'host'. In doing so, this KMS will not need a
  14902. * STUN or TURN server, but remote peers will still be able to contact it.
  14903. * </p>
  14904. * <p>
  14905. * You can try using this setting if KMS is deployed on a publicly accessible
  14906. * server, without NAT, and with a static public IP address. But if it doesn't
  14907. * work for you, just go back to using the STUN or TURN settings above.
  14908. * </p>
  14909. * <p>
  14910. * <code>externalAddress</code> is an IPv4 or IPv6 address.
  14911. * </p>
  14912. * <p>Examples:</p>
  14913. * <ul>
  14914. * <li><code>externalAddress=10.70.35.2</code></li>
  14915. * <li><code>externalAddress=2001:0db8:85a3:0000:0000:8a2e:0370:7334</code></li>
  14916. * </ul>
  14917. *
  14918. * @alias module:elements.WebRtcEndpoint#getExternalAddress
  14919. *
  14920. * @param {module:elements.WebRtcEndpoint~getExternalAddressCallback} [callback]
  14921. *
  14922. * @return {external:Promise}
  14923. */
  14924. WebRtcEndpoint.prototype.getExternalAddress = function(callback){
  14925. var transaction = (arguments[0] instanceof Transaction)
  14926. ? Array.prototype.shift.apply(arguments)
  14927. : undefined;
  14928. var usePromise = false;
  14929. if (callback == undefined) {
  14930. usePromise = true;
  14931. }
  14932. if(!arguments.length) callback = undefined;
  14933. callback = (callback || noop).bind(this)
  14934. return disguise(this._invoke(transaction, 'getExternalAddress', callback), this)
  14935. };
  14936. /**
  14937. * @callback module:elements.WebRtcEndpoint~getExternalAddressCallback
  14938. * @param {external:Error} error
  14939. * @param {external:String} result
  14940. */
  14941. /**
  14942. * External IP address of the media server.
  14943. * <p>
  14944. * This setting is normally NOT needed. Only use it if you know what you're
  14945. * doing, and understand 100% WHY you want it. For the majority of cases, you
  14946. * should prefer configuring STUN or TURN servers over using this setting.
  14947. * </p>
  14948. * <p>
  14949. * This setting implements a hack that will mangle all local ICE candidates so
  14950. * that their candidate address is replaced with the provided external
  14951. * address,
  14952. * even for candidates of type 'host'. In doing so, this KMS will not need a
  14953. * STUN or TURN server, but remote peers will still be able to contact it.
  14954. * </p>
  14955. * <p>
  14956. * You can try using this setting if KMS is deployed on a publicly accessible
  14957. * server, without NAT, and with a static public IP address. But if it doesn't
  14958. * work for you, just go back to using the STUN or TURN settings above.
  14959. * </p>
  14960. * <p>
  14961. * <code>externalAddress</code> is an IPv4 or IPv6 address.
  14962. * </p>
  14963. * <p>Examples:</p>
  14964. * <ul>
  14965. * <li><code>externalAddress=10.70.35.2</code></li>
  14966. * <li><code>externalAddress=2001:0db8:85a3:0000:0000:8a2e:0370:7334</code></li>
  14967. * </ul>
  14968. *
  14969. * @alias module:elements.WebRtcEndpoint#setExternalAddress
  14970. *
  14971. * @param {external:String} externalAddress
  14972. * @param {module:elements.WebRtcEndpoint~setExternalAddressCallback} [callback]
  14973. *
  14974. * @return {external:Promise}
  14975. */
  14976. WebRtcEndpoint.prototype.setExternalAddress = function(externalAddress, callback){
  14977. var transaction = (arguments[0] instanceof Transaction)
  14978. ? Array.prototype.shift.apply(arguments)
  14979. : undefined;
  14980. //
  14981. // checkType('String', 'externalAddress', externalAddress, {required: true});
  14982. //
  14983. var params = {
  14984. externalAddress: externalAddress
  14985. };
  14986. callback = (callback || noop).bind(this)
  14987. return disguise(this._invoke(transaction, 'setExternalAddress', params, callback), this)
  14988. };
  14989. /**
  14990. * @callback module:elements.WebRtcEndpoint~setExternalAddressCallback
  14991. * @param {external:Error} error
  14992. */
  14993. /**
  14994. * the ICE candidate pair (local and remote candidates) used by the ice library
  14995. * for each stream.
  14996. *
  14997. * @alias module:elements.WebRtcEndpoint#getICECandidatePairs
  14998. *
  14999. * @param {module:elements.WebRtcEndpoint~getICECandidatePairsCallback} [callback]
  15000. *
  15001. * @return {external:Promise}
  15002. */
  15003. WebRtcEndpoint.prototype.getICECandidatePairs = function(callback){
  15004. var transaction = (arguments[0] instanceof Transaction)
  15005. ? Array.prototype.shift.apply(arguments)
  15006. : undefined;
  15007. var usePromise = false;
  15008. if (callback == undefined) {
  15009. usePromise = true;
  15010. }
  15011. if(!arguments.length) callback = undefined;
  15012. callback = (callback || noop).bind(this)
  15013. return disguise(this._invoke(transaction, 'getICECandidatePairs', callback), this)
  15014. };
  15015. /**
  15016. * @callback module:elements.WebRtcEndpoint~getICECandidatePairsCallback
  15017. * @param {external:Error} error
  15018. * @param {module:elements/complexTypes.IceCandidatePair} result
  15019. */
  15020. /**
  15021. * the ICE connection state for all the connections.
  15022. *
  15023. * @alias module:elements.WebRtcEndpoint#getIceConnectionState
  15024. *
  15025. * @param {module:elements.WebRtcEndpoint~getIceConnectionStateCallback} [callback]
  15026. *
  15027. * @return {external:Promise}
  15028. */
  15029. WebRtcEndpoint.prototype.getIceConnectionState = function(callback){
  15030. var transaction = (arguments[0] instanceof Transaction)
  15031. ? Array.prototype.shift.apply(arguments)
  15032. : undefined;
  15033. var usePromise = false;
  15034. if (callback == undefined) {
  15035. usePromise = true;
  15036. }
  15037. if(!arguments.length) callback = undefined;
  15038. callback = (callback || noop).bind(this)
  15039. return disguise(this._invoke(transaction, 'getIceConnectionState', callback), this)
  15040. };
  15041. /**
  15042. * @callback module:elements.WebRtcEndpoint~getIceConnectionStateCallback
  15043. * @param {external:Error} error
  15044. * @param {module:elements/complexTypes.IceConnection} result
  15045. */
  15046. /**
  15047. * Local network interfaces used for ICE gathering.
  15048. * <p>
  15049. * If you know which network interfaces should be used to perform ICE (for
  15050. * WebRTC
  15051. * connectivity), you can define them here. Doing so has several advantages:
  15052. * </p>
  15053. * <ul>
  15054. * <li>
  15055. * The WebRTC ICE gathering process will be much quicker. Normally, it needs
  15056. * gather local candidates for all of the network interfaces, but this step
  15057. * can
  15058. * be made faster if you limit it to only the interface that you know will
  15059. * work.
  15060. * </li>
  15061. * <li>
  15062. * It will ensure that the media server always decides to use the correct
  15063. * network interface. With WebRTC ICE gathering it's possible that, under
  15064. * some
  15065. * circumstances (in systems with virtual network interfaces such as
  15066. * <code>docker0</code>) the ICE process ends up choosing the wrong local
  15067. * IP.
  15068. * </li>
  15069. * </ul>
  15070. * <p>
  15071. * <code>networkInterfaces</code> is a comma-separated list of network
  15072. * interface
  15073. * names.
  15074. * </p>
  15075. * <p>Examples:</p>
  15076. * <ul>
  15077. * <li><code>networkInterfaces=eth0</code></li>
  15078. * <li><code>networkInterfaces=eth0,enp0s25</code></li>
  15079. * </ul>
  15080. *
  15081. * @alias module:elements.WebRtcEndpoint#getNetworkInterfaces
  15082. *
  15083. * @param {module:elements.WebRtcEndpoint~getNetworkInterfacesCallback} [callback]
  15084. *
  15085. * @return {external:Promise}
  15086. */
  15087. WebRtcEndpoint.prototype.getNetworkInterfaces = function(callback){
  15088. var transaction = (arguments[0] instanceof Transaction)
  15089. ? Array.prototype.shift.apply(arguments)
  15090. : undefined;
  15091. var usePromise = false;
  15092. if (callback == undefined) {
  15093. usePromise = true;
  15094. }
  15095. if(!arguments.length) callback = undefined;
  15096. callback = (callback || noop).bind(this)
  15097. return disguise(this._invoke(transaction, 'getNetworkInterfaces', callback), this)
  15098. };
  15099. /**
  15100. * @callback module:elements.WebRtcEndpoint~getNetworkInterfacesCallback
  15101. * @param {external:Error} error
  15102. * @param {external:String} result
  15103. */
  15104. /**
  15105. * Local network interfaces used for ICE gathering.
  15106. * <p>
  15107. * If you know which network interfaces should be used to perform ICE (for
  15108. * WebRTC
  15109. * connectivity), you can define them here. Doing so has several advantages:
  15110. * </p>
  15111. * <ul>
  15112. * <li>
  15113. * The WebRTC ICE gathering process will be much quicker. Normally, it needs
  15114. * gather local candidates for all of the network interfaces, but this step
  15115. * can
  15116. * be made faster if you limit it to only the interface that you know will
  15117. * work.
  15118. * </li>
  15119. * <li>
  15120. * It will ensure that the media server always decides to use the correct
  15121. * network interface. With WebRTC ICE gathering it's possible that, under
  15122. * some
  15123. * circumstances (in systems with virtual network interfaces such as
  15124. * <code>docker0</code>) the ICE process ends up choosing the wrong local
  15125. * IP.
  15126. * </li>
  15127. * </ul>
  15128. * <p>
  15129. * <code>networkInterfaces</code> is a comma-separated list of network
  15130. * interface
  15131. * names.
  15132. * </p>
  15133. * <p>Examples:</p>
  15134. * <ul>
  15135. * <li><code>networkInterfaces=eth0</code></li>
  15136. * <li><code>networkInterfaces=eth0,enp0s25</code></li>
  15137. * </ul>
  15138. *
  15139. * @alias module:elements.WebRtcEndpoint#setNetworkInterfaces
  15140. *
  15141. * @param {external:String} networkInterfaces
  15142. * @param {module:elements.WebRtcEndpoint~setNetworkInterfacesCallback} [callback]
  15143. *
  15144. * @return {external:Promise}
  15145. */
  15146. WebRtcEndpoint.prototype.setNetworkInterfaces = function(networkInterfaces, callback){
  15147. var transaction = (arguments[0] instanceof Transaction)
  15148. ? Array.prototype.shift.apply(arguments)
  15149. : undefined;
  15150. //
  15151. // checkType('String', 'networkInterfaces', networkInterfaces, {required: true});
  15152. //
  15153. var params = {
  15154. networkInterfaces: networkInterfaces
  15155. };
  15156. callback = (callback || noop).bind(this)
  15157. return disguise(this._invoke(transaction, 'setNetworkInterfaces', params, callback), this)
  15158. };
  15159. /**
  15160. * @callback module:elements.WebRtcEndpoint~setNetworkInterfacesCallback
  15161. * @param {external:Error} error
  15162. */
  15163. /**
  15164. * STUN server IP address.
  15165. * <p>The ICE process uses STUN to punch holes through NAT firewalls.</p>
  15166. * <p>
  15167. * <code>stunServerAddress</code> MUST be an IP address; domain names are NOT
  15168. * supported.
  15169. * </p>
  15170. * <p>
  15171. * You need to use a well-working STUN server. Use this to check if it
  15172. * works:<br />
  15173. * https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/<br
  15174. * From that check, you should get at least one Server-Reflexive Candidate
  15175. * (type
  15176. * <code>srflx</code>).
  15177. * </p>
  15178. *
  15179. * @alias module:elements.WebRtcEndpoint#getStunServerAddress
  15180. *
  15181. * @param {module:elements.WebRtcEndpoint~getStunServerAddressCallback} [callback]
  15182. *
  15183. * @return {external:Promise}
  15184. */
  15185. WebRtcEndpoint.prototype.getStunServerAddress = function(callback){
  15186. var transaction = (arguments[0] instanceof Transaction)
  15187. ? Array.prototype.shift.apply(arguments)
  15188. : undefined;
  15189. var usePromise = false;
  15190. if (callback == undefined) {
  15191. usePromise = true;
  15192. }
  15193. if(!arguments.length) callback = undefined;
  15194. callback = (callback || noop).bind(this)
  15195. return disguise(this._invoke(transaction, 'getStunServerAddress', callback), this)
  15196. };
  15197. /**
  15198. * @callback module:elements.WebRtcEndpoint~getStunServerAddressCallback
  15199. * @param {external:Error} error
  15200. * @param {external:String} result
  15201. */
  15202. /**
  15203. * STUN server IP address.
  15204. * <p>The ICE process uses STUN to punch holes through NAT firewalls.</p>
  15205. * <p>
  15206. * <code>stunServerAddress</code> MUST be an IP address; domain names are NOT
  15207. * supported.
  15208. * </p>
  15209. * <p>
  15210. * You need to use a well-working STUN server. Use this to check if it
  15211. * works:<br />
  15212. * https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/<br
  15213. * From that check, you should get at least one Server-Reflexive Candidate
  15214. * (type
  15215. * <code>srflx</code>).
  15216. * </p>
  15217. *
  15218. * @alias module:elements.WebRtcEndpoint#setStunServerAddress
  15219. *
  15220. * @param {external:String} stunServerAddress
  15221. * @param {module:elements.WebRtcEndpoint~setStunServerAddressCallback} [callback]
  15222. *
  15223. * @return {external:Promise}
  15224. */
  15225. WebRtcEndpoint.prototype.setStunServerAddress = function(stunServerAddress, callback){
  15226. var transaction = (arguments[0] instanceof Transaction)
  15227. ? Array.prototype.shift.apply(arguments)
  15228. : undefined;
  15229. //
  15230. // checkType('String', 'stunServerAddress', stunServerAddress, {required: true});
  15231. //
  15232. var params = {
  15233. stunServerAddress: stunServerAddress
  15234. };
  15235. callback = (callback || noop).bind(this)
  15236. return disguise(this._invoke(transaction, 'setStunServerAddress', params, callback), this)
  15237. };
  15238. /**
  15239. * @callback module:elements.WebRtcEndpoint~setStunServerAddressCallback
  15240. * @param {external:Error} error
  15241. */
  15242. /**
  15243. * Port of the STUN server
  15244. *
  15245. * @alias module:elements.WebRtcEndpoint#getStunServerPort
  15246. *
  15247. * @param {module:elements.WebRtcEndpoint~getStunServerPortCallback} [callback]
  15248. *
  15249. * @return {external:Promise}
  15250. */
  15251. WebRtcEndpoint.prototype.getStunServerPort = function(callback){
  15252. var transaction = (arguments[0] instanceof Transaction)
  15253. ? Array.prototype.shift.apply(arguments)
  15254. : undefined;
  15255. var usePromise = false;
  15256. if (callback == undefined) {
  15257. usePromise = true;
  15258. }
  15259. if(!arguments.length) callback = undefined;
  15260. callback = (callback || noop).bind(this)
  15261. return disguise(this._invoke(transaction, 'getStunServerPort', callback), this)
  15262. };
  15263. /**
  15264. * @callback module:elements.WebRtcEndpoint~getStunServerPortCallback
  15265. * @param {external:Error} error
  15266. * @param {external:Integer} result
  15267. */
  15268. /**
  15269. * Port of the STUN server
  15270. *
  15271. * @alias module:elements.WebRtcEndpoint#setStunServerPort
  15272. *
  15273. * @param {external:Integer} stunServerPort
  15274. * @param {module:elements.WebRtcEndpoint~setStunServerPortCallback} [callback]
  15275. *
  15276. * @return {external:Promise}
  15277. */
  15278. WebRtcEndpoint.prototype.setStunServerPort = function(stunServerPort, callback){
  15279. var transaction = (arguments[0] instanceof Transaction)
  15280. ? Array.prototype.shift.apply(arguments)
  15281. : undefined;
  15282. //
  15283. // checkType('int', 'stunServerPort', stunServerPort, {required: true});
  15284. //
  15285. var params = {
  15286. stunServerPort: stunServerPort
  15287. };
  15288. callback = (callback || noop).bind(this)
  15289. return disguise(this._invoke(transaction, 'setStunServerPort', params, callback), this)
  15290. };
  15291. /**
  15292. * @callback module:elements.WebRtcEndpoint~setStunServerPortCallback
  15293. * @param {external:Error} error
  15294. */
  15295. /**
  15296. * TURN server URL.
  15297. * <p>
  15298. * When STUN is not enough to open connections through some NAT firewalls,
  15299. * using
  15300. * TURN is the remaining alternative.
  15301. * </p>
  15302. * <p>
  15303. * Note that TURN is a superset of STUN, so you don't need to configure STUN
  15304. * if
  15305. * you are using TURN.
  15306. * </p>
  15307. * <p>The provided URL should follow one of these formats:</p>
  15308. * <ul>
  15309. * <li><code>user:password@ipaddress:port</code></li>
  15310. * <li>
  15311. * <code>user:password@ipaddress:port?transport=[udp|tcp|tls]</code>
  15312. * </li>
  15313. * </ul>
  15314. * <p>
  15315. * <code>ipaddress</code> MUST be an IP address; domain names are NOT
  15316. * supported.<br />
  15317. * <code>transport</code> is OPTIONAL. Possible values: udp, tcp, tls.
  15318. * Default: udp.
  15319. * </p>
  15320. * <p>
  15321. * You need to use a well-working TURN server. Use this to check if it
  15322. * works:<br />
  15323. * https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/<br
  15324. * From that check, you should get at least one Server-Reflexive Candidate
  15325. * (type
  15326. * <code>srflx</code>) AND one Relay Candidate (type <code>relay</code>).
  15327. * </p>
  15328. *
  15329. * @alias module:elements.WebRtcEndpoint#getTurnUrl
  15330. *
  15331. * @param {module:elements.WebRtcEndpoint~getTurnUrlCallback} [callback]
  15332. *
  15333. * @return {external:Promise}
  15334. */
  15335. WebRtcEndpoint.prototype.getTurnUrl = function(callback){
  15336. var transaction = (arguments[0] instanceof Transaction)
  15337. ? Array.prototype.shift.apply(arguments)
  15338. : undefined;
  15339. var usePromise = false;
  15340. if (callback == undefined) {
  15341. usePromise = true;
  15342. }
  15343. if(!arguments.length) callback = undefined;
  15344. callback = (callback || noop).bind(this)
  15345. return disguise(this._invoke(transaction, 'getTurnUrl', callback), this)
  15346. };
  15347. /**
  15348. * @callback module:elements.WebRtcEndpoint~getTurnUrlCallback
  15349. * @param {external:Error} error
  15350. * @param {external:String} result
  15351. */
  15352. /**
  15353. * TURN server URL.
  15354. * <p>
  15355. * When STUN is not enough to open connections through some NAT firewalls,
  15356. * using
  15357. * TURN is the remaining alternative.
  15358. * </p>
  15359. * <p>
  15360. * Note that TURN is a superset of STUN, so you don't need to configure STUN
  15361. * if
  15362. * you are using TURN.
  15363. * </p>
  15364. * <p>The provided URL should follow one of these formats:</p>
  15365. * <ul>
  15366. * <li><code>user:password@ipaddress:port</code></li>
  15367. * <li>
  15368. * <code>user:password@ipaddress:port?transport=[udp|tcp|tls]</code>
  15369. * </li>
  15370. * </ul>
  15371. * <p>
  15372. * <code>ipaddress</code> MUST be an IP address; domain names are NOT
  15373. * supported.<br />
  15374. * <code>transport</code> is OPTIONAL. Possible values: udp, tcp, tls.
  15375. * Default: udp.
  15376. * </p>
  15377. * <p>
  15378. * You need to use a well-working TURN server. Use this to check if it
  15379. * works:<br />
  15380. * https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/<br
  15381. * From that check, you should get at least one Server-Reflexive Candidate
  15382. * (type
  15383. * <code>srflx</code>) AND one Relay Candidate (type <code>relay</code>).
  15384. * </p>
  15385. *
  15386. * @alias module:elements.WebRtcEndpoint#setTurnUrl
  15387. *
  15388. * @param {external:String} turnUrl
  15389. * @param {module:elements.WebRtcEndpoint~setTurnUrlCallback} [callback]
  15390. *
  15391. * @return {external:Promise}
  15392. */
  15393. WebRtcEndpoint.prototype.setTurnUrl = function(turnUrl, callback){
  15394. var transaction = (arguments[0] instanceof Transaction)
  15395. ? Array.prototype.shift.apply(arguments)
  15396. : undefined;
  15397. //
  15398. // checkType('String', 'turnUrl', turnUrl, {required: true});
  15399. //
  15400. var params = {
  15401. turnUrl: turnUrl
  15402. };
  15403. callback = (callback || noop).bind(this)
  15404. return disguise(this._invoke(transaction, 'setTurnUrl', params, callback), this)
  15405. };
  15406. /**
  15407. * @callback module:elements.WebRtcEndpoint~setTurnUrlCallback
  15408. * @param {external:Error} error
  15409. */
  15410. //
  15411. // Public methods
  15412. //
  15413. /**
  15414. * Process an ICE candidate sent by the remote peer of the connection.
  15415. *
  15416. * @alias module:elements.WebRtcEndpoint.addIceCandidate
  15417. *
  15418. * @param {module:elements/complexTypes.IceCandidate} candidate
  15419. * Remote ICE candidate
  15420. *
  15421. * @param {module:elements.WebRtcEndpoint~addIceCandidateCallback} [callback]
  15422. *
  15423. * @return {external:Promise}
  15424. */
  15425. WebRtcEndpoint.prototype.addIceCandidate = function(candidate, callback){
  15426. var transaction = (arguments[0] instanceof Transaction)
  15427. ? Array.prototype.shift.apply(arguments)
  15428. : undefined;
  15429. //
  15430. // checkType('IceCandidate', 'candidate', candidate, {required: true});
  15431. //
  15432. var params = {
  15433. candidate: candidate
  15434. };
  15435. callback = (callback || noop).bind(this)
  15436. return disguise(this._invoke(transaction, 'addIceCandidate', params, callback), this)
  15437. };
  15438. /**
  15439. * @callback module:elements.WebRtcEndpoint~addIceCandidateCallback
  15440. * @param {external:Error} error
  15441. */
  15442. /**
  15443. * Closes an open data channel
  15444. *
  15445. * @alias module:elements.WebRtcEndpoint.closeDataChannel
  15446. *
  15447. * @param {external:Integer} channelId
  15448. * The channel identifier
  15449. *
  15450. * @param {module:elements.WebRtcEndpoint~closeDataChannelCallback} [callback]
  15451. *
  15452. * @return {external:Promise}
  15453. */
  15454. WebRtcEndpoint.prototype.closeDataChannel = function(channelId, callback){
  15455. var transaction = (arguments[0] instanceof Transaction)
  15456. ? Array.prototype.shift.apply(arguments)
  15457. : undefined;
  15458. //
  15459. // checkType('int', 'channelId', channelId, {required: true});
  15460. //
  15461. var params = {
  15462. channelId: channelId
  15463. };
  15464. callback = (callback || noop).bind(this)
  15465. return disguise(this._invoke(transaction, 'closeDataChannel', params, callback), this)
  15466. };
  15467. /**
  15468. * @callback module:elements.WebRtcEndpoint~closeDataChannelCallback
  15469. * @param {external:Error} error
  15470. */
  15471. /**
  15472. * Create a new data channel, if data channels are supported.
  15473. * <p>
  15474. * Being supported means that the WebRtcEndpoint has been created with data
  15475. * channel support, the client also supports data channels, and they have been
  15476. * negotiated in the SDP exchange. Otherwise, the method throws an exception,
  15477. * indicating that the operation is not possible.
  15478. * </p>
  15479. * <p>
  15480. * Data channels can work in either unreliable mode (analogous to User
  15481. * Datagram
  15482. * Protocol or UDP) or reliable mode (analogous to Transmission Control
  15483. * Protocol
  15484. * or TCP). The two modes have a simple distinction:
  15485. * </p>
  15486. * <ul>
  15487. * <li>
  15488. * Reliable mode guarantees the transmission of messages and also the order
  15489. * in
  15490. * which they are delivered. This takes extra overhead, thus potentially
  15491. * making
  15492. * this mode slower.
  15493. * </li>
  15494. * <li>
  15495. * Unreliable mode does not guarantee every message will get to the other
  15496. * side
  15497. * nor what order they get there. This removes the overhead, allowing this
  15498. * mode
  15499. * to work much faster.
  15500. * </li>
  15501. * </ul>
  15502. * <p>If data channels are not supported, this method throws an exception.</p>
  15503. *
  15504. * @alias module:elements.WebRtcEndpoint.createDataChannel
  15505. *
  15506. * @param {external:String} [label]
  15507. * Channel's label
  15508. *
  15509. * @param {external:Boolean} [ordered]
  15510. * If the data channel should guarantee order or not. If true, and
  15511. * maxPacketLifeTime and maxRetransmits have not been provided, reliable mode
  15512. * is activated.
  15513. *
  15514. * @param {external:Integer} [maxPacketLifeTime]
  15515. * The time window (in milliseconds) during which transmissions and
  15516. * retransmissions may take place in unreliable mode.
  15517. * Note that this forces unreliable mode, even if <code>ordered</code> has been
  15518. *
  15519. * @param {external:Integer} [maxRetransmits]
  15520. * maximum number of retransmissions that are attempted in unreliable mode.
  15521. * Note that this forces unreliable mode, even if <code>ordered</code> has been
  15522. *
  15523. * @param {external:String} [protocol]
  15524. * Name of the subprotocol used for data communication
  15525. *
  15526. * @param {module:elements.WebRtcEndpoint~createDataChannelCallback} [callback]
  15527. *
  15528. * @return {external:Promise}
  15529. */
  15530. WebRtcEndpoint.prototype.createDataChannel = function(label, ordered, maxPacketLifeTime, maxRetransmits, protocol, callback){
  15531. var transaction = (arguments[0] instanceof Transaction)
  15532. ? Array.prototype.shift.apply(arguments)
  15533. : undefined;
  15534. callback = arguments[arguments.length-1] instanceof Function
  15535. ? Array.prototype.pop.call(arguments)
  15536. : undefined;
  15537. switch(arguments.length){
  15538. case 0: label = undefined;
  15539. case 1: ordered = undefined;
  15540. case 2: maxPacketLifeTime = undefined;
  15541. case 3: maxRetransmits = undefined;
  15542. case 4: protocol = undefined;
  15543. break;
  15544. case 5:
  15545. break;
  15546. default:
  15547. var error = new RangeError('Number of params ('+arguments.length+') not in range [0-5]');
  15548. error.length = arguments.length;
  15549. error.min = 0;
  15550. error.max = 5;
  15551. throw error;
  15552. }
  15553. //
  15554. // checkType('String', 'label', label);
  15555. //
  15556. // checkType('boolean', 'ordered', ordered);
  15557. //
  15558. // checkType('int', 'maxPacketLifeTime', maxPacketLifeTime);
  15559. //
  15560. // checkType('int', 'maxRetransmits', maxRetransmits);
  15561. //
  15562. // checkType('String', 'protocol', protocol);
  15563. //
  15564. var params = {
  15565. label: label,
  15566. ordered: ordered,
  15567. maxPacketLifeTime: maxPacketLifeTime,
  15568. maxRetransmits: maxRetransmits,
  15569. protocol: protocol
  15570. };
  15571. callback = (callback || noop).bind(this)
  15572. return disguise(this._invoke(transaction, 'createDataChannel', params, callback), this)
  15573. };
  15574. /**
  15575. * @callback module:elements.WebRtcEndpoint~createDataChannelCallback
  15576. * @param {external:Error} error
  15577. */
  15578. /**
  15579. * Start the gathering of ICE candidates.
  15580. * <p>
  15581. * It must be called after <code>SdpEndpoint::generateOffer</code> or
  15582. * <code>SdpEndpoint::processOffer</code> for <strong>Trickle ICE</strong>. If
  15583. * invoked before generating or processing an SDP offer, the candidates
  15584. * gathered
  15585. * will be added to the SDP processed.
  15586. * </p>
  15587. *
  15588. * @alias module:elements.WebRtcEndpoint.gatherCandidates
  15589. *
  15590. * @param {module:elements.WebRtcEndpoint~gatherCandidatesCallback} [callback]
  15591. *
  15592. * @return {external:Promise}
  15593. */
  15594. WebRtcEndpoint.prototype.gatherCandidates = function(callback){
  15595. var transaction = (arguments[0] instanceof Transaction)
  15596. ? Array.prototype.shift.apply(arguments)
  15597. : undefined;
  15598. var usePromise = false;
  15599. if (callback == undefined) {
  15600. usePromise = true;
  15601. }
  15602. if(!arguments.length) callback = undefined;
  15603. callback = (callback || noop).bind(this)
  15604. return disguise(this._invoke(transaction, 'gatherCandidates', callback), this)
  15605. };
  15606. /**
  15607. * @callback module:elements.WebRtcEndpoint~gatherCandidatesCallback
  15608. * @param {external:Error} error
  15609. */
  15610. /**
  15611. * @alias module:elements.WebRtcEndpoint.constructorParams
  15612. *
  15613. * @property {module:elements/complexTypes.CertificateKeyType} [certificateKeyType]
  15614. * Define the type of the certificate used in dtls
  15615. *
  15616. * @property {module:core.MediaPipeline} mediaPipeline
  15617. * the {@link module:core.MediaPipeline MediaPipeline} to which the endpoint
  15618. * belongs
  15619. *
  15620. * @property {external:Boolean} [recvonly]
  15621. * Single direction, receive-only endpoint
  15622. *
  15623. * @property {external:Boolean} [sendonly]
  15624. * Single direction, send-only endpoint
  15625. *
  15626. * @property {external:Boolean} [useDataChannels]
  15627. * Activate data channels support
  15628. */
  15629. WebRtcEndpoint.constructorParams = {
  15630. certificateKeyType: {
  15631. type: 'kurento.CertificateKeyType' },
  15632. mediaPipeline: {
  15633. type: 'kurento.MediaPipeline',
  15634. required: true
  15635. },
  15636. recvonly: {
  15637. type: 'boolean' },
  15638. sendonly: {
  15639. type: 'boolean' },
  15640. useDataChannels: {
  15641. type: 'boolean' }
  15642. };
  15643. /**
  15644. * @alias module:elements.WebRtcEndpoint.events
  15645. *
  15646. * @extends module:core/abstracts.BaseRtpEndpoint.events
  15647. */
  15648. WebRtcEndpoint.events = BaseRtpEndpoint.events.concat(['DataChannelClose', 'DataChannelOpen', 'IceCandidateFound', 'IceComponentStateChange', 'IceGatheringDone', 'NewCandidatePairSelected', 'OnDataChannelClosed', 'OnDataChannelOpened', 'OnIceCandidate', 'OnIceComponentStateChanged', 'OnIceGatheringDone']);
  15649. /**
  15650. * Checker for {@link module:elements.WebRtcEndpoint}
  15651. *
  15652. * @memberof module:elements
  15653. *
  15654. * @param {external:String} key
  15655. * @param {module:elements.WebRtcEndpoint} value
  15656. */
  15657. function checkWebRtcEndpoint(key, value)
  15658. {
  15659. if(!(value instanceof WebRtcEndpoint))
  15660. throw ChecktypeError(key, WebRtcEndpoint, value);
  15661. };
  15662. module.exports = WebRtcEndpoint;
  15663. WebRtcEndpoint.check = checkWebRtcEndpoint;
  15664. },{"inherits":"inherits","kurento-client":"kurento-client","kurento-client-core":"kurento-client-core"}],94:[function(require,module,exports){
  15665. /* Autogenerated with Kurento Idl */
  15666. /*
  15667. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  15668. *
  15669. * Licensed under the Apache License, Version 2.0 (the "License");
  15670. * you may not use this file except in compliance with the License.
  15671. * You may obtain a copy of the License at
  15672. *
  15673. * http://www.apache.org/licenses/LICENSE-2.0
  15674. *
  15675. * Unless required by applicable law or agreed to in writing, software
  15676. * distributed under the License is distributed on an "AS IS" BASIS,
  15677. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15678. * See the License for the specific language governing permissions and
  15679. * limitations under the License.
  15680. */
  15681. var inherits = require('inherits');
  15682. var kurentoClient = require('kurento-client');
  15683. var disguise = kurentoClient.disguise;
  15684. var checkType = kurentoClient.checkType;
  15685. var ChecktypeError = checkType.ChecktypeError;
  15686. var Transaction = kurentoClient.TransactionsManager.Transaction;
  15687. var SessionEndpoint = require('kurento-client-core').abstracts.SessionEndpoint;
  15688. function noop(error, result) {
  15689. if (error) console.trace(error);
  15690. return result
  15691. };
  15692. /**
  15693. * @classdesc
  15694. * Endpoint that enables Kurento to work as an HTTP server, allowing peer HTTP
  15695. * clients to access media.
  15696. *
  15697. * @abstract
  15698. * @extends module:core/abstracts.SessionEndpoint
  15699. *
  15700. * @constructor module:elements/abstracts.HttpEndpoint
  15701. */
  15702. function HttpEndpoint(){
  15703. HttpEndpoint.super_.call(this);
  15704. };
  15705. inherits(HttpEndpoint, SessionEndpoint);
  15706. //
  15707. // Public methods
  15708. //
  15709. /**
  15710. * Obtains the URL associated to this endpoint
  15711. *
  15712. * @alias module:elements/abstracts.HttpEndpoint.getUrl
  15713. *
  15714. * @param {module:elements/abstracts.HttpEndpoint~getUrlCallback} [callback]
  15715. *
  15716. * @return {external:Promise}
  15717. */
  15718. HttpEndpoint.prototype.getUrl = function(callback){
  15719. var transaction = (arguments[0] instanceof Transaction)
  15720. ? Array.prototype.shift.apply(arguments)
  15721. : undefined;
  15722. var usePromise = false;
  15723. if (callback == undefined) {
  15724. usePromise = true;
  15725. }
  15726. if(!arguments.length) callback = undefined;
  15727. callback = (callback || noop).bind(this)
  15728. return disguise(this._invoke(transaction, 'getUrl', callback), this)
  15729. };
  15730. /**
  15731. * @callback module:elements/abstracts.HttpEndpoint~getUrlCallback
  15732. * @param {external:Error} error
  15733. * @param {external:String} result
  15734. * The url as a String
  15735. */
  15736. /**
  15737. * @alias module:elements/abstracts.HttpEndpoint.constructorParams
  15738. */
  15739. HttpEndpoint.constructorParams = {
  15740. };
  15741. /**
  15742. * @alias module:elements/abstracts.HttpEndpoint.events
  15743. *
  15744. * @extends module:core/abstracts.SessionEndpoint.events
  15745. */
  15746. HttpEndpoint.events = SessionEndpoint.events;
  15747. /**
  15748. * Checker for {@link module:elements/abstracts.HttpEndpoint}
  15749. *
  15750. * @memberof module:elements/abstracts
  15751. *
  15752. * @param {external:String} key
  15753. * @param {module:elements/abstracts.HttpEndpoint} value
  15754. */
  15755. function checkHttpEndpoint(key, value)
  15756. {
  15757. if(!(value instanceof HttpEndpoint))
  15758. throw ChecktypeError(key, HttpEndpoint, value);
  15759. };
  15760. module.exports = HttpEndpoint;
  15761. HttpEndpoint.check = checkHttpEndpoint;
  15762. },{"inherits":"inherits","kurento-client":"kurento-client","kurento-client-core":"kurento-client-core"}],95:[function(require,module,exports){
  15763. /* Autogenerated with Kurento Idl */
  15764. /*
  15765. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  15766. *
  15767. * Licensed under the Apache License, Version 2.0 (the "License");
  15768. * you may not use this file except in compliance with the License.
  15769. * You may obtain a copy of the License at
  15770. *
  15771. * http://www.apache.org/licenses/LICENSE-2.0
  15772. *
  15773. * Unless required by applicable law or agreed to in writing, software
  15774. * distributed under the License is distributed on an "AS IS" BASIS,
  15775. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15776. * See the License for the specific language governing permissions and
  15777. * limitations under the License.
  15778. */
  15779. /**
  15780. * Media API for the Kurento Web SDK
  15781. *
  15782. * @module elements/abstracts
  15783. *
  15784. * @copyright 2013-2015 Kurento (http://kurento.org/)
  15785. * @license ALv2
  15786. */
  15787. var HttpEndpoint = require('./HttpEndpoint');
  15788. exports.HttpEndpoint = HttpEndpoint;
  15789. },{"./HttpEndpoint":94}],96:[function(require,module,exports){
  15790. /* Autogenerated with Kurento Idl */
  15791. /*
  15792. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  15793. *
  15794. * Licensed under the Apache License, Version 2.0 (the "License");
  15795. * you may not use this file except in compliance with the License.
  15796. * You may obtain a copy of the License at
  15797. *
  15798. * http://www.apache.org/licenses/LICENSE-2.0
  15799. *
  15800. * Unless required by applicable law or agreed to in writing, software
  15801. * distributed under the License is distributed on an "AS IS" BASIS,
  15802. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15803. * See the License for the specific language governing permissions and
  15804. * limitations under the License.
  15805. */
  15806. var kurentoClient = require('kurento-client');
  15807. /**
  15808. * .
  15809. *
  15810. * @typedef elements/complexTypes.CertificateKeyType
  15811. *
  15812. * @type {(RSA|ECDSA)}
  15813. */
  15814. /**
  15815. * Checker for {@link module:elements/complexTypes.CertificateKeyType}
  15816. *
  15817. * @memberof module:elements/complexTypes
  15818. *
  15819. * @param {external:String} key
  15820. * @param {module:elements/complexTypes.CertificateKeyType} value
  15821. */
  15822. function checkCertificateKeyType(key, value)
  15823. {
  15824. if(typeof value != 'string')
  15825. throw SyntaxError(key+' param should be a String, not '+typeof value);
  15826. if(!value.match('RSA|ECDSA'))
  15827. throw SyntaxError(key+' param is not one of [RSA|ECDSA] ('+value+')');
  15828. };
  15829. module.exports = checkCertificateKeyType;
  15830. },{"kurento-client":"kurento-client"}],97:[function(require,module,exports){
  15831. /* Autogenerated with Kurento Idl */
  15832. /*
  15833. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  15834. *
  15835. * Licensed under the Apache License, Version 2.0 (the "License");
  15836. * you may not use this file except in compliance with the License.
  15837. * You may obtain a copy of the License at
  15838. *
  15839. * http://www.apache.org/licenses/LICENSE-2.0
  15840. *
  15841. * Unless required by applicable law or agreed to in writing, software
  15842. * distributed under the License is distributed on an "AS IS" BASIS,
  15843. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15844. * See the License for the specific language governing permissions and
  15845. * limitations under the License.
  15846. */
  15847. var kurentoClient = require('kurento-client');
  15848. /**
  15849. * Describes the encryption and authentication algorithms
  15850. *
  15851. * @typedef elements/complexTypes.CryptoSuite
  15852. *
  15853. * @type {(AES_128_CM_HMAC_SHA1_32|AES_128_CM_HMAC_SHA1_80|AES_256_CM_HMAC_SHA1_32|AES_256_CM_HMAC_SHA1_80)}
  15854. */
  15855. /**
  15856. * Checker for {@link module:elements/complexTypes.CryptoSuite}
  15857. *
  15858. * @memberof module:elements/complexTypes
  15859. *
  15860. * @param {external:String} key
  15861. * @param {module:elements/complexTypes.CryptoSuite} value
  15862. */
  15863. function checkCryptoSuite(key, value)
  15864. {
  15865. if(typeof value != 'string')
  15866. throw SyntaxError(key+' param should be a String, not '+typeof value);
  15867. if(!value.match('AES_128_CM_HMAC_SHA1_32|AES_128_CM_HMAC_SHA1_80|AES_256_CM_HMAC_SHA1_32|AES_256_CM_HMAC_SHA1_80'))
  15868. throw SyntaxError(key+' param is not one of [AES_128_CM_HMAC_SHA1_32|AES_128_CM_HMAC_SHA1_80|AES_256_CM_HMAC_SHA1_32|AES_256_CM_HMAC_SHA1_80] ('+value+')');
  15869. };
  15870. module.exports = checkCryptoSuite;
  15871. },{"kurento-client":"kurento-client"}],98:[function(require,module,exports){
  15872. /* Autogenerated with Kurento Idl */
  15873. /*
  15874. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  15875. *
  15876. * Licensed under the Apache License, Version 2.0 (the "License");
  15877. * you may not use this file except in compliance with the License.
  15878. * You may obtain a copy of the License at
  15879. *
  15880. * http://www.apache.org/licenses/LICENSE-2.0
  15881. *
  15882. * Unless required by applicable law or agreed to in writing, software
  15883. * distributed under the License is distributed on an "AS IS" BASIS,
  15884. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15885. * See the License for the specific language governing permissions and
  15886. * limitations under the License.
  15887. */
  15888. var inherits = require('inherits');
  15889. var kurentoClient = require('kurento-client');
  15890. var checkType = kurentoClient.checkType;
  15891. var ChecktypeError = checkType.ChecktypeError;
  15892. var ComplexType = require('kurento-client-core').complexTypes.ComplexType;
  15893. /**
  15894. * IceCandidate representation based on <code>RTCIceCandidate</code> interface.
  15895. * @see https://www.w3.org/TR/2018/CR-webrtc-20180927/#rtcicecandidate-interface
  15896. *
  15897. * @constructor module:elements/complexTypes.IceCandidate
  15898. *
  15899. * @property {external:String} candidate
  15900. * The candidate-attribute as defined in section 15.1 of ICE (rfc5245).
  15901. * @property {external:String} sdpMid
  15902. * If present, this contains the identifier of the 'media stream
  15903. * identification'.
  15904. * @property {external:Integer} sdpMLineIndex
  15905. * The index (starting at zero) of the m-line in the SDP this candidate is
  15906. * associated with.
  15907. */
  15908. function IceCandidate(iceCandidateDict){
  15909. if(!(this instanceof IceCandidate))
  15910. return new IceCandidate(iceCandidateDict)
  15911. iceCandidateDict = iceCandidateDict || {}
  15912. // Check iceCandidateDict has the required fields
  15913. //
  15914. // checkType('String', 'iceCandidateDict.candidate', iceCandidateDict.candidate, {required: true});
  15915. //
  15916. // checkType('String', 'iceCandidateDict.sdpMid', iceCandidateDict.sdpMid, {required: true});
  15917. //
  15918. // checkType('int', 'iceCandidateDict.sdpMLineIndex', iceCandidateDict.sdpMLineIndex, {required: true});
  15919. //
  15920. // Init parent class
  15921. IceCandidate.super_.call(this, iceCandidateDict)
  15922. // Set object properties
  15923. Object.defineProperties(this, {
  15924. candidate: {
  15925. writable: true,
  15926. enumerable: true,
  15927. value: iceCandidateDict.candidate
  15928. },
  15929. sdpMid: {
  15930. writable: true,
  15931. enumerable: true,
  15932. value: iceCandidateDict.sdpMid
  15933. },
  15934. sdpMLineIndex: {
  15935. writable: true,
  15936. enumerable: true,
  15937. value: iceCandidateDict.sdpMLineIndex
  15938. }
  15939. })
  15940. }
  15941. inherits(IceCandidate, ComplexType)
  15942. // Private identifiers to allow re-construction of the complexType on the server
  15943. // They need to be enumerable so JSON.stringify() can access to them
  15944. Object.defineProperties(IceCandidate.prototype, {
  15945. __module__: {
  15946. enumerable: true,
  15947. value: "kurento"
  15948. },
  15949. __type__: {
  15950. enumerable: true,
  15951. value: "IceCandidate"
  15952. }
  15953. })
  15954. /**
  15955. * Checker for {@link module:elements/complexTypes.IceCandidate}
  15956. *
  15957. * @memberof module:elements/complexTypes
  15958. *
  15959. * @param {external:String} key
  15960. * @param {module:elements/complexTypes.IceCandidate} value
  15961. */
  15962. function checkIceCandidate(key, value)
  15963. {
  15964. if(!(value instanceof IceCandidate))
  15965. throw ChecktypeError(key, IceCandidate, value);
  15966. };
  15967. module.exports = IceCandidate;
  15968. IceCandidate.check = checkIceCandidate;
  15969. },{"inherits":"inherits","kurento-client":"kurento-client","kurento-client-core":"kurento-client-core"}],99:[function(require,module,exports){
  15970. /* Autogenerated with Kurento Idl */
  15971. /*
  15972. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  15973. *
  15974. * Licensed under the Apache License, Version 2.0 (the "License");
  15975. * you may not use this file except in compliance with the License.
  15976. * You may obtain a copy of the License at
  15977. *
  15978. * http://www.apache.org/licenses/LICENSE-2.0
  15979. *
  15980. * Unless required by applicable law or agreed to in writing, software
  15981. * distributed under the License is distributed on an "AS IS" BASIS,
  15982. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15983. * See the License for the specific language governing permissions and
  15984. * limitations under the License.
  15985. */
  15986. var inherits = require('inherits');
  15987. var kurentoClient = require('kurento-client');
  15988. var checkType = kurentoClient.checkType;
  15989. var ChecktypeError = checkType.ChecktypeError;
  15990. var ComplexType = require('kurento-client-core').complexTypes.ComplexType;
  15991. /**
  15992. * The ICE candidate pair used by the ice library, for a certain stream.
  15993. *
  15994. * @constructor module:elements/complexTypes.IceCandidatePair
  15995. *
  15996. * @property {external:String} streamID
  15997. * Stream ID of the ice connection
  15998. * @property {external:Integer} componentID
  15999. * Component ID of the ice connection
  16000. * @property {external:String} localCandidate
  16001. * The local candidate used by the ice library.
  16002. * @property {external:String} remoteCandidate
  16003. * The remote candidate used by the ice library.
  16004. */
  16005. function IceCandidatePair(iceCandidatePairDict){
  16006. if(!(this instanceof IceCandidatePair))
  16007. return new IceCandidatePair(iceCandidatePairDict)
  16008. iceCandidatePairDict = iceCandidatePairDict || {}
  16009. // Check iceCandidatePairDict has the required fields
  16010. //
  16011. // checkType('String', 'iceCandidatePairDict.streamID', iceCandidatePairDict.streamID, {required: true});
  16012. //
  16013. // checkType('int', 'iceCandidatePairDict.componentID', iceCandidatePairDict.componentID, {required: true});
  16014. //
  16015. // checkType('String', 'iceCandidatePairDict.localCandidate', iceCandidatePairDict.localCandidate, {required: true});
  16016. //
  16017. // checkType('String', 'iceCandidatePairDict.remoteCandidate', iceCandidatePairDict.remoteCandidate, {required: true});
  16018. //
  16019. // Init parent class
  16020. IceCandidatePair.super_.call(this, iceCandidatePairDict)
  16021. // Set object properties
  16022. Object.defineProperties(this, {
  16023. streamID: {
  16024. writable: true,
  16025. enumerable: true,
  16026. value: iceCandidatePairDict.streamID
  16027. },
  16028. componentID: {
  16029. writable: true,
  16030. enumerable: true,
  16031. value: iceCandidatePairDict.componentID
  16032. },
  16033. localCandidate: {
  16034. writable: true,
  16035. enumerable: true,
  16036. value: iceCandidatePairDict.localCandidate
  16037. },
  16038. remoteCandidate: {
  16039. writable: true,
  16040. enumerable: true,
  16041. value: iceCandidatePairDict.remoteCandidate
  16042. }
  16043. })
  16044. }
  16045. inherits(IceCandidatePair, ComplexType)
  16046. // Private identifiers to allow re-construction of the complexType on the server
  16047. // They need to be enumerable so JSON.stringify() can access to them
  16048. Object.defineProperties(IceCandidatePair.prototype, {
  16049. __module__: {
  16050. enumerable: true,
  16051. value: "kurento"
  16052. },
  16053. __type__: {
  16054. enumerable: true,
  16055. value: "IceCandidatePair"
  16056. }
  16057. })
  16058. /**
  16059. * Checker for {@link module:elements/complexTypes.IceCandidatePair}
  16060. *
  16061. * @memberof module:elements/complexTypes
  16062. *
  16063. * @param {external:String} key
  16064. * @param {module:elements/complexTypes.IceCandidatePair} value
  16065. */
  16066. function checkIceCandidatePair(key, value)
  16067. {
  16068. if(!(value instanceof IceCandidatePair))
  16069. throw ChecktypeError(key, IceCandidatePair, value);
  16070. };
  16071. module.exports = IceCandidatePair;
  16072. IceCandidatePair.check = checkIceCandidatePair;
  16073. },{"inherits":"inherits","kurento-client":"kurento-client","kurento-client-core":"kurento-client-core"}],100:[function(require,module,exports){
  16074. /* Autogenerated with Kurento Idl */
  16075. /*
  16076. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  16077. *
  16078. * Licensed under the Apache License, Version 2.0 (the "License");
  16079. * you may not use this file except in compliance with the License.
  16080. * You may obtain a copy of the License at
  16081. *
  16082. * http://www.apache.org/licenses/LICENSE-2.0
  16083. *
  16084. * Unless required by applicable law or agreed to in writing, software
  16085. * distributed under the License is distributed on an "AS IS" BASIS,
  16086. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16087. * See the License for the specific language governing permissions and
  16088. * limitations under the License.
  16089. */
  16090. var kurentoClient = require('kurento-client');
  16091. /**
  16092. * States of an ICE component.
  16093. *
  16094. * @typedef elements/complexTypes.IceComponentState
  16095. *
  16096. * @type {(DISCONNECTED|GATHERING|CONNECTING|CONNECTED|READY|FAILED)}
  16097. */
  16098. /**
  16099. * Checker for {@link module:elements/complexTypes.IceComponentState}
  16100. *
  16101. * @memberof module:elements/complexTypes
  16102. *
  16103. * @param {external:String} key
  16104. * @param {module:elements/complexTypes.IceComponentState} value
  16105. */
  16106. function checkIceComponentState(key, value)
  16107. {
  16108. if(typeof value != 'string')
  16109. throw SyntaxError(key+' param should be a String, not '+typeof value);
  16110. if(!value.match('DISCONNECTED|GATHERING|CONNECTING|CONNECTED|READY|FAILED'))
  16111. throw SyntaxError(key+' param is not one of [DISCONNECTED|GATHERING|CONNECTING|CONNECTED|READY|FAILED] ('+value+')');
  16112. };
  16113. module.exports = checkIceComponentState;
  16114. },{"kurento-client":"kurento-client"}],101:[function(require,module,exports){
  16115. /* Autogenerated with Kurento Idl */
  16116. /*
  16117. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  16118. *
  16119. * Licensed under the Apache License, Version 2.0 (the "License");
  16120. * you may not use this file except in compliance with the License.
  16121. * You may obtain a copy of the License at
  16122. *
  16123. * http://www.apache.org/licenses/LICENSE-2.0
  16124. *
  16125. * Unless required by applicable law or agreed to in writing, software
  16126. * distributed under the License is distributed on an "AS IS" BASIS,
  16127. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16128. * See the License for the specific language governing permissions and
  16129. * limitations under the License.
  16130. */
  16131. var inherits = require('inherits');
  16132. var kurentoClient = require('kurento-client');
  16133. var checkType = kurentoClient.checkType;
  16134. var ChecktypeError = checkType.ChecktypeError;
  16135. var ComplexType = require('kurento-client-core').complexTypes.ComplexType;
  16136. /**
  16137. * The ICE connection state for a certain stream and component.
  16138. *
  16139. * @constructor module:elements/complexTypes.IceConnection
  16140. *
  16141. * @property {external:String} streamId
  16142. * The ID of the stream
  16143. * @property {external:Integer} componentId
  16144. * The ID of the component
  16145. * @property {module:elements/complexTypes.IceComponentState} state
  16146. * The state of the component
  16147. */
  16148. function IceConnection(iceConnectionDict){
  16149. if(!(this instanceof IceConnection))
  16150. return new IceConnection(iceConnectionDict)
  16151. iceConnectionDict = iceConnectionDict || {}
  16152. // Check iceConnectionDict has the required fields
  16153. //
  16154. // checkType('String', 'iceConnectionDict.streamId', iceConnectionDict.streamId, {required: true});
  16155. //
  16156. // checkType('int', 'iceConnectionDict.componentId', iceConnectionDict.componentId, {required: true});
  16157. //
  16158. // checkType('IceComponentState', 'iceConnectionDict.state', iceConnectionDict.state, {required: true});
  16159. //
  16160. // Init parent class
  16161. IceConnection.super_.call(this, iceConnectionDict)
  16162. // Set object properties
  16163. Object.defineProperties(this, {
  16164. streamId: {
  16165. writable: true,
  16166. enumerable: true,
  16167. value: iceConnectionDict.streamId
  16168. },
  16169. componentId: {
  16170. writable: true,
  16171. enumerable: true,
  16172. value: iceConnectionDict.componentId
  16173. },
  16174. state: {
  16175. writable: true,
  16176. enumerable: true,
  16177. value: iceConnectionDict.state
  16178. }
  16179. })
  16180. }
  16181. inherits(IceConnection, ComplexType)
  16182. // Private identifiers to allow re-construction of the complexType on the server
  16183. // They need to be enumerable so JSON.stringify() can access to them
  16184. Object.defineProperties(IceConnection.prototype, {
  16185. __module__: {
  16186. enumerable: true,
  16187. value: "kurento"
  16188. },
  16189. __type__: {
  16190. enumerable: true,
  16191. value: "IceConnection"
  16192. }
  16193. })
  16194. /**
  16195. * Checker for {@link module:elements/complexTypes.IceConnection}
  16196. *
  16197. * @memberof module:elements/complexTypes
  16198. *
  16199. * @param {external:String} key
  16200. * @param {module:elements/complexTypes.IceConnection} value
  16201. */
  16202. function checkIceConnection(key, value)
  16203. {
  16204. if(!(value instanceof IceConnection))
  16205. throw ChecktypeError(key, IceConnection, value);
  16206. };
  16207. module.exports = IceConnection;
  16208. IceConnection.check = checkIceConnection;
  16209. },{"inherits":"inherits","kurento-client":"kurento-client","kurento-client-core":"kurento-client-core"}],102:[function(require,module,exports){
  16210. /* Autogenerated with Kurento Idl */
  16211. /*
  16212. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  16213. *
  16214. * Licensed under the Apache License, Version 2.0 (the "License");
  16215. * you may not use this file except in compliance with the License.
  16216. * You may obtain a copy of the License at
  16217. *
  16218. * http://www.apache.org/licenses/LICENSE-2.0
  16219. *
  16220. * Unless required by applicable law or agreed to in writing, software
  16221. * distributed under the License is distributed on an "AS IS" BASIS,
  16222. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16223. * See the License for the specific language governing permissions and
  16224. * limitations under the License.
  16225. */
  16226. var kurentoClient = require('kurento-client');
  16227. /**
  16228. * Media Profile.
  16229. * Currently WEBM, MKV, MP4 and JPEG are supported.
  16230. *
  16231. * @typedef elements/complexTypes.MediaProfileSpecType
  16232. *
  16233. * @type {(WEBM|MKV|MP4|WEBM_VIDEO_ONLY|WEBM_AUDIO_ONLY|MKV_VIDEO_ONLY|MKV_AUDIO_ONLY|MP4_VIDEO_ONLY|MP4_AUDIO_ONLY|JPEG_VIDEO_ONLY|KURENTO_SPLIT_RECORDER)}
  16234. */
  16235. /**
  16236. * Checker for {@link module:elements/complexTypes.MediaProfileSpecType}
  16237. *
  16238. * @memberof module:elements/complexTypes
  16239. *
  16240. * @param {external:String} key
  16241. * @param {module:elements/complexTypes.MediaProfileSpecType} value
  16242. */
  16243. function checkMediaProfileSpecType(key, value)
  16244. {
  16245. if(typeof value != 'string')
  16246. throw SyntaxError(key+' param should be a String, not '+typeof value);
  16247. if(!value.match('WEBM|MKV|MP4|WEBM_VIDEO_ONLY|WEBM_AUDIO_ONLY|MKV_VIDEO_ONLY|MKV_AUDIO_ONLY|MP4_VIDEO_ONLY|MP4_AUDIO_ONLY|JPEG_VIDEO_ONLY|KURENTO_SPLIT_RECORDER'))
  16248. throw SyntaxError(key+' param is not one of [WEBM|MKV|MP4|WEBM_VIDEO_ONLY|WEBM_AUDIO_ONLY|MKV_VIDEO_ONLY|MKV_AUDIO_ONLY|MP4_VIDEO_ONLY|MP4_AUDIO_ONLY|JPEG_VIDEO_ONLY|KURENTO_SPLIT_RECORDER] ('+value+')');
  16249. };
  16250. module.exports = checkMediaProfileSpecType;
  16251. },{"kurento-client":"kurento-client"}],103:[function(require,module,exports){
  16252. /* Autogenerated with Kurento Idl */
  16253. /*
  16254. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  16255. *
  16256. * Licensed under the Apache License, Version 2.0 (the "License");
  16257. * you may not use this file except in compliance with the License.
  16258. * You may obtain a copy of the License at
  16259. *
  16260. * http://www.apache.org/licenses/LICENSE-2.0
  16261. *
  16262. * Unless required by applicable law or agreed to in writing, software
  16263. * distributed under the License is distributed on an "AS IS" BASIS,
  16264. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16265. * See the License for the specific language governing permissions and
  16266. * limitations under the License.
  16267. */
  16268. var inherits = require('inherits');
  16269. var kurentoClient = require('kurento-client');
  16270. var checkType = kurentoClient.checkType;
  16271. var ChecktypeError = checkType.ChecktypeError;
  16272. var ComplexType = require('kurento-client-core').complexTypes.ComplexType;
  16273. /**
  16274. * Security Descriptions for Media Streams
  16275. *
  16276. * @constructor module:elements/complexTypes.SDES
  16277. *
  16278. * @property {external:String} key
  16279. * <p>Master key and salt (plain text)</p>
  16280. * <p>
  16281. * This field provides the the cryptographic master key appended with
  16282. * </p>
  16283. * <p>
  16284. * The expected length of the key (as provided to this parameter) is
  16285. * determined by the crypto-suite for which the key applies (30
  16286. * characters for AES_CM_128, 46 characters for AES_CM_256). If the
  16287. * length does not match the expected value, the key will be
  16288. * considered invalid.
  16289. * </p>
  16290. * <p>
  16291. * If no key is provided, a random one will be generated using the
  16292. * `getrandom` system call.
  16293. * </p>
  16294. * @property {external:String} keyBase64
  16295. * <p>Master key and salt (base64 encoded)</p>
  16296. * <p>
  16297. * This field provides the cryptographic master key appended with the
  16298. * </p>
  16299. * <p>
  16300. * The expected length of the key (after being decoded from base64)
  16301. * is determined by the crypto-suite for which the key applies (30
  16302. * bytes for AES_CM_128, 46 bytes for AES_CM_256). If the length does
  16303. * </p>
  16304. * <p>
  16305. * If no key is provided, a random one will be generated using the
  16306. * `getrandom` system call.
  16307. * </p>
  16308. * @property {module:elements/complexTypes.CryptoSuite} crypto
  16309. * Selects the cryptographic suite to be used. For available values, please see
  16310. */
  16311. function SDES(sDESDict){
  16312. if(!(this instanceof SDES))
  16313. return new SDES(sDESDict)
  16314. sDESDict = sDESDict || {}
  16315. // Check sDESDict has the required fields
  16316. //
  16317. // checkType('String', 'sDESDict.key', sDESDict.key);
  16318. //
  16319. // checkType('String', 'sDESDict.keyBase64', sDESDict.keyBase64);
  16320. //
  16321. // checkType('CryptoSuite', 'sDESDict.crypto', sDESDict.crypto);
  16322. //
  16323. // Init parent class
  16324. SDES.super_.call(this, sDESDict)
  16325. // Set object properties
  16326. Object.defineProperties(this, {
  16327. key: {
  16328. writable: true,
  16329. enumerable: true,
  16330. value: sDESDict.key
  16331. },
  16332. keyBase64: {
  16333. writable: true,
  16334. enumerable: true,
  16335. value: sDESDict.keyBase64
  16336. },
  16337. crypto: {
  16338. writable: true,
  16339. enumerable: true,
  16340. value: sDESDict.crypto
  16341. }
  16342. })
  16343. }
  16344. inherits(SDES, ComplexType)
  16345. // Private identifiers to allow re-construction of the complexType on the server
  16346. // They need to be enumerable so JSON.stringify() can access to them
  16347. Object.defineProperties(SDES.prototype, {
  16348. __module__: {
  16349. enumerable: true,
  16350. value: "kurento"
  16351. },
  16352. __type__: {
  16353. enumerable: true,
  16354. value: "SDES"
  16355. }
  16356. })
  16357. /**
  16358. * Checker for {@link module:elements/complexTypes.SDES}
  16359. *
  16360. * @memberof module:elements/complexTypes
  16361. *
  16362. * @param {external:String} key
  16363. * @param {module:elements/complexTypes.SDES} value
  16364. */
  16365. function checkSDES(key, value)
  16366. {
  16367. if(!(value instanceof SDES))
  16368. throw ChecktypeError(key, SDES, value);
  16369. };
  16370. module.exports = SDES;
  16371. SDES.check = checkSDES;
  16372. },{"inherits":"inherits","kurento-client":"kurento-client","kurento-client-core":"kurento-client-core"}],104:[function(require,module,exports){
  16373. /* Autogenerated with Kurento Idl */
  16374. /*
  16375. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  16376. *
  16377. * Licensed under the Apache License, Version 2.0 (the "License");
  16378. * you may not use this file except in compliance with the License.
  16379. * You may obtain a copy of the License at
  16380. *
  16381. * http://www.apache.org/licenses/LICENSE-2.0
  16382. *
  16383. * Unless required by applicable law or agreed to in writing, software
  16384. * distributed under the License is distributed on an "AS IS" BASIS,
  16385. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16386. * See the License for the specific language governing permissions and
  16387. * limitations under the License.
  16388. */
  16389. var inherits = require('inherits');
  16390. var kurentoClient = require('kurento-client');
  16391. var checkType = kurentoClient.checkType;
  16392. var ChecktypeError = checkType.ChecktypeError;
  16393. var ComplexType = require('kurento-client-core').complexTypes.ComplexType;
  16394. /**
  16395. *
  16396. * @constructor module:elements/complexTypes.VideoInfo
  16397. *
  16398. * @property {external:Boolean} isSeekable
  16399. * Seek is possible in video source
  16400. * @property {external:int64} seekableInit
  16401. * First video position to do seek in ms
  16402. * @property {external:int64} seekableEnd
  16403. * Last video position to do seek in ms
  16404. * @property {external:int64} duration
  16405. * Video duration in ms
  16406. */
  16407. function VideoInfo(videoInfoDict){
  16408. if(!(this instanceof VideoInfo))
  16409. return new VideoInfo(videoInfoDict)
  16410. videoInfoDict = videoInfoDict || {}
  16411. // Check videoInfoDict has the required fields
  16412. //
  16413. // checkType('boolean', 'videoInfoDict.isSeekable', videoInfoDict.isSeekable, {required: true});
  16414. //
  16415. // checkType('int64', 'videoInfoDict.seekableInit', videoInfoDict.seekableInit, {required: true});
  16416. //
  16417. // checkType('int64', 'videoInfoDict.seekableEnd', videoInfoDict.seekableEnd, {required: true});
  16418. //
  16419. // checkType('int64', 'videoInfoDict.duration', videoInfoDict.duration, {required: true});
  16420. //
  16421. // Init parent class
  16422. VideoInfo.super_.call(this, videoInfoDict)
  16423. // Set object properties
  16424. Object.defineProperties(this, {
  16425. isSeekable: {
  16426. writable: true,
  16427. enumerable: true,
  16428. value: videoInfoDict.isSeekable
  16429. },
  16430. seekableInit: {
  16431. writable: true,
  16432. enumerable: true,
  16433. value: videoInfoDict.seekableInit
  16434. },
  16435. seekableEnd: {
  16436. writable: true,
  16437. enumerable: true,
  16438. value: videoInfoDict.seekableEnd
  16439. },
  16440. duration: {
  16441. writable: true,
  16442. enumerable: true,
  16443. value: videoInfoDict.duration
  16444. }
  16445. })
  16446. }
  16447. inherits(VideoInfo, ComplexType)
  16448. // Private identifiers to allow re-construction of the complexType on the server
  16449. // They need to be enumerable so JSON.stringify() can access to them
  16450. Object.defineProperties(VideoInfo.prototype, {
  16451. __module__: {
  16452. enumerable: true,
  16453. value: "kurento"
  16454. },
  16455. __type__: {
  16456. enumerable: true,
  16457. value: "VideoInfo"
  16458. }
  16459. })
  16460. /**
  16461. * Checker for {@link module:elements/complexTypes.VideoInfo}
  16462. *
  16463. * @memberof module:elements/complexTypes
  16464. *
  16465. * @param {external:String} key
  16466. * @param {module:elements/complexTypes.VideoInfo} value
  16467. */
  16468. function checkVideoInfo(key, value)
  16469. {
  16470. if(!(value instanceof VideoInfo))
  16471. throw ChecktypeError(key, VideoInfo, value);
  16472. };
  16473. module.exports = VideoInfo;
  16474. VideoInfo.check = checkVideoInfo;
  16475. },{"inherits":"inherits","kurento-client":"kurento-client","kurento-client-core":"kurento-client-core"}],105:[function(require,module,exports){
  16476. /* Autogenerated with Kurento Idl */
  16477. /*
  16478. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  16479. *
  16480. * Licensed under the Apache License, Version 2.0 (the "License");
  16481. * you may not use this file except in compliance with the License.
  16482. * You may obtain a copy of the License at
  16483. *
  16484. * http://www.apache.org/licenses/LICENSE-2.0
  16485. *
  16486. * Unless required by applicable law or agreed to in writing, software
  16487. * distributed under the License is distributed on an "AS IS" BASIS,
  16488. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16489. * See the License for the specific language governing permissions and
  16490. * limitations under the License.
  16491. */
  16492. /**
  16493. * Media API for the Kurento Web SDK
  16494. *
  16495. * @module elements/complexTypes
  16496. *
  16497. * @copyright 2013-2015 Kurento (http://kurento.org/)
  16498. * @license ALv2
  16499. */
  16500. var CertificateKeyType = require('./CertificateKeyType');
  16501. var CryptoSuite = require('./CryptoSuite');
  16502. var IceCandidate = require('./IceCandidate');
  16503. var IceCandidatePair = require('./IceCandidatePair');
  16504. var IceComponentState = require('./IceComponentState');
  16505. var IceConnection = require('./IceConnection');
  16506. var MediaProfileSpecType = require('./MediaProfileSpecType');
  16507. var SDES = require('./SDES');
  16508. var VideoInfo = require('./VideoInfo');
  16509. exports.CertificateKeyType = CertificateKeyType;
  16510. exports.CryptoSuite = CryptoSuite;
  16511. exports.IceCandidate = IceCandidate;
  16512. exports.IceCandidatePair = IceCandidatePair;
  16513. exports.IceComponentState = IceComponentState;
  16514. exports.IceConnection = IceConnection;
  16515. exports.MediaProfileSpecType = MediaProfileSpecType;
  16516. exports.SDES = SDES;
  16517. exports.VideoInfo = VideoInfo;
  16518. },{"./CertificateKeyType":96,"./CryptoSuite":97,"./IceCandidate":98,"./IceCandidatePair":99,"./IceComponentState":100,"./IceConnection":101,"./MediaProfileSpecType":102,"./SDES":103,"./VideoInfo":104}],106:[function(require,module,exports){
  16519. /* Autogenerated with Kurento Idl */
  16520. /*
  16521. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  16522. *
  16523. * Licensed under the Apache License, Version 2.0 (the "License");
  16524. * you may not use this file except in compliance with the License.
  16525. * You may obtain a copy of the License at
  16526. *
  16527. * http://www.apache.org/licenses/LICENSE-2.0
  16528. *
  16529. * Unless required by applicable law or agreed to in writing, software
  16530. * distributed under the License is distributed on an "AS IS" BASIS,
  16531. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16532. * See the License for the specific language governing permissions and
  16533. * limitations under the License.
  16534. */
  16535. var inherits = require('inherits');
  16536. var kurentoClient = require('kurento-client');
  16537. var disguise = kurentoClient.disguise;
  16538. var checkType = kurentoClient.checkType;
  16539. var ChecktypeError = checkType.ChecktypeError;
  16540. var Transaction = kurentoClient.TransactionsManager.Transaction;
  16541. var Filter = require('kurento-client-core').abstracts.Filter;
  16542. function noop(error, result) {
  16543. if (error) console.trace(error);
  16544. return result
  16545. };
  16546. /**
  16547. * FaceOverlayFilter interface. This type of {@link module:core/abstracts.Filter
  16548. *
  16549. * @classdesc
  16550. * FaceOverlayFilter interface. This type of {@link
  16551. * module:core/abstracts.Filter Filter} detects faces in a video feed. The face
  16552. *
  16553. * @extends module:core/abstracts.Filter
  16554. *
  16555. * @constructor module:filters.FaceOverlayFilter
  16556. */
  16557. function FaceOverlayFilter(){
  16558. FaceOverlayFilter.super_.call(this);
  16559. };
  16560. inherits(FaceOverlayFilter, Filter);
  16561. //
  16562. // Public methods
  16563. //
  16564. /**
  16565. * Sets the image to use as overlay on the detected faces.
  16566. *
  16567. * @alias module:filters.FaceOverlayFilter.setOverlayedImage
  16568. *
  16569. * @param {external:String} uri
  16570. * URI where the image is located
  16571. *
  16572. * @param {external:Number} offsetXPercent
  16573. * the offset applied to the image, from the X coordinate of the detected face
  16574. * upper right corner. A positive value indicates right displacement, while a
  16575. * negative value moves the overlaid image to the left. This offset is
  16576. * specified as a percentage of the face width.
  16577. * For example, to cover the detected face with the overlaid image, the
  16578. * parameter has to be <code>0.0</code>. Values of <code>1.0</code> or
  16579. * <code>-1.0</code> indicate that the image upper right corner will be at the
  16580. * face´s X coord, +- the face´s width.
  16581. * <hr/><b>Note</b>
  16582. * The parameter name is misleading, the value is not a percent but a ratio
  16583. *
  16584. * @param {external:Number} offsetYPercent
  16585. * the offset applied to the image, from the Y coordinate of the detected face
  16586. * upper right corner. A positive value indicates up displacement, while a
  16587. * negative value moves the overlaid image down. This offset is specified as a
  16588. * percentage of the face width.
  16589. * For example, to cover the detected face with the overlaid image, the
  16590. * parameter has to be <code>0.0</code>. Values of <code>1.0</code> or
  16591. * <code>-1.0</code> indicate that the image upper right corner will be at the
  16592. * face´s Y coord, +- the face´s width.
  16593. * <hr/><b>Note</b>
  16594. * The parameter name is misleading, the value is not a percent but a ratio
  16595. *
  16596. * @param {external:Number} widthPercent
  16597. * proportional width of the overlaid image, relative to the width of the
  16598. * detected face. A value of 1.0 implies that the overlaid image will have the
  16599. * same width as the detected face. Values greater than 1.0 are allowed, while
  16600. * negative values are forbidden.
  16601. * <hr/><b>Note</b>
  16602. * The parameter name is misleading, the value is not a percent but a ratio
  16603. *
  16604. * @param {external:Number} heightPercent
  16605. * proportional height of the overlaid image, relative to the height of the
  16606. * detected face. A value of 1.0 implies that the overlaid image will have the
  16607. * same height as the detected face. Values greater than 1.0 are allowed, while
  16608. * <hr/><b>Note</b>
  16609. * The parameter name is misleading, the value is not a percent but a ratio
  16610. *
  16611. * @param {module:filters.FaceOverlayFilter~setOverlayedImageCallback} [callback]
  16612. *
  16613. * @return {external:Promise}
  16614. */
  16615. FaceOverlayFilter.prototype.setOverlayedImage = function(uri, offsetXPercent, offsetYPercent, widthPercent, heightPercent, callback){
  16616. var transaction = (arguments[0] instanceof Transaction)
  16617. ? Array.prototype.shift.apply(arguments)
  16618. : undefined;
  16619. //
  16620. // checkType('String', 'uri', uri, {required: true});
  16621. //
  16622. // checkType('float', 'offsetXPercent', offsetXPercent, {required: true});
  16623. //
  16624. // checkType('float', 'offsetYPercent', offsetYPercent, {required: true});
  16625. //
  16626. // checkType('float', 'widthPercent', widthPercent, {required: true});
  16627. //
  16628. // checkType('float', 'heightPercent', heightPercent, {required: true});
  16629. //
  16630. var params = {
  16631. uri: uri,
  16632. offsetXPercent: offsetXPercent,
  16633. offsetYPercent: offsetYPercent,
  16634. widthPercent: widthPercent,
  16635. heightPercent: heightPercent
  16636. };
  16637. callback = (callback || noop).bind(this)
  16638. return disguise(this._invoke(transaction, 'setOverlayedImage', params, callback), this)
  16639. };
  16640. /**
  16641. * @callback module:filters.FaceOverlayFilter~setOverlayedImageCallback
  16642. * @param {external:Error} error
  16643. */
  16644. /**
  16645. * Clear the image to be shown over each detected face. Stops overlaying the
  16646. * faces.
  16647. *
  16648. * @alias module:filters.FaceOverlayFilter.unsetOverlayedImage
  16649. *
  16650. * @param {module:filters.FaceOverlayFilter~unsetOverlayedImageCallback} [callback]
  16651. *
  16652. * @return {external:Promise}
  16653. */
  16654. FaceOverlayFilter.prototype.unsetOverlayedImage = function(callback){
  16655. var transaction = (arguments[0] instanceof Transaction)
  16656. ? Array.prototype.shift.apply(arguments)
  16657. : undefined;
  16658. var usePromise = false;
  16659. if (callback == undefined) {
  16660. usePromise = true;
  16661. }
  16662. if(!arguments.length) callback = undefined;
  16663. callback = (callback || noop).bind(this)
  16664. return disguise(this._invoke(transaction, 'unsetOverlayedImage', callback), this)
  16665. };
  16666. /**
  16667. * @callback module:filters.FaceOverlayFilter~unsetOverlayedImageCallback
  16668. * @param {external:Error} error
  16669. */
  16670. /**
  16671. * @alias module:filters.FaceOverlayFilter.constructorParams
  16672. *
  16673. * @property {module:core.MediaPipeline} mediaPipeline
  16674. * pipeline to which this {@link module:core/abstracts.Filter Filter} belons
  16675. */
  16676. FaceOverlayFilter.constructorParams = {
  16677. mediaPipeline: {
  16678. type: 'kurento.MediaPipeline',
  16679. required: true
  16680. }
  16681. };
  16682. /**
  16683. * @alias module:filters.FaceOverlayFilter.events
  16684. *
  16685. * @extends module:core/abstracts.Filter.events
  16686. */
  16687. FaceOverlayFilter.events = Filter.events;
  16688. /**
  16689. * Checker for {@link module:filters.FaceOverlayFilter}
  16690. *
  16691. * @memberof module:filters
  16692. *
  16693. * @param {external:String} key
  16694. * @param {module:filters.FaceOverlayFilter} value
  16695. */
  16696. function checkFaceOverlayFilter(key, value)
  16697. {
  16698. if(!(value instanceof FaceOverlayFilter))
  16699. throw ChecktypeError(key, FaceOverlayFilter, value);
  16700. };
  16701. module.exports = FaceOverlayFilter;
  16702. FaceOverlayFilter.check = checkFaceOverlayFilter;
  16703. },{"inherits":"inherits","kurento-client":"kurento-client","kurento-client-core":"kurento-client-core"}],107:[function(require,module,exports){
  16704. /* Autogenerated with Kurento Idl */
  16705. /*
  16706. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  16707. *
  16708. * Licensed under the Apache License, Version 2.0 (the "License");
  16709. * you may not use this file except in compliance with the License.
  16710. * You may obtain a copy of the License at
  16711. *
  16712. * http://www.apache.org/licenses/LICENSE-2.0
  16713. *
  16714. * Unless required by applicable law or agreed to in writing, software
  16715. * distributed under the License is distributed on an "AS IS" BASIS,
  16716. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16717. * See the License for the specific language governing permissions and
  16718. * limitations under the License.
  16719. */
  16720. var inherits = require('inherits');
  16721. var kurentoClient = require('kurento-client');
  16722. var disguise = kurentoClient.disguise;
  16723. var checkType = kurentoClient.checkType;
  16724. var ChecktypeError = checkType.ChecktypeError;
  16725. var Transaction = kurentoClient.TransactionsManager.Transaction;
  16726. var Filter = require('kurento-client-core').abstracts.Filter;
  16727. function noop(error, result) {
  16728. if (error) console.trace(error);
  16729. return result
  16730. };
  16731. /**
  16732. * Create a {@link module:filters.GStreamerFilter GStreamerFilter}.
  16733. *
  16734. * @classdesc
  16735. * A generic filter interface that allows injecting any GStreamer element.
  16736. * <p>
  16737. * Note however that the current implementation of GStreamerFilter only
  16738. * allows single elements to be injected; one cannot indicate more than
  16739. * one at the same time; use several GStreamerFilters if you need to
  16740. * inject more than one element at the same time.
  16741. * </p>
  16742. *
  16743. * @extends module:core/abstracts.Filter
  16744. *
  16745. * @constructor module:filters.GStreamerFilter
  16746. */
  16747. function GStreamerFilter(){
  16748. GStreamerFilter.super_.call(this);
  16749. };
  16750. inherits(GStreamerFilter, Filter);
  16751. //
  16752. // Public properties
  16753. //
  16754. /**
  16755. * String used to instantiate the GStreamer element, as in `gst-launch
  16756. * <https://gstreamer.freedesktop.org/documentation/tools/gst-launch.html>`__.
  16757. *
  16758. * @alias module:filters.GStreamerFilter#getCommand
  16759. *
  16760. * @param {module:filters.GStreamerFilter~getCommandCallback} [callback]
  16761. *
  16762. * @return {external:Promise}
  16763. */
  16764. GStreamerFilter.prototype.getCommand = function(callback){
  16765. var transaction = (arguments[0] instanceof Transaction)
  16766. ? Array.prototype.shift.apply(arguments)
  16767. : undefined;
  16768. var usePromise = false;
  16769. if (callback == undefined) {
  16770. usePromise = true;
  16771. }
  16772. if(!arguments.length) callback = undefined;
  16773. callback = (callback || noop).bind(this)
  16774. return disguise(this._invoke(transaction, 'getCommand', callback), this)
  16775. };
  16776. /**
  16777. * @callback module:filters.GStreamerFilter~getCommandCallback
  16778. * @param {external:Error} error
  16779. * @param {external:String} result
  16780. */
  16781. //
  16782. // Public methods
  16783. //
  16784. /**
  16785. * Provide a value to one of the GStreamer element's properties.
  16786. *
  16787. * @alias module:filters.GStreamerFilter.setElementProperty
  16788. *
  16789. * @param {external:String} propertyName
  16790. * Name of the property that needs to be modified in the GStreamer element.
  16791. *
  16792. * @param {external:String} propertyValue
  16793. * Value that must be assigned to the property.
  16794. *
  16795. * @param {module:filters.GStreamerFilter~setElementPropertyCallback} [callback]
  16796. *
  16797. * @return {external:Promise}
  16798. */
  16799. GStreamerFilter.prototype.setElementProperty = function(propertyName, propertyValue, callback){
  16800. var transaction = (arguments[0] instanceof Transaction)
  16801. ? Array.prototype.shift.apply(arguments)
  16802. : undefined;
  16803. //
  16804. // checkType('String', 'propertyName', propertyName, {required: true});
  16805. //
  16806. // checkType('String', 'propertyValue', propertyValue, {required: true});
  16807. //
  16808. var params = {
  16809. propertyName: propertyName,
  16810. propertyValue: propertyValue
  16811. };
  16812. callback = (callback || noop).bind(this)
  16813. return disguise(this._invoke(transaction, 'setElementProperty', params, callback), this)
  16814. };
  16815. /**
  16816. * @callback module:filters.GStreamerFilter~setElementPropertyCallback
  16817. * @param {external:Error} error
  16818. */
  16819. /**
  16820. * @alias module:filters.GStreamerFilter.constructorParams
  16821. *
  16822. * @property {external:String} command
  16823. * String used to instantiate the GStreamer element, as in `gst-launch
  16824. * <https://gstreamer.freedesktop.org/documentation/tools/gst-launch.html>`__.
  16825. *
  16826. * @property {external:FilterType} [filterType]
  16827. * Sets the filter as Audio, Video, or Autodetect.
  16828. *
  16829. * @property {module:core.MediaPipeline} mediaPipeline
  16830. * the {@link module:core.MediaPipeline MediaPipeline} to which the filter
  16831. * belongs
  16832. */
  16833. GStreamerFilter.constructorParams = {
  16834. command: {
  16835. type: 'String',
  16836. required: true
  16837. },
  16838. filterType: {
  16839. type: 'kurento.FilterType' },
  16840. mediaPipeline: {
  16841. type: 'kurento.MediaPipeline',
  16842. required: true
  16843. }
  16844. };
  16845. /**
  16846. * @alias module:filters.GStreamerFilter.events
  16847. *
  16848. * @extends module:core/abstracts.Filter.events
  16849. */
  16850. GStreamerFilter.events = Filter.events;
  16851. /**
  16852. * Checker for {@link module:filters.GStreamerFilter}
  16853. *
  16854. * @memberof module:filters
  16855. *
  16856. * @param {external:String} key
  16857. * @param {module:filters.GStreamerFilter} value
  16858. */
  16859. function checkGStreamerFilter(key, value)
  16860. {
  16861. if(!(value instanceof GStreamerFilter))
  16862. throw ChecktypeError(key, GStreamerFilter, value);
  16863. };
  16864. module.exports = GStreamerFilter;
  16865. GStreamerFilter.check = checkGStreamerFilter;
  16866. },{"inherits":"inherits","kurento-client":"kurento-client","kurento-client-core":"kurento-client-core"}],108:[function(require,module,exports){
  16867. /* Autogenerated with Kurento Idl */
  16868. /*
  16869. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  16870. *
  16871. * Licensed under the Apache License, Version 2.0 (the "License");
  16872. * you may not use this file except in compliance with the License.
  16873. * You may obtain a copy of the License at
  16874. *
  16875. * http://www.apache.org/licenses/LICENSE-2.0
  16876. *
  16877. * Unless required by applicable law or agreed to in writing, software
  16878. * distributed under the License is distributed on an "AS IS" BASIS,
  16879. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16880. * See the License for the specific language governing permissions and
  16881. * limitations under the License.
  16882. */
  16883. var inherits = require('inherits');
  16884. var kurentoClient = require('kurento-client');
  16885. var disguise = kurentoClient.disguise;
  16886. var checkType = kurentoClient.checkType;
  16887. var ChecktypeError = checkType.ChecktypeError;
  16888. var Transaction = kurentoClient.TransactionsManager.Transaction;
  16889. var Filter = require('kurento-client-core').abstracts.Filter;
  16890. function noop(error, result) {
  16891. if (error) console.trace(error);
  16892. return result
  16893. };
  16894. /**
  16895. * ImageOverlayFilter interface. This type of {@link
  16896. * module:core/abstracts.Filter Filter} draws an image in a configured position
  16897. * over a video feed.
  16898. *
  16899. * @classdesc
  16900. * ImageOverlayFilter interface. This type of {@link
  16901. * module:core/abstracts.Filter Filter} draws an image in a configured position
  16902. *
  16903. * @extends module:core/abstracts.Filter
  16904. *
  16905. * @constructor module:filters.ImageOverlayFilter
  16906. */
  16907. function ImageOverlayFilter(){
  16908. ImageOverlayFilter.super_.call(this);
  16909. };
  16910. inherits(ImageOverlayFilter, Filter);
  16911. //
  16912. // Public methods
  16913. //
  16914. /**
  16915. * Add an image to be used as overlay.
  16916. *
  16917. * @alias module:filters.ImageOverlayFilter.addImage
  16918. *
  16919. * @param {external:String} id
  16920. * image ID
  16921. *
  16922. * @param {external:String} uri
  16923. * URI where the image is located
  16924. *
  16925. * @param {external:Number} offsetXPercent
  16926. * Percentage relative to the image width to calculate the X coordinate of the
  16927. * position (left upper corner) [0..1]
  16928. *
  16929. * @param {external:Number} offsetYPercent
  16930. * Percentage relative to the image height to calculate the Y coordinate of the
  16931. *
  16932. * @param {external:Number} widthPercent
  16933. * Proportional width of the overlaid image, relative to the width of the video
  16934. *
  16935. * @param {external:Number} heightPercent
  16936. * Proportional height of the overlaid image, relative to the height of the
  16937. * video [0..1].
  16938. *
  16939. * @param {external:Boolean} keepAspectRatio
  16940. * Keep the aspect ratio of the original image.
  16941. *
  16942. * @param {external:Boolean} center
  16943. * If the image doesn't fit in the dimensions, the image will be center into
  16944. * the region defined by height and width.
  16945. *
  16946. * @param {module:filters.ImageOverlayFilter~addImageCallback} [callback]
  16947. *
  16948. * @return {external:Promise}
  16949. */
  16950. ImageOverlayFilter.prototype.addImage = function(id, uri, offsetXPercent, offsetYPercent, widthPercent, heightPercent, keepAspectRatio, center, callback){
  16951. var transaction = (arguments[0] instanceof Transaction)
  16952. ? Array.prototype.shift.apply(arguments)
  16953. : undefined;
  16954. //
  16955. // checkType('String', 'id', id, {required: true});
  16956. //
  16957. // checkType('String', 'uri', uri, {required: true});
  16958. //
  16959. // checkType('float', 'offsetXPercent', offsetXPercent, {required: true});
  16960. //
  16961. // checkType('float', 'offsetYPercent', offsetYPercent, {required: true});
  16962. //
  16963. // checkType('float', 'widthPercent', widthPercent, {required: true});
  16964. //
  16965. // checkType('float', 'heightPercent', heightPercent, {required: true});
  16966. //
  16967. // checkType('boolean', 'keepAspectRatio', keepAspectRatio, {required: true});
  16968. //
  16969. // checkType('boolean', 'center', center, {required: true});
  16970. //
  16971. var params = {
  16972. id: id,
  16973. uri: uri,
  16974. offsetXPercent: offsetXPercent,
  16975. offsetYPercent: offsetYPercent,
  16976. widthPercent: widthPercent,
  16977. heightPercent: heightPercent,
  16978. keepAspectRatio: keepAspectRatio,
  16979. center: center
  16980. };
  16981. callback = (callback || noop).bind(this)
  16982. return disguise(this._invoke(transaction, 'addImage', params, callback), this)
  16983. };
  16984. /**
  16985. * @callback module:filters.ImageOverlayFilter~addImageCallback
  16986. * @param {external:Error} error
  16987. */
  16988. /**
  16989. * Remove the image with the given ID.
  16990. *
  16991. * @alias module:filters.ImageOverlayFilter.removeImage
  16992. *
  16993. * @param {external:String} id
  16994. * Image ID to be removed
  16995. *
  16996. * @param {module:filters.ImageOverlayFilter~removeImageCallback} [callback]
  16997. *
  16998. * @return {external:Promise}
  16999. */
  17000. ImageOverlayFilter.prototype.removeImage = function(id, callback){
  17001. var transaction = (arguments[0] instanceof Transaction)
  17002. ? Array.prototype.shift.apply(arguments)
  17003. : undefined;
  17004. //
  17005. // checkType('String', 'id', id, {required: true});
  17006. //
  17007. var params = {
  17008. id: id
  17009. };
  17010. callback = (callback || noop).bind(this)
  17011. return disguise(this._invoke(transaction, 'removeImage', params, callback), this)
  17012. };
  17013. /**
  17014. * @callback module:filters.ImageOverlayFilter~removeImageCallback
  17015. * @param {external:Error} error
  17016. */
  17017. /**
  17018. * @alias module:filters.ImageOverlayFilter.constructorParams
  17019. *
  17020. * @property {module:core.MediaPipeline} mediaPipeline
  17021. * pipeline to which this {@link module:core/abstracts.Filter Filter} belongs
  17022. */
  17023. ImageOverlayFilter.constructorParams = {
  17024. mediaPipeline: {
  17025. type: 'kurento.MediaPipeline',
  17026. required: true
  17027. }
  17028. };
  17029. /**
  17030. * @alias module:filters.ImageOverlayFilter.events
  17031. *
  17032. * @extends module:core/abstracts.Filter.events
  17033. */
  17034. ImageOverlayFilter.events = Filter.events;
  17035. /**
  17036. * Checker for {@link module:filters.ImageOverlayFilter}
  17037. *
  17038. * @memberof module:filters
  17039. *
  17040. * @param {external:String} key
  17041. * @param {module:filters.ImageOverlayFilter} value
  17042. */
  17043. function checkImageOverlayFilter(key, value)
  17044. {
  17045. if(!(value instanceof ImageOverlayFilter))
  17046. throw ChecktypeError(key, ImageOverlayFilter, value);
  17047. };
  17048. module.exports = ImageOverlayFilter;
  17049. ImageOverlayFilter.check = checkImageOverlayFilter;
  17050. },{"inherits":"inherits","kurento-client":"kurento-client","kurento-client-core":"kurento-client-core"}],109:[function(require,module,exports){
  17051. /* Autogenerated with Kurento Idl */
  17052. /*
  17053. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  17054. *
  17055. * Licensed under the Apache License, Version 2.0 (the "License");
  17056. * you may not use this file except in compliance with the License.
  17057. * You may obtain a copy of the License at
  17058. *
  17059. * http://www.apache.org/licenses/LICENSE-2.0
  17060. *
  17061. * Unless required by applicable law or agreed to in writing, software
  17062. * distributed under the License is distributed on an "AS IS" BASIS,
  17063. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17064. * See the License for the specific language governing permissions and
  17065. * limitations under the License.
  17066. */
  17067. var inherits = require('inherits');
  17068. var kurentoClient = require('kurento-client');
  17069. var disguise = kurentoClient.disguise;
  17070. var ChecktypeError = kurentoClient.checkType.ChecktypeError;
  17071. var Filter = require('kurento-client-core').abstracts.Filter;
  17072. /**
  17073. * Builder for the {@link module:filters.ZBarFilter ZBarFilter}.
  17074. *
  17075. * @classdesc
  17076. * This filter detects <a
  17077. * href="http://www.kurento.org/docs/current/glossary.html#term-qr">QR</a>
  17078. * codes in a video feed. When a code is found, the filter raises a
  17079. * :rom:evnt:`CodeFound` event.
  17080. *
  17081. * @extends module:core/abstracts.Filter
  17082. *
  17083. * @constructor module:filters.ZBarFilter
  17084. *
  17085. * @fires {@link module:filters#event:CodeFound CodeFound}
  17086. */
  17087. function ZBarFilter(){
  17088. ZBarFilter.super_.call(this);
  17089. };
  17090. inherits(ZBarFilter, Filter);
  17091. /**
  17092. * @alias module:filters.ZBarFilter.constructorParams
  17093. *
  17094. * @property {module:core.MediaPipeline} mediaPipeline
  17095. * the {@link module:core.MediaPipeline MediaPipeline} to which the filter
  17096. * belongs
  17097. */
  17098. ZBarFilter.constructorParams = {
  17099. mediaPipeline: {
  17100. type: 'kurento.MediaPipeline',
  17101. required: true
  17102. }
  17103. };
  17104. /**
  17105. * @alias module:filters.ZBarFilter.events
  17106. *
  17107. * @extends module:core/abstracts.Filter.events
  17108. */
  17109. ZBarFilter.events = Filter.events.concat(['CodeFound']);
  17110. /**
  17111. * Checker for {@link module:filters.ZBarFilter}
  17112. *
  17113. * @memberof module:filters
  17114. *
  17115. * @param {external:String} key
  17116. * @param {module:filters.ZBarFilter} value
  17117. */
  17118. function checkZBarFilter(key, value)
  17119. {
  17120. if(!(value instanceof ZBarFilter))
  17121. throw ChecktypeError(key, ZBarFilter, value);
  17122. };
  17123. module.exports = ZBarFilter;
  17124. ZBarFilter.check = checkZBarFilter;
  17125. },{"inherits":"inherits","kurento-client":"kurento-client","kurento-client-core":"kurento-client-core"}],110:[function(require,module,exports){
  17126. /* Autogenerated with Kurento Idl */
  17127. /*
  17128. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  17129. *
  17130. * Licensed under the Apache License, Version 2.0 (the "License");
  17131. * you may not use this file except in compliance with the License.
  17132. * You may obtain a copy of the License at
  17133. *
  17134. * http://www.apache.org/licenses/LICENSE-2.0
  17135. *
  17136. * Unless required by applicable law or agreed to in writing, software
  17137. * distributed under the License is distributed on an "AS IS" BASIS,
  17138. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17139. * See the License for the specific language governing permissions and
  17140. * limitations under the License.
  17141. */
  17142. var inherits = require('inherits');
  17143. var kurentoClient = require('kurento-client');
  17144. var disguise = kurentoClient.disguise;
  17145. var ChecktypeError = kurentoClient.checkType.ChecktypeError;
  17146. var Filter = require('kurento-client-core').abstracts.Filter;
  17147. /**
  17148. * @classdesc
  17149. * Generic OpenCV Filter
  17150. *
  17151. * @abstract
  17152. * @extends module:core/abstracts.Filter
  17153. *
  17154. * @constructor module:filters/abstracts.OpenCVFilter
  17155. */
  17156. function OpenCVFilter(){
  17157. OpenCVFilter.super_.call(this);
  17158. };
  17159. inherits(OpenCVFilter, Filter);
  17160. /**
  17161. * @alias module:filters/abstracts.OpenCVFilter.constructorParams
  17162. */
  17163. OpenCVFilter.constructorParams = {
  17164. };
  17165. /**
  17166. * @alias module:filters/abstracts.OpenCVFilter.events
  17167. *
  17168. * @extends module:core/abstracts.Filter.events
  17169. */
  17170. OpenCVFilter.events = Filter.events;
  17171. /**
  17172. * Checker for {@link module:filters/abstracts.OpenCVFilter}
  17173. *
  17174. * @memberof module:filters/abstracts
  17175. *
  17176. * @param {external:String} key
  17177. * @param {module:filters/abstracts.OpenCVFilter} value
  17178. */
  17179. function checkOpenCVFilter(key, value)
  17180. {
  17181. if(!(value instanceof OpenCVFilter))
  17182. throw ChecktypeError(key, OpenCVFilter, value);
  17183. };
  17184. module.exports = OpenCVFilter;
  17185. OpenCVFilter.check = checkOpenCVFilter;
  17186. },{"inherits":"inherits","kurento-client":"kurento-client","kurento-client-core":"kurento-client-core"}],111:[function(require,module,exports){
  17187. /* Autogenerated with Kurento Idl */
  17188. /*
  17189. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  17190. *
  17191. * Licensed under the Apache License, Version 2.0 (the "License");
  17192. * you may not use this file except in compliance with the License.
  17193. * You may obtain a copy of the License at
  17194. *
  17195. * http://www.apache.org/licenses/LICENSE-2.0
  17196. *
  17197. * Unless required by applicable law or agreed to in writing, software
  17198. * distributed under the License is distributed on an "AS IS" BASIS,
  17199. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17200. * See the License for the specific language governing permissions and
  17201. * limitations under the License.
  17202. */
  17203. /**
  17204. * Media API for the Kurento Web SDK
  17205. *
  17206. * @module filters/abstracts
  17207. *
  17208. * @copyright 2013-2015 Kurento (http://kurento.org/)
  17209. * @license ALv2
  17210. */
  17211. var OpenCVFilter = require('./OpenCVFilter');
  17212. exports.OpenCVFilter = OpenCVFilter;
  17213. },{"./OpenCVFilter":110}],112:[function(require,module,exports){
  17214. function Mapper() {
  17215. var sources = {};
  17216. this.forEach = function (callback) {
  17217. for (var key in sources) {
  17218. var source = sources[key];
  17219. for (var key2 in source)
  17220. callback(source[key2]);
  17221. };
  17222. };
  17223. this.get = function (id, source) {
  17224. var ids = sources[source];
  17225. if (ids == undefined)
  17226. return undefined;
  17227. return ids[id];
  17228. };
  17229. this.remove = function (id, source) {
  17230. var ids = sources[source];
  17231. if (ids == undefined)
  17232. return;
  17233. delete ids[id];
  17234. // Check it's empty
  17235. for (var i in ids) {
  17236. return false
  17237. }
  17238. delete sources[source];
  17239. };
  17240. this.set = function (value, id, source) {
  17241. if (value == undefined)
  17242. return this.remove(id, source);
  17243. var ids = sources[source];
  17244. if (ids == undefined)
  17245. sources[source] = ids = {};
  17246. ids[id] = value;
  17247. };
  17248. };
  17249. Mapper.prototype.pop = function (id, source) {
  17250. var value = this.get(id, source);
  17251. if (value == undefined)
  17252. return undefined;
  17253. this.remove(id, source);
  17254. return value;
  17255. };
  17256. module.exports = Mapper;
  17257. },{}],113:[function(require,module,exports){
  17258. /*
  17259. * (C) Copyright 2014 Kurento (http://kurento.org/)
  17260. *
  17261. * Licensed under the Apache License, Version 2.0 (the "License");
  17262. * you may not use this file except in compliance with the License.
  17263. * You may obtain a copy of the License at
  17264. *
  17265. * http://www.apache.org/licenses/LICENSE-2.0
  17266. *
  17267. * Unless required by applicable law or agreed to in writing, software
  17268. * distributed under the License is distributed on an "AS IS" BASIS,
  17269. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17270. * See the License for the specific language governing permissions and
  17271. * limitations under the License.
  17272. *
  17273. */
  17274. var JsonRpcClient = require('./jsonrpcclient');
  17275. exports.JsonRpcClient = JsonRpcClient;
  17276. },{"./jsonrpcclient":114}],114:[function(require,module,exports){
  17277. /*
  17278. * (C) Copyright 2014 Kurento (http://kurento.org/)
  17279. *
  17280. * Licensed under the Apache License, Version 2.0 (the "License");
  17281. * you may not use this file except in compliance with the License.
  17282. * You may obtain a copy of the License at
  17283. *
  17284. * http://www.apache.org/licenses/LICENSE-2.0
  17285. *
  17286. * Unless required by applicable law or agreed to in writing, software
  17287. * distributed under the License is distributed on an "AS IS" BASIS,
  17288. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17289. * See the License for the specific language governing permissions and
  17290. * limitations under the License.
  17291. *
  17292. */
  17293. var RpcBuilder = require('../..');
  17294. var WebSocketWithReconnection = require(
  17295. './transports/webSocketWithReconnection');
  17296. Date.now = Date.now || function () {
  17297. return +new Date;
  17298. };
  17299. var PING_INTERVAL = 5000;
  17300. var RECONNECTING = 'RECONNECTING';
  17301. var CONNECTED = 'CONNECTED';
  17302. var DISCONNECTED = 'DISCONNECTED';
  17303. var Logger = console;
  17304. /**
  17305. *
  17306. * heartbeat: interval in ms for each heartbeat message,
  17307. * sendCloseMessage : true / false, before closing the connection, it sends a closeSession message
  17308. * <pre>
  17309. * ws : {
  17310. * uri : URI to conntect to,
  17311. * useSockJS : true (use SockJS) / false (use WebSocket) by default,
  17312. * onconnected : callback method to invoke when connection is successful,
  17313. * ondisconnect : callback method to invoke when the connection is lost,
  17314. * onreconnecting : callback method to invoke when the client is reconnecting,
  17315. * onreconnected : callback method to invoke when the client succesfully reconnects,
  17316. * onerror : callback method to invoke when there is an error
  17317. * },
  17318. * rpc : {
  17319. * requestTimeout : timeout for a request,
  17320. * sessionStatusChanged: callback method for changes in session status,
  17321. * mediaRenegotiation: mediaRenegotiation
  17322. * }
  17323. * </pre>
  17324. */
  17325. function JsonRpcClient(configuration) {
  17326. var self = this;
  17327. var wsConfig = configuration.ws;
  17328. var notReconnectIfNumLessThan = -1;
  17329. var pingNextNum = 0;
  17330. var enabledPings = true;
  17331. var pingPongStarted = false;
  17332. var pingInterval;
  17333. var status = DISCONNECTED;
  17334. var onreconnecting = wsConfig.onreconnecting;
  17335. var onreconnected = wsConfig.onreconnected;
  17336. var onconnected = wsConfig.onconnected;
  17337. var onerror = wsConfig.onerror;
  17338. configuration.rpc.pull = function (params, request) {
  17339. request.reply(null, "push");
  17340. }
  17341. wsConfig.onreconnecting = function () {
  17342. Logger.debug("--------- ONRECONNECTING -----------");
  17343. if (status === RECONNECTING) {
  17344. Logger.error(
  17345. "Websocket already in RECONNECTING state when receiving a new ONRECONNECTING message. Ignoring it"
  17346. );
  17347. return;
  17348. }
  17349. status = RECONNECTING;
  17350. if (onreconnecting) {
  17351. onreconnecting();
  17352. }
  17353. }
  17354. wsConfig.onreconnected = function () {
  17355. Logger.debug("--------- ONRECONNECTED -----------");
  17356. if (status === CONNECTED) {
  17357. Logger.error(
  17358. "Websocket already in CONNECTED state when receiving a new ONRECONNECTED message. Ignoring it"
  17359. );
  17360. return;
  17361. }
  17362. status = CONNECTED;
  17363. enabledPings = true;
  17364. updateNotReconnectIfLessThan();
  17365. usePing();
  17366. if (onreconnected) {
  17367. onreconnected();
  17368. }
  17369. }
  17370. wsConfig.onconnected = function () {
  17371. Logger.debug("--------- ONCONNECTED -----------");
  17372. if (status === CONNECTED) {
  17373. Logger.error(
  17374. "Websocket already in CONNECTED state when receiving a new ONCONNECTED message. Ignoring it"
  17375. );
  17376. return;
  17377. }
  17378. status = CONNECTED;
  17379. enabledPings = true;
  17380. usePing();
  17381. if (onconnected) {
  17382. onconnected();
  17383. }
  17384. }
  17385. wsConfig.onerror = function (error) {
  17386. Logger.debug("--------- ONERROR -----------");
  17387. status = DISCONNECTED;
  17388. if (onerror) {
  17389. onerror(error);
  17390. }
  17391. }
  17392. var ws = new WebSocketWithReconnection(wsConfig);
  17393. Logger.debug('Connecting websocket to URI: ' + wsConfig.uri);
  17394. var rpcBuilderOptions = {
  17395. request_timeout: configuration.rpc.requestTimeout,
  17396. ping_request_timeout: configuration.rpc.heartbeatRequestTimeout
  17397. };
  17398. var rpc = new RpcBuilder(RpcBuilder.packers.JsonRPC, rpcBuilderOptions, ws,
  17399. function (request) {
  17400. Logger.debug('Received request: ' + JSON.stringify(request));
  17401. try {
  17402. var func = configuration.rpc[request.method];
  17403. if (func === undefined) {
  17404. Logger.error("Method " + request.method +
  17405. " not registered in client");
  17406. } else {
  17407. func(request.params, request);
  17408. }
  17409. } catch (err) {
  17410. Logger.error('Exception processing request: ' + JSON.stringify(
  17411. request));
  17412. Logger.error(err);
  17413. }
  17414. });
  17415. this.send = function (method, params, callback) {
  17416. if (method !== 'ping') {
  17417. Logger.debug('Request: method:' + method + " params:" + JSON.stringify(
  17418. params));
  17419. }
  17420. var requestTime = Date.now();
  17421. rpc.encode(method, params, function (error, result) {
  17422. if (error) {
  17423. try {
  17424. Logger.error("ERROR:" + error.message + " in Request: method:" +
  17425. method + " params:" + JSON.stringify(params) + " request:" +
  17426. error.request);
  17427. if (error.data) {
  17428. Logger.error("ERROR DATA:" + JSON.stringify(error.data));
  17429. }
  17430. } catch (e) {}
  17431. error.requestTime = requestTime;
  17432. }
  17433. if (callback) {
  17434. if (result != undefined && result.value !== 'pong') {
  17435. Logger.debug('Response: ' + JSON.stringify(result));
  17436. }
  17437. callback(error, result);
  17438. }
  17439. });
  17440. }
  17441. function updateNotReconnectIfLessThan() {
  17442. Logger.debug("notReconnectIfNumLessThan = " + pingNextNum + ' (old=' +
  17443. notReconnectIfNumLessThan + ')');
  17444. notReconnectIfNumLessThan = pingNextNum;
  17445. }
  17446. function sendPing() {
  17447. if (enabledPings) {
  17448. var params = null;
  17449. if (pingNextNum == 0 || pingNextNum == notReconnectIfNumLessThan) {
  17450. params = {
  17451. interval: configuration.heartbeat || PING_INTERVAL
  17452. };
  17453. }
  17454. pingNextNum++;
  17455. self.send('ping', params, (function (pingNum) {
  17456. return function (error, result) {
  17457. if (error) {
  17458. Logger.debug("Error in ping request #" + pingNum + " (" +
  17459. error.message + ")");
  17460. if (pingNum > notReconnectIfNumLessThan) {
  17461. enabledPings = false;
  17462. updateNotReconnectIfLessThan();
  17463. Logger.debug("Server did not respond to ping message #" +
  17464. pingNum + ". Reconnecting... ");
  17465. ws.reconnectWs();
  17466. }
  17467. }
  17468. }
  17469. })(pingNextNum));
  17470. } else {
  17471. Logger.debug("Trying to send ping, but ping is not enabled");
  17472. }
  17473. }
  17474. /*
  17475. * If configuration.hearbeat has any value, the ping-pong will work with the interval
  17476. * of configuration.hearbeat
  17477. */
  17478. function usePing() {
  17479. if (!pingPongStarted) {
  17480. Logger.debug("Starting ping (if configured)")
  17481. pingPongStarted = true;
  17482. if (configuration.heartbeat != undefined) {
  17483. pingInterval = setInterval(sendPing, configuration.heartbeat);
  17484. sendPing();
  17485. }
  17486. }
  17487. }
  17488. this.close = function () {
  17489. Logger.debug("Closing jsonRpcClient explicitly by client");
  17490. if (pingInterval != undefined) {
  17491. Logger.debug("Clearing ping interval");
  17492. clearInterval(pingInterval);
  17493. }
  17494. pingPongStarted = false;
  17495. enabledPings = false;
  17496. if (configuration.sendCloseMessage) {
  17497. Logger.debug("Sending close message")
  17498. this.send('closeSession', null, function (error, result) {
  17499. if (error) {
  17500. Logger.error("Error sending close message: " + JSON.stringify(
  17501. error));
  17502. }
  17503. ws.close();
  17504. });
  17505. } else {
  17506. ws.close();
  17507. }
  17508. }
  17509. // This method is only for testing
  17510. this.forceClose = function (millis) {
  17511. ws.forceClose(millis);
  17512. }
  17513. this.reconnect = function () {
  17514. ws.reconnectWs();
  17515. }
  17516. }
  17517. module.exports = JsonRpcClient;
  17518. },{"../..":117,"./transports/webSocketWithReconnection":116}],115:[function(require,module,exports){
  17519. /*
  17520. * (C) Copyright 2014 Kurento (http://kurento.org/)
  17521. *
  17522. * Licensed under the Apache License, Version 2.0 (the "License");
  17523. * you may not use this file except in compliance with the License.
  17524. * You may obtain a copy of the License at
  17525. *
  17526. * http://www.apache.org/licenses/LICENSE-2.0
  17527. *
  17528. * Unless required by applicable law or agreed to in writing, software
  17529. * distributed under the License is distributed on an "AS IS" BASIS,
  17530. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17531. * See the License for the specific language governing permissions and
  17532. * limitations under the License.
  17533. *
  17534. */
  17535. var WebSocketWithReconnection = require('./webSocketWithReconnection');
  17536. exports.WebSocketWithReconnection = WebSocketWithReconnection;
  17537. },{"./webSocketWithReconnection":116}],116:[function(require,module,exports){
  17538. (function (global){
  17539. /*
  17540. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  17541. *
  17542. * Licensed under the Apache License, Version 2.0 (the "License");
  17543. * you may not use this file except in compliance with the License.
  17544. * You may obtain a copy of the License at
  17545. *
  17546. * http://www.apache.org/licenses/LICENSE-2.0
  17547. *
  17548. * Unless required by applicable law or agreed to in writing, software
  17549. * distributed under the License is distributed on an "AS IS" BASIS,
  17550. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17551. * See the License for the specific language governing permissions and
  17552. * limitations under the License.
  17553. */
  17554. "use strict";
  17555. var BrowserWebSocket = global.WebSocket || global.MozWebSocket;
  17556. var Logger = console;
  17557. /**
  17558. * Get either the `WebSocket` or `MozWebSocket` globals
  17559. * in the browser or try to resolve WebSocket-compatible
  17560. * interface exposed by `ws` for Node-like environment.
  17561. */
  17562. var WebSocket = BrowserWebSocket;
  17563. if (!WebSocket && typeof window === 'undefined') {
  17564. try {
  17565. WebSocket = require('ws');
  17566. } catch (e) {}
  17567. }
  17568. //var SockJS = require('sockjs-client');
  17569. var MAX_RETRIES = 2000; // Forever...
  17570. var RETRY_TIME_MS = 3000; // FIXME: Implement exponential wait times...
  17571. var CONNECTING = 0;
  17572. var OPEN = 1;
  17573. var CLOSING = 2;
  17574. var CLOSED = 3;
  17575. /*
  17576. config = {
  17577. uri : wsUri,
  17578. useSockJS : true (use SockJS) / false (use WebSocket) by default,
  17579. onconnected : callback method to invoke when connection is successful,
  17580. ondisconnect : callback method to invoke when the connection is lost,
  17581. onreconnecting : callback method to invoke when the client is reconnecting,
  17582. onreconnected : callback method to invoke when the client succesfully reconnects,
  17583. };
  17584. */
  17585. function WebSocketWithReconnection(config) {
  17586. var closing = false;
  17587. var registerMessageHandler;
  17588. var wsUri = config.uri;
  17589. var useSockJS = config.useSockJS;
  17590. var reconnecting = false;
  17591. var forcingDisconnection = false;
  17592. var ws;
  17593. if (useSockJS) {
  17594. ws = new SockJS(wsUri);
  17595. } else {
  17596. ws = new WebSocket(wsUri);
  17597. }
  17598. ws.onopen = function () {
  17599. logConnected(ws, wsUri);
  17600. if (config.onconnected) {
  17601. config.onconnected();
  17602. }
  17603. };
  17604. ws.onerror = function (error) {
  17605. Logger.error("Could not connect to " + wsUri +
  17606. " (invoking onerror if defined)", error);
  17607. if (config.onerror) {
  17608. config.onerror(error);
  17609. }
  17610. };
  17611. function logConnected(ws, wsUri) {
  17612. try {
  17613. Logger.debug("WebSocket connected to " + wsUri);
  17614. } catch (e) {
  17615. Logger.error(e);
  17616. }
  17617. }
  17618. var reconnectionOnClose = function () {
  17619. if (ws.readyState === CLOSED) {
  17620. if (closing) {
  17621. Logger.debug("Connection closed by user");
  17622. } else {
  17623. Logger.debug("Connection closed unexpectecly. Reconnecting...");
  17624. reconnectToSameUri(MAX_RETRIES, 1);
  17625. }
  17626. } else {
  17627. Logger.debug("Close callback from previous websocket. Ignoring it");
  17628. }
  17629. };
  17630. ws.onclose = reconnectionOnClose;
  17631. function reconnectToSameUri(maxRetries, numRetries) {
  17632. Logger.debug("reconnectToSameUri (attempt #" + numRetries + ", max=" +
  17633. maxRetries + ")");
  17634. if (numRetries === 1) {
  17635. if (reconnecting) {
  17636. Logger.warn(
  17637. "Trying to reconnectToNewUri when reconnecting... Ignoring this reconnection."
  17638. )
  17639. return;
  17640. } else {
  17641. reconnecting = true;
  17642. }
  17643. if (config.onreconnecting) {
  17644. config.onreconnecting();
  17645. }
  17646. }
  17647. if (forcingDisconnection) {
  17648. reconnectToNewUri(maxRetries, numRetries, wsUri);
  17649. } else {
  17650. if (config.newWsUriOnReconnection) {
  17651. config.newWsUriOnReconnection(function (error, newWsUri) {
  17652. if (error) {
  17653. Logger.debug(error);
  17654. setTimeout(function () {
  17655. reconnectToSameUri(maxRetries, numRetries + 1);
  17656. }, RETRY_TIME_MS);
  17657. } else {
  17658. reconnectToNewUri(maxRetries, numRetries, newWsUri);
  17659. }
  17660. })
  17661. } else {
  17662. reconnectToNewUri(maxRetries, numRetries, wsUri);
  17663. }
  17664. }
  17665. }
  17666. // TODO Test retries. How to force not connection?
  17667. function reconnectToNewUri(maxRetries, numRetries, reconnectWsUri) {
  17668. Logger.debug("Reconnection attempt #" + numRetries);
  17669. ws.close();
  17670. wsUri = reconnectWsUri || wsUri;
  17671. var newWs;
  17672. if (useSockJS) {
  17673. newWs = new SockJS(wsUri);
  17674. } else {
  17675. newWs = new WebSocket(wsUri);
  17676. }
  17677. newWs.onopen = function () {
  17678. Logger.debug("Reconnected after " + numRetries + " attempts...");
  17679. logConnected(newWs, wsUri);
  17680. reconnecting = false;
  17681. registerMessageHandler();
  17682. if (config.onreconnected()) {
  17683. config.onreconnected();
  17684. }
  17685. newWs.onclose = reconnectionOnClose;
  17686. };
  17687. var onErrorOrClose = function (error) {
  17688. Logger.warn("Reconnection error: ", error);
  17689. if (numRetries === maxRetries) {
  17690. if (config.ondisconnect) {
  17691. config.ondisconnect();
  17692. }
  17693. } else {
  17694. setTimeout(function () {
  17695. reconnectToSameUri(maxRetries, numRetries + 1);
  17696. }, RETRY_TIME_MS);
  17697. }
  17698. };
  17699. newWs.onerror = onErrorOrClose;
  17700. ws = newWs;
  17701. }
  17702. this.close = function () {
  17703. closing = true;
  17704. ws.close();
  17705. };
  17706. // This method is only for testing
  17707. this.forceClose = function (millis) {
  17708. Logger.debug("Testing: Force WebSocket close");
  17709. if (millis) {
  17710. Logger.debug("Testing: Change wsUri for " + millis +
  17711. " millis to simulate net failure");
  17712. var goodWsUri = wsUri;
  17713. wsUri = "wss://21.234.12.34.4:443/";
  17714. forcingDisconnection = true;
  17715. setTimeout(function () {
  17716. Logger.debug("Testing: Recover good wsUri " + goodWsUri);
  17717. wsUri = goodWsUri;
  17718. forcingDisconnection = false;
  17719. }, millis);
  17720. }
  17721. ws.close();
  17722. };
  17723. this.reconnectWs = function () {
  17724. Logger.debug("reconnectWs");
  17725. reconnectToSameUri(MAX_RETRIES, 1, wsUri);
  17726. };
  17727. this.send = function (message) {
  17728. ws.send(message);
  17729. };
  17730. this.addEventListener = function (type, callback) {
  17731. registerMessageHandler = function () {
  17732. ws.addEventListener(type, callback);
  17733. };
  17734. registerMessageHandler();
  17735. };
  17736. }
  17737. module.exports = WebSocketWithReconnection;
  17738. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  17739. },{"ws":154}],117:[function(require,module,exports){
  17740. /*
  17741. * (C) Copyright 2014 Kurento (http://kurento.org/)
  17742. *
  17743. * Licensed under the Apache License, Version 2.0 (the "License");
  17744. * you may not use this file except in compliance with the License.
  17745. * You may obtain a copy of the License at
  17746. *
  17747. * http://www.apache.org/licenses/LICENSE-2.0
  17748. *
  17749. * Unless required by applicable law or agreed to in writing, software
  17750. * distributed under the License is distributed on an "AS IS" BASIS,
  17751. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17752. * See the License for the specific language governing permissions and
  17753. * limitations under the License.
  17754. *
  17755. */
  17756. var defineProperty_IE8 = false
  17757. if (Object.defineProperty) {
  17758. try {
  17759. Object.defineProperty({}, "x", {});
  17760. } catch (e) {
  17761. defineProperty_IE8 = true
  17762. }
  17763. }
  17764. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
  17765. if (!Function.prototype.bind) {
  17766. Function.prototype.bind = function (oThis) {
  17767. if (typeof this !== 'function') {
  17768. // closest thing possible to the ECMAScript 5
  17769. // internal IsCallable function
  17770. throw new TypeError(
  17771. 'Function.prototype.bind - what is trying to be bound is not callable'
  17772. );
  17773. }
  17774. var aArgs = Array.prototype.slice.call(arguments, 1),
  17775. fToBind = this,
  17776. fNOP = function () {},
  17777. fBound = function () {
  17778. return fToBind.apply(this instanceof fNOP && oThis ?
  17779. this :
  17780. oThis,
  17781. aArgs.concat(Array.prototype.slice.call(arguments)));
  17782. };
  17783. fNOP.prototype = this.prototype;
  17784. fBound.prototype = new fNOP();
  17785. return fBound;
  17786. };
  17787. }
  17788. var EventEmitter = require('events').EventEmitter;
  17789. var inherits = require('inherits');
  17790. var packers = require('./packers');
  17791. var Mapper = require('./Mapper');
  17792. var BASE_TIMEOUT = 5000;
  17793. function unifyResponseMethods(responseMethods) {
  17794. if (!responseMethods) return {};
  17795. for (var key in responseMethods) {
  17796. var value = responseMethods[key];
  17797. if (typeof value == 'string')
  17798. responseMethods[key] = {
  17799. response: value
  17800. }
  17801. };
  17802. return responseMethods;
  17803. };
  17804. function unifyTransport(transport) {
  17805. if (!transport) return;
  17806. // Transport as a function
  17807. if (transport instanceof Function)
  17808. return {
  17809. send: transport
  17810. };
  17811. // WebSocket & DataChannel
  17812. if (transport.send instanceof Function)
  17813. return transport;
  17814. // Message API (Inter-window & WebWorker)
  17815. if (transport.postMessage instanceof Function) {
  17816. transport.send = transport.postMessage;
  17817. return transport;
  17818. }
  17819. // Stream API
  17820. if (transport.write instanceof Function) {
  17821. transport.send = transport.write;
  17822. return transport;
  17823. }
  17824. // Transports that only can receive messages, but not send
  17825. if (transport.onmessage !== undefined) return;
  17826. if (transport.pause instanceof Function) return;
  17827. throw new SyntaxError("Transport is not a function nor a valid object");
  17828. };
  17829. /**
  17830. * Representation of a RPC notification
  17831. *
  17832. * @class
  17833. *
  17834. * @constructor
  17835. *
  17836. * @param {String} method -method of the notification
  17837. * @param params - parameters of the notification
  17838. */
  17839. function RpcNotification(method, params) {
  17840. if (defineProperty_IE8) {
  17841. this.method = method
  17842. this.params = params
  17843. } else {
  17844. Object.defineProperty(this, 'method', {
  17845. value: method,
  17846. enumerable: true
  17847. });
  17848. Object.defineProperty(this, 'params', {
  17849. value: params,
  17850. enumerable: true
  17851. });
  17852. }
  17853. };
  17854. /**
  17855. * @class
  17856. *
  17857. * @constructor
  17858. *
  17859. * @param {object} packer
  17860. *
  17861. * @param {object} [options]
  17862. *
  17863. * @param {object} [transport]
  17864. *
  17865. * @param {Function} [onRequest]
  17866. */
  17867. function RpcBuilder(packer, options, transport, onRequest) {
  17868. var self = this;
  17869. if (!packer)
  17870. throw new SyntaxError('Packer is not defined');
  17871. if (!packer.pack || !packer.unpack)
  17872. throw new SyntaxError('Packer is invalid');
  17873. var responseMethods = unifyResponseMethods(packer.responseMethods);
  17874. if (options instanceof Function) {
  17875. if (transport != undefined)
  17876. throw new SyntaxError("There can't be parameters after onRequest");
  17877. onRequest = options;
  17878. transport = undefined;
  17879. options = undefined;
  17880. };
  17881. if (options && options.send instanceof Function) {
  17882. if (transport && !(transport instanceof Function))
  17883. throw new SyntaxError("Only a function can be after transport");
  17884. onRequest = transport;
  17885. transport = options;
  17886. options = undefined;
  17887. };
  17888. if (transport instanceof Function) {
  17889. if (onRequest != undefined)
  17890. throw new SyntaxError("There can't be parameters after onRequest");
  17891. onRequest = transport;
  17892. transport = undefined;
  17893. };
  17894. if (transport && transport.send instanceof Function)
  17895. if (onRequest && !(onRequest instanceof Function))
  17896. throw new SyntaxError("Only a function can be after transport");
  17897. options = options || {};
  17898. EventEmitter.call(this);
  17899. if (onRequest)
  17900. this.on('request', onRequest);
  17901. if (defineProperty_IE8)
  17902. this.peerID = options.peerID
  17903. else
  17904. Object.defineProperty(this, 'peerID', {
  17905. value: options.peerID
  17906. });
  17907. var max_retries = options.max_retries || 0;
  17908. function transportMessage(event) {
  17909. self.decode(event.data || event.toString());
  17910. };
  17911. this.getTransport = function () {
  17912. return transport;
  17913. }
  17914. this.setTransport = function (value) {
  17915. // Remove listener from old transport
  17916. if (transport) {
  17917. // W3C transports
  17918. if (transport.removeEventListener)
  17919. transport.removeEventListener('message', transportMessage);
  17920. // Node.js Streams API
  17921. else if (transport.removeListener)
  17922. transport.removeListener('data', transportMessage);
  17923. };
  17924. // Set listener on new transport
  17925. if (value) {
  17926. // W3C transports
  17927. if (value.addEventListener)
  17928. value.addEventListener('message', transportMessage);
  17929. // Node.js Streams API
  17930. else if (value.addListener)
  17931. value.addListener('data', transportMessage);
  17932. };
  17933. transport = unifyTransport(value);
  17934. }
  17935. if (!defineProperty_IE8)
  17936. Object.defineProperty(this, 'transport', {
  17937. get: this.getTransport.bind(this),
  17938. set: this.setTransport.bind(this)
  17939. })
  17940. this.setTransport(transport);
  17941. var request_timeout = options.request_timeout || BASE_TIMEOUT;
  17942. var ping_request_timeout = options.ping_request_timeout || request_timeout;
  17943. var response_timeout = options.response_timeout || BASE_TIMEOUT;
  17944. var duplicates_timeout = options.duplicates_timeout || BASE_TIMEOUT;
  17945. var requestID = 0;
  17946. var requests = new Mapper();
  17947. var responses = new Mapper();
  17948. var processedResponses = new Mapper();
  17949. var message2Key = {};
  17950. /**
  17951. * Store the response to prevent to process duplicate request later
  17952. */
  17953. function storeResponse(message, id, dest) {
  17954. var response = {
  17955. message: message,
  17956. /** Timeout to auto-clean old responses */
  17957. timeout: setTimeout(function () {
  17958. responses.remove(id, dest);
  17959. },
  17960. response_timeout)
  17961. };
  17962. responses.set(response, id, dest);
  17963. };
  17964. /**
  17965. * Store the response to ignore duplicated messages later
  17966. */
  17967. function storeProcessedResponse(ack, from) {
  17968. var timeout = setTimeout(function () {
  17969. processedResponses.remove(ack, from);
  17970. },
  17971. duplicates_timeout);
  17972. processedResponses.set(timeout, ack, from);
  17973. };
  17974. /**
  17975. * Representation of a RPC request
  17976. *
  17977. * @class
  17978. * @extends RpcNotification
  17979. *
  17980. * @constructor
  17981. *
  17982. * @param {String} method -method of the notification
  17983. * @param params - parameters of the notification
  17984. * @param {Integer} id - identifier of the request
  17985. * @param [from] - source of the notification
  17986. */
  17987. function RpcRequest(method, params, id, from, transport) {
  17988. RpcNotification.call(this, method, params);
  17989. this.getTransport = function () {
  17990. return transport;
  17991. }
  17992. this.setTransport = function (value) {
  17993. transport = unifyTransport(value);
  17994. }
  17995. if (!defineProperty_IE8)
  17996. Object.defineProperty(this, 'transport', {
  17997. get: this.getTransport.bind(this),
  17998. set: this.setTransport.bind(this)
  17999. })
  18000. var response = responses.get(id, from);
  18001. /**
  18002. * @constant {Boolean} duplicated
  18003. */
  18004. if (!(transport || self.getTransport())) {
  18005. if (defineProperty_IE8)
  18006. this.duplicated = Boolean(response)
  18007. else
  18008. Object.defineProperty(this, 'duplicated', {
  18009. value: Boolean(response)
  18010. });
  18011. }
  18012. var responseMethod = responseMethods[method];
  18013. this.pack = packer.pack.bind(packer, this, id)
  18014. /**
  18015. * Generate a response to this request
  18016. *
  18017. * @param {Error} [error]
  18018. * @param {*} [result]
  18019. *
  18020. * @returns {string}
  18021. */
  18022. this.reply = function (error, result, transport) {
  18023. // Fix optional parameters
  18024. if (error instanceof Function || error && error
  18025. .send instanceof Function) {
  18026. if (result != undefined)
  18027. throw new SyntaxError("There can't be parameters after callback");
  18028. transport = error;
  18029. result = null;
  18030. error = undefined;
  18031. } else if (result instanceof Function ||
  18032. result && result.send instanceof Function) {
  18033. if (transport != undefined)
  18034. throw new SyntaxError("There can't be parameters after callback");
  18035. transport = result;
  18036. result = null;
  18037. };
  18038. transport = unifyTransport(transport);
  18039. // Duplicated request, remove old response timeout
  18040. if (response)
  18041. clearTimeout(response.timeout);
  18042. if (from != undefined) {
  18043. if (error)
  18044. error.dest = from;
  18045. if (result)
  18046. result.dest = from;
  18047. };
  18048. var message;
  18049. // New request or overriden one, create new response with provided data
  18050. if (error || result != undefined) {
  18051. if (self.peerID != undefined) {
  18052. if (error)
  18053. error.from = self.peerID;
  18054. else
  18055. result.from = self.peerID;
  18056. }
  18057. // Protocol indicates that responses has own request methods
  18058. if (responseMethod) {
  18059. if (responseMethod.error == undefined && error)
  18060. message = {
  18061. error: error
  18062. };
  18063. else {
  18064. var method = error ?
  18065. responseMethod.error :
  18066. responseMethod.response;
  18067. message = {
  18068. method: method,
  18069. params: error || result
  18070. };
  18071. }
  18072. } else
  18073. message = {
  18074. error: error,
  18075. result: result
  18076. };
  18077. message = packer.pack(message, id);
  18078. }
  18079. // Duplicate & not-overriden request, re-send old response
  18080. else if (response)
  18081. message = response.message;
  18082. // New empty reply, response null value
  18083. else
  18084. message = packer.pack({
  18085. result: null
  18086. }, id);
  18087. // Store the response to prevent to process a duplicated request later
  18088. storeResponse(message, id, from);
  18089. // Return the stored response so it can be directly send back
  18090. transport = transport || this.getTransport() || self.getTransport();
  18091. if (transport)
  18092. return transport.send(message);
  18093. return message;
  18094. }
  18095. };
  18096. inherits(RpcRequest, RpcNotification);
  18097. function cancel(message) {
  18098. var key = message2Key[message];
  18099. if (!key) return;
  18100. delete message2Key[message];
  18101. var request = requests.pop(key.id, key.dest);
  18102. if (!request) return;
  18103. clearTimeout(request.timeout);
  18104. // Start duplicated responses timeout
  18105. storeProcessedResponse(key.id, key.dest);
  18106. };
  18107. /**
  18108. * Allow to cancel a request and don't wait for a response
  18109. *
  18110. * If `message` is not given, cancel all the request
  18111. */
  18112. this.cancel = function (message) {
  18113. if (message) return cancel(message);
  18114. for (var message in message2Key)
  18115. cancel(message);
  18116. };
  18117. this.close = function () {
  18118. // Prevent to receive new messages
  18119. var transport = this.getTransport();
  18120. if (transport && transport.close)
  18121. transport.close();
  18122. // Request & processed responses
  18123. this.cancel();
  18124. processedResponses.forEach(clearTimeout);
  18125. // Responses
  18126. responses.forEach(function (response) {
  18127. clearTimeout(response.timeout);
  18128. });
  18129. };
  18130. /**
  18131. * Generates and encode a JsonRPC 2.0 message
  18132. *
  18133. * @param {String} method -method of the notification
  18134. * @param params - parameters of the notification
  18135. * @param [dest] - destination of the notification
  18136. * @param {object} [transport] - transport where to send the message
  18137. * @param [callback] - function called when a response to this request is
  18138. * received. If not defined, a notification will be send instead
  18139. *
  18140. * @returns {string} A raw JsonRPC 2.0 request or notification string
  18141. */
  18142. this.encode = function (method, params, dest, transport, callback) {
  18143. // Fix optional parameters
  18144. if (params instanceof Function) {
  18145. if (dest != undefined)
  18146. throw new SyntaxError("There can't be parameters after callback");
  18147. callback = params;
  18148. transport = undefined;
  18149. dest = undefined;
  18150. params = undefined;
  18151. } else if (dest instanceof Function) {
  18152. if (transport != undefined)
  18153. throw new SyntaxError("There can't be parameters after callback");
  18154. callback = dest;
  18155. transport = undefined;
  18156. dest = undefined;
  18157. } else if (transport instanceof Function) {
  18158. if (callback != undefined)
  18159. throw new SyntaxError("There can't be parameters after callback");
  18160. callback = transport;
  18161. transport = undefined;
  18162. };
  18163. if (self.peerID != undefined) {
  18164. params = params || {};
  18165. params.from = self.peerID;
  18166. };
  18167. if (dest != undefined) {
  18168. params = params || {};
  18169. params.dest = dest;
  18170. };
  18171. // Encode message
  18172. var message = {
  18173. method: method,
  18174. params: params
  18175. };
  18176. if (callback) {
  18177. var id = requestID++;
  18178. var retried = 0;
  18179. message = packer.pack(message, id);
  18180. function dispatchCallback(error, result) {
  18181. self.cancel(message);
  18182. callback(error, result);
  18183. };
  18184. var request = {
  18185. message: message,
  18186. callback: dispatchCallback,
  18187. responseMethods: responseMethods[method] || {}
  18188. };
  18189. var encode_transport = unifyTransport(transport);
  18190. function sendRequest(transport) {
  18191. var rt = (method === 'ping' ? ping_request_timeout : request_timeout);
  18192. request.timeout = setTimeout(timeout, rt * Math.pow(2, retried++));
  18193. message2Key[message] = {
  18194. id: id,
  18195. dest: dest
  18196. };
  18197. requests.set(request, id, dest);
  18198. transport = transport || encode_transport || self.getTransport();
  18199. if (transport)
  18200. return transport.send(message);
  18201. return message;
  18202. };
  18203. function retry(transport) {
  18204. transport = unifyTransport(transport);
  18205. console.warn(retried + ' retry for request message:', message);
  18206. var timeout = processedResponses.pop(id, dest);
  18207. clearTimeout(timeout);
  18208. return sendRequest(transport);
  18209. };
  18210. function timeout() {
  18211. if (retried < max_retries)
  18212. return retry(transport);
  18213. var error = new Error('Request has timed out');
  18214. error.request = message;
  18215. error.retry = retry;
  18216. dispatchCallback(error)
  18217. };
  18218. return sendRequest(transport);
  18219. };
  18220. // Return the packed message
  18221. message = packer.pack(message);
  18222. transport = transport || this.getTransport();
  18223. if (transport)
  18224. return transport.send(message);
  18225. return message;
  18226. };
  18227. /**
  18228. * Decode and process a JsonRPC 2.0 message
  18229. *
  18230. * @param {string} message - string with the content of the message
  18231. *
  18232. * @returns {RpcNotification|RpcRequest|undefined} - the representation of the
  18233. * notification or the request. If a response was processed, it will return
  18234. * `undefined` to notify that it was processed
  18235. *
  18236. * @throws {TypeError} - Message is not defined
  18237. */
  18238. this.decode = function (message, transport) {
  18239. if (!message)
  18240. throw new TypeError("Message is not defined");
  18241. try {
  18242. message = packer.unpack(message);
  18243. } catch (e) {
  18244. // Ignore invalid messages
  18245. return console.debug(e, message);
  18246. };
  18247. var id = message.id;
  18248. var ack = message.ack;
  18249. var method = message.method;
  18250. var params = message.params || {};
  18251. var from = params.from;
  18252. var dest = params.dest;
  18253. // Ignore messages send by us
  18254. if (self.peerID != undefined && from == self.peerID) return;
  18255. // Notification
  18256. if (id == undefined && ack == undefined) {
  18257. var notification = new RpcNotification(method, params);
  18258. if (self.emit('request', notification)) return;
  18259. return notification;
  18260. };
  18261. function processRequest() {
  18262. // If we have a transport and it's a duplicated request, reply inmediatly
  18263. transport = unifyTransport(transport) || self.getTransport();
  18264. if (transport) {
  18265. var response = responses.get(id, from);
  18266. if (response)
  18267. return transport.send(response.message);
  18268. };
  18269. var idAck = (id != undefined) ? id : ack;
  18270. var request = new RpcRequest(method, params, idAck, from, transport);
  18271. if (self.emit('request', request)) return;
  18272. return request;
  18273. };
  18274. function processResponse(request, error, result) {
  18275. request.callback(error, result);
  18276. };
  18277. function duplicatedResponse(timeout) {
  18278. console.warn("Response already processed", message);
  18279. // Update duplicated responses timeout
  18280. clearTimeout(timeout);
  18281. storeProcessedResponse(ack, from);
  18282. };
  18283. // Request, or response with own method
  18284. if (method) {
  18285. // Check if it's a response with own method
  18286. if (dest == undefined || dest == self.peerID) {
  18287. var request = requests.get(ack, from);
  18288. if (request) {
  18289. var responseMethods = request.responseMethods;
  18290. if (method == responseMethods.error)
  18291. return processResponse(request, params);
  18292. if (method == responseMethods.response)
  18293. return processResponse(request, null, params);
  18294. return processRequest();
  18295. }
  18296. var processed = processedResponses.get(ack, from);
  18297. if (processed)
  18298. return duplicatedResponse(processed);
  18299. }
  18300. // Request
  18301. return processRequest();
  18302. };
  18303. var error = message.error;
  18304. var result = message.result;
  18305. // Ignore responses not send to us
  18306. if (error && error.dest && error.dest != self.peerID) return;
  18307. if (result && result.dest && result.dest != self.peerID) return;
  18308. // Response
  18309. var request = requests.get(ack, from);
  18310. if (!request) {
  18311. var processed = processedResponses.get(ack, from);
  18312. if (processed)
  18313. return duplicatedResponse(processed);
  18314. return console.warn("No callback was defined for this message",
  18315. message);
  18316. };
  18317. // Process response
  18318. processResponse(request, error, result);
  18319. };
  18320. };
  18321. inherits(RpcBuilder, EventEmitter);
  18322. RpcBuilder.RpcNotification = RpcNotification;
  18323. module.exports = RpcBuilder;
  18324. var clients = require('./clients');
  18325. var transports = require('./clients/transports');
  18326. RpcBuilder.clients = clients;
  18327. RpcBuilder.clients.transports = transports;
  18328. RpcBuilder.packers = packers;
  18329. },{"./Mapper":112,"./clients":113,"./clients/transports":115,"./packers":120,"events":21,"inherits":"inherits"}],118:[function(require,module,exports){
  18330. /**
  18331. * JsonRPC 2.0 packer
  18332. */
  18333. /**
  18334. * Pack a JsonRPC 2.0 message
  18335. *
  18336. * @param {Object} message - object to be packaged. It requires to have all the
  18337. * fields needed by the JsonRPC 2.0 message that it's going to be generated
  18338. *
  18339. * @return {String} - the stringified JsonRPC 2.0 message
  18340. */
  18341. function pack(message, id) {
  18342. var result = {
  18343. jsonrpc: "2.0"
  18344. };
  18345. // Request
  18346. if (message.method) {
  18347. result.method = message.method;
  18348. if (message.params)
  18349. result.params = message.params;
  18350. // Request is a notification
  18351. if (id != undefined)
  18352. result.id = id;
  18353. }
  18354. // Response
  18355. else if (id != undefined) {
  18356. if (message.error) {
  18357. if (message.result !== undefined)
  18358. throw new TypeError("Both result and error are defined");
  18359. result.error = message.error;
  18360. } else if (message.result !== undefined)
  18361. result.result = message.result;
  18362. else
  18363. throw new TypeError("No result or error is defined");
  18364. result.id = id;
  18365. };
  18366. return JSON.stringify(result);
  18367. };
  18368. /**
  18369. * Unpack a JsonRPC 2.0 message
  18370. *
  18371. * @param {String} message - string with the content of the JsonRPC 2.0 message
  18372. *
  18373. * @throws {TypeError} - Invalid JsonRPC version
  18374. *
  18375. * @return {Object} - object filled with the JsonRPC 2.0 message content
  18376. */
  18377. function unpack(message) {
  18378. var result = message;
  18379. if (typeof message === 'string' || message instanceof String) {
  18380. result = JSON.parse(message);
  18381. }
  18382. // Check if it's a valid message
  18383. var version = result.jsonrpc;
  18384. if (version !== '2.0')
  18385. throw new TypeError("Invalid JsonRPC version '" + version + "': " +
  18386. message);
  18387. // Response
  18388. if (result.method == undefined) {
  18389. if (result.id == undefined)
  18390. throw new TypeError("Invalid message: " + message);
  18391. var result_defined = result.result !== undefined;
  18392. var error_defined = result.error !== undefined;
  18393. // Check only result or error is defined, not both or none
  18394. if (result_defined && error_defined)
  18395. throw new TypeError("Both result and error are defined: " + message);
  18396. if (!result_defined && !error_defined)
  18397. throw new TypeError("No result or error is defined: " + message);
  18398. result.ack = result.id;
  18399. delete result.id;
  18400. }
  18401. // Return unpacked message
  18402. return result;
  18403. };
  18404. exports.pack = pack;
  18405. exports.unpack = unpack;
  18406. },{}],119:[function(require,module,exports){
  18407. function pack(message) {
  18408. throw new TypeError("Not yet implemented");
  18409. };
  18410. function unpack(message) {
  18411. throw new TypeError("Not yet implemented");
  18412. };
  18413. exports.pack = pack;
  18414. exports.unpack = unpack;
  18415. },{}],120:[function(require,module,exports){
  18416. var JsonRPC = require('./JsonRPC');
  18417. var XmlRPC = require('./XmlRPC');
  18418. exports.JsonRPC = JsonRPC;
  18419. exports.XmlRPC = XmlRPC;
  18420. },{"./JsonRPC":118,"./XmlRPC":119}],121:[function(require,module,exports){
  18421. (function (process){
  18422. 'use strict';
  18423. if (typeof process === 'undefined' ||
  18424. !process.version ||
  18425. process.version.indexOf('v0.') === 0 ||
  18426. process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  18427. module.exports = { nextTick: nextTick };
  18428. } else {
  18429. module.exports = process
  18430. }
  18431. function nextTick(fn, arg1, arg2, arg3) {
  18432. if (typeof fn !== 'function') {
  18433. throw new TypeError('"callback" argument must be a function');
  18434. }
  18435. var len = arguments.length;
  18436. var args, i;
  18437. switch (len) {
  18438. case 0:
  18439. case 1:
  18440. return process.nextTick(fn);
  18441. case 2:
  18442. return process.nextTick(function afterTickOne() {
  18443. fn.call(null, arg1);
  18444. });
  18445. case 3:
  18446. return process.nextTick(function afterTickTwo() {
  18447. fn.call(null, arg1, arg2);
  18448. });
  18449. case 4:
  18450. return process.nextTick(function afterTickThree() {
  18451. fn.call(null, arg1, arg2, arg3);
  18452. });
  18453. default:
  18454. args = new Array(len - 1);
  18455. i = 0;
  18456. while (i < args.length) {
  18457. args[i++] = arguments[i];
  18458. }
  18459. return process.nextTick(function afterTick() {
  18460. fn.apply(null, args);
  18461. });
  18462. }
  18463. }
  18464. }).call(this,require('_process'))
  18465. },{"_process":122}],122:[function(require,module,exports){
  18466. // shim for using process in browser
  18467. var process = module.exports = {};
  18468. // cached from whatever global is present so that test runners that stub it
  18469. // don't break things. But we need to wrap it in a try catch in case it is
  18470. // wrapped in strict mode code which doesn't define any globals. It's inside a
  18471. // function because try/catches deoptimize in certain engines.
  18472. var cachedSetTimeout;
  18473. var cachedClearTimeout;
  18474. function defaultSetTimout() {
  18475. throw new Error('setTimeout has not been defined');
  18476. }
  18477. function defaultClearTimeout () {
  18478. throw new Error('clearTimeout has not been defined');
  18479. }
  18480. (function () {
  18481. try {
  18482. if (typeof setTimeout === 'function') {
  18483. cachedSetTimeout = setTimeout;
  18484. } else {
  18485. cachedSetTimeout = defaultSetTimout;
  18486. }
  18487. } catch (e) {
  18488. cachedSetTimeout = defaultSetTimout;
  18489. }
  18490. try {
  18491. if (typeof clearTimeout === 'function') {
  18492. cachedClearTimeout = clearTimeout;
  18493. } else {
  18494. cachedClearTimeout = defaultClearTimeout;
  18495. }
  18496. } catch (e) {
  18497. cachedClearTimeout = defaultClearTimeout;
  18498. }
  18499. } ())
  18500. function runTimeout(fun) {
  18501. if (cachedSetTimeout === setTimeout) {
  18502. //normal enviroments in sane situations
  18503. return setTimeout(fun, 0);
  18504. }
  18505. // if setTimeout wasn't available but was latter defined
  18506. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  18507. cachedSetTimeout = setTimeout;
  18508. return setTimeout(fun, 0);
  18509. }
  18510. try {
  18511. // when when somebody has screwed with setTimeout but no I.E. maddness
  18512. return cachedSetTimeout(fun, 0);
  18513. } catch(e){
  18514. try {
  18515. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  18516. return cachedSetTimeout.call(null, fun, 0);
  18517. } catch(e){
  18518. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  18519. return cachedSetTimeout.call(this, fun, 0);
  18520. }
  18521. }
  18522. }
  18523. function runClearTimeout(marker) {
  18524. if (cachedClearTimeout === clearTimeout) {
  18525. //normal enviroments in sane situations
  18526. return clearTimeout(marker);
  18527. }
  18528. // if clearTimeout wasn't available but was latter defined
  18529. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  18530. cachedClearTimeout = clearTimeout;
  18531. return clearTimeout(marker);
  18532. }
  18533. try {
  18534. // when when somebody has screwed with setTimeout but no I.E. maddness
  18535. return cachedClearTimeout(marker);
  18536. } catch (e){
  18537. try {
  18538. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  18539. return cachedClearTimeout.call(null, marker);
  18540. } catch (e){
  18541. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  18542. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  18543. return cachedClearTimeout.call(this, marker);
  18544. }
  18545. }
  18546. }
  18547. var queue = [];
  18548. var draining = false;
  18549. var currentQueue;
  18550. var queueIndex = -1;
  18551. function cleanUpNextTick() {
  18552. if (!draining || !currentQueue) {
  18553. return;
  18554. }
  18555. draining = false;
  18556. if (currentQueue.length) {
  18557. queue = currentQueue.concat(queue);
  18558. } else {
  18559. queueIndex = -1;
  18560. }
  18561. if (queue.length) {
  18562. drainQueue();
  18563. }
  18564. }
  18565. function drainQueue() {
  18566. if (draining) {
  18567. return;
  18568. }
  18569. var timeout = runTimeout(cleanUpNextTick);
  18570. draining = true;
  18571. var len = queue.length;
  18572. while(len) {
  18573. currentQueue = queue;
  18574. queue = [];
  18575. while (++queueIndex < len) {
  18576. if (currentQueue) {
  18577. currentQueue[queueIndex].run();
  18578. }
  18579. }
  18580. queueIndex = -1;
  18581. len = queue.length;
  18582. }
  18583. currentQueue = null;
  18584. draining = false;
  18585. runClearTimeout(timeout);
  18586. }
  18587. process.nextTick = function (fun) {
  18588. var args = new Array(arguments.length - 1);
  18589. if (arguments.length > 1) {
  18590. for (var i = 1; i < arguments.length; i++) {
  18591. args[i - 1] = arguments[i];
  18592. }
  18593. }
  18594. queue.push(new Item(fun, args));
  18595. if (queue.length === 1 && !draining) {
  18596. runTimeout(drainQueue);
  18597. }
  18598. };
  18599. // v8 likes predictible objects
  18600. function Item(fun, array) {
  18601. this.fun = fun;
  18602. this.array = array;
  18603. }
  18604. Item.prototype.run = function () {
  18605. this.fun.apply(null, this.array);
  18606. };
  18607. process.title = 'browser';
  18608. process.browser = true;
  18609. process.env = {};
  18610. process.argv = [];
  18611. process.version = ''; // empty string to avoid regexp issues
  18612. process.versions = {};
  18613. function noop() {}
  18614. process.on = noop;
  18615. process.addListener = noop;
  18616. process.once = noop;
  18617. process.off = noop;
  18618. process.removeListener = noop;
  18619. process.removeAllListeners = noop;
  18620. process.emit = noop;
  18621. process.prependListener = noop;
  18622. process.prependOnceListener = noop;
  18623. process.listeners = function (name) { return [] }
  18624. process.binding = function (name) {
  18625. throw new Error('process.binding is not supported');
  18626. };
  18627. process.cwd = function () { return '/' };
  18628. process.chdir = function (dir) {
  18629. throw new Error('process.chdir is not supported');
  18630. };
  18631. process.umask = function() { return 0; };
  18632. },{}],123:[function(require,module,exports){
  18633. (function (global){
  18634. /*! https://mths.be/punycode v1.4.1 by @mathias */
  18635. ;(function(root) {
  18636. /** Detect free variables */
  18637. var freeExports = typeof exports == 'object' && exports &&
  18638. !exports.nodeType && exports;
  18639. var freeModule = typeof module == 'object' && module &&
  18640. !module.nodeType && module;
  18641. var freeGlobal = typeof global == 'object' && global;
  18642. if (
  18643. freeGlobal.global === freeGlobal ||
  18644. freeGlobal.window === freeGlobal ||
  18645. freeGlobal.self === freeGlobal
  18646. ) {
  18647. root = freeGlobal;
  18648. }
  18649. /**
  18650. * The `punycode` object.
  18651. * @name punycode
  18652. * @type Object
  18653. */
  18654. var punycode,
  18655. /** Highest positive signed 32-bit float value */
  18656. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  18657. /** Bootstring parameters */
  18658. base = 36,
  18659. tMin = 1,
  18660. tMax = 26,
  18661. skew = 38,
  18662. damp = 700,
  18663. initialBias = 72,
  18664. initialN = 128, // 0x80
  18665. delimiter = '-', // '\x2D'
  18666. /** Regular expressions */
  18667. regexPunycode = /^xn--/,
  18668. regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
  18669. regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
  18670. /** Error messages */
  18671. errors = {
  18672. 'overflow': 'Overflow: input needs wider integers to process',
  18673. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  18674. 'invalid-input': 'Invalid input'
  18675. },
  18676. /** Convenience shortcuts */
  18677. baseMinusTMin = base - tMin,
  18678. floor = Math.floor,
  18679. stringFromCharCode = String.fromCharCode,
  18680. /** Temporary variable */
  18681. key;
  18682. /*--------------------------------------------------------------------------*/
  18683. /**
  18684. * A generic error utility function.
  18685. * @private
  18686. * @param {String} type The error type.
  18687. * @returns {Error} Throws a `RangeError` with the applicable error message.
  18688. */
  18689. function error(type) {
  18690. throw new RangeError(errors[type]);
  18691. }
  18692. /**
  18693. * A generic `Array#map` utility function.
  18694. * @private
  18695. * @param {Array} array The array to iterate over.
  18696. * @param {Function} callback The function that gets called for every array
  18697. * item.
  18698. * @returns {Array} A new array of values returned by the callback function.
  18699. */
  18700. function map(array, fn) {
  18701. var length = array.length;
  18702. var result = [];
  18703. while (length--) {
  18704. result[length] = fn(array[length]);
  18705. }
  18706. return result;
  18707. }
  18708. /**
  18709. * A simple `Array#map`-like wrapper to work with domain name strings or email
  18710. * addresses.
  18711. * @private
  18712. * @param {String} domain The domain name or email address.
  18713. * @param {Function} callback The function that gets called for every
  18714. * character.
  18715. * @returns {Array} A new string of characters returned by the callback
  18716. * function.
  18717. */
  18718. function mapDomain(string, fn) {
  18719. var parts = string.split('@');
  18720. var result = '';
  18721. if (parts.length > 1) {
  18722. // In email addresses, only the domain name should be punycoded. Leave
  18723. // the local part (i.e. everything up to `@`) intact.
  18724. result = parts[0] + '@';
  18725. string = parts[1];
  18726. }
  18727. // Avoid `split(regex)` for IE8 compatibility. See #17.
  18728. string = string.replace(regexSeparators, '\x2E');
  18729. var labels = string.split('.');
  18730. var encoded = map(labels, fn).join('.');
  18731. return result + encoded;
  18732. }
  18733. /**
  18734. * Creates an array containing the numeric code points of each Unicode
  18735. * character in the string. While JavaScript uses UCS-2 internally,
  18736. * this function will convert a pair of surrogate halves (each of which
  18737. * UCS-2 exposes as separate characters) into a single code point,
  18738. * matching UTF-16.
  18739. * @see `punycode.ucs2.encode`
  18740. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  18741. * @memberOf punycode.ucs2
  18742. * @name decode
  18743. * @param {String} string The Unicode input string (UCS-2).
  18744. * @returns {Array} The new array of code points.
  18745. */
  18746. function ucs2decode(string) {
  18747. var output = [],
  18748. counter = 0,
  18749. length = string.length,
  18750. value,
  18751. extra;
  18752. while (counter < length) {
  18753. value = string.charCodeAt(counter++);
  18754. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  18755. // high surrogate, and there is a next character
  18756. extra = string.charCodeAt(counter++);
  18757. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  18758. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  18759. } else {
  18760. // unmatched surrogate; only append this code unit, in case the next
  18761. // code unit is the high surrogate of a surrogate pair
  18762. output.push(value);
  18763. counter--;
  18764. }
  18765. } else {
  18766. output.push(value);
  18767. }
  18768. }
  18769. return output;
  18770. }
  18771. /**
  18772. * Creates a string based on an array of numeric code points.
  18773. * @see `punycode.ucs2.decode`
  18774. * @memberOf punycode.ucs2
  18775. * @name encode
  18776. * @param {Array} codePoints The array of numeric code points.
  18777. * @returns {String} The new Unicode string (UCS-2).
  18778. */
  18779. function ucs2encode(array) {
  18780. return map(array, function(value) {
  18781. var output = '';
  18782. if (value > 0xFFFF) {
  18783. value -= 0x10000;
  18784. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  18785. value = 0xDC00 | value & 0x3FF;
  18786. }
  18787. output += stringFromCharCode(value);
  18788. return output;
  18789. }).join('');
  18790. }
  18791. /**
  18792. * Converts a basic code point into a digit/integer.
  18793. * @see `digitToBasic()`
  18794. * @private
  18795. * @param {Number} codePoint The basic numeric code point value.
  18796. * @returns {Number} The numeric value of a basic code point (for use in
  18797. * representing integers) in the range `0` to `base - 1`, or `base` if
  18798. * the code point does not represent a value.
  18799. */
  18800. function basicToDigit(codePoint) {
  18801. if (codePoint - 48 < 10) {
  18802. return codePoint - 22;
  18803. }
  18804. if (codePoint - 65 < 26) {
  18805. return codePoint - 65;
  18806. }
  18807. if (codePoint - 97 < 26) {
  18808. return codePoint - 97;
  18809. }
  18810. return base;
  18811. }
  18812. /**
  18813. * Converts a digit/integer into a basic code point.
  18814. * @see `basicToDigit()`
  18815. * @private
  18816. * @param {Number} digit The numeric value of a basic code point.
  18817. * @returns {Number} The basic code point whose value (when used for
  18818. * representing integers) is `digit`, which needs to be in the range
  18819. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  18820. * used; else, the lowercase form is used. The behavior is undefined
  18821. * if `flag` is non-zero and `digit` has no uppercase form.
  18822. */
  18823. function digitToBasic(digit, flag) {
  18824. // 0..25 map to ASCII a..z or A..Z
  18825. // 26..35 map to ASCII 0..9
  18826. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  18827. }
  18828. /**
  18829. * Bias adaptation function as per section 3.4 of RFC 3492.
  18830. * https://tools.ietf.org/html/rfc3492#section-3.4
  18831. * @private
  18832. */
  18833. function adapt(delta, numPoints, firstTime) {
  18834. var k = 0;
  18835. delta = firstTime ? floor(delta / damp) : delta >> 1;
  18836. delta += floor(delta / numPoints);
  18837. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  18838. delta = floor(delta / baseMinusTMin);
  18839. }
  18840. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  18841. }
  18842. /**
  18843. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  18844. * symbols.
  18845. * @memberOf punycode
  18846. * @param {String} input The Punycode string of ASCII-only symbols.
  18847. * @returns {String} The resulting string of Unicode symbols.
  18848. */
  18849. function decode(input) {
  18850. // Don't use UCS-2
  18851. var output = [],
  18852. inputLength = input.length,
  18853. out,
  18854. i = 0,
  18855. n = initialN,
  18856. bias = initialBias,
  18857. basic,
  18858. j,
  18859. index,
  18860. oldi,
  18861. w,
  18862. k,
  18863. digit,
  18864. t,
  18865. /** Cached calculation results */
  18866. baseMinusT;
  18867. // Handle the basic code points: let `basic` be the number of input code
  18868. // points before the last delimiter, or `0` if there is none, then copy
  18869. // the first basic code points to the output.
  18870. basic = input.lastIndexOf(delimiter);
  18871. if (basic < 0) {
  18872. basic = 0;
  18873. }
  18874. for (j = 0; j < basic; ++j) {
  18875. // if it's not a basic code point
  18876. if (input.charCodeAt(j) >= 0x80) {
  18877. error('not-basic');
  18878. }
  18879. output.push(input.charCodeAt(j));
  18880. }
  18881. // Main decoding loop: start just after the last delimiter if any basic code
  18882. // points were copied; start at the beginning otherwise.
  18883. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  18884. // `index` is the index of the next character to be consumed.
  18885. // Decode a generalized variable-length integer into `delta`,
  18886. // which gets added to `i`. The overflow checking is easier
  18887. // if we increase `i` as we go, then subtract off its starting
  18888. // value at the end to obtain `delta`.
  18889. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  18890. if (index >= inputLength) {
  18891. error('invalid-input');
  18892. }
  18893. digit = basicToDigit(input.charCodeAt(index++));
  18894. if (digit >= base || digit > floor((maxInt - i) / w)) {
  18895. error('overflow');
  18896. }
  18897. i += digit * w;
  18898. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  18899. if (digit < t) {
  18900. break;
  18901. }
  18902. baseMinusT = base - t;
  18903. if (w > floor(maxInt / baseMinusT)) {
  18904. error('overflow');
  18905. }
  18906. w *= baseMinusT;
  18907. }
  18908. out = output.length + 1;
  18909. bias = adapt(i - oldi, out, oldi == 0);
  18910. // `i` was supposed to wrap around from `out` to `0`,
  18911. // incrementing `n` each time, so we'll fix that now:
  18912. if (floor(i / out) > maxInt - n) {
  18913. error('overflow');
  18914. }
  18915. n += floor(i / out);
  18916. i %= out;
  18917. // Insert `n` at position `i` of the output
  18918. output.splice(i++, 0, n);
  18919. }
  18920. return ucs2encode(output);
  18921. }
  18922. /**
  18923. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  18924. * Punycode string of ASCII-only symbols.
  18925. * @memberOf punycode
  18926. * @param {String} input The string of Unicode symbols.
  18927. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  18928. */
  18929. function encode(input) {
  18930. var n,
  18931. delta,
  18932. handledCPCount,
  18933. basicLength,
  18934. bias,
  18935. j,
  18936. m,
  18937. q,
  18938. k,
  18939. t,
  18940. currentValue,
  18941. output = [],
  18942. /** `inputLength` will hold the number of code points in `input`. */
  18943. inputLength,
  18944. /** Cached calculation results */
  18945. handledCPCountPlusOne,
  18946. baseMinusT,
  18947. qMinusT;
  18948. // Convert the input in UCS-2 to Unicode
  18949. input = ucs2decode(input);
  18950. // Cache the length
  18951. inputLength = input.length;
  18952. // Initialize the state
  18953. n = initialN;
  18954. delta = 0;
  18955. bias = initialBias;
  18956. // Handle the basic code points
  18957. for (j = 0; j < inputLength; ++j) {
  18958. currentValue = input[j];
  18959. if (currentValue < 0x80) {
  18960. output.push(stringFromCharCode(currentValue));
  18961. }
  18962. }
  18963. handledCPCount = basicLength = output.length;
  18964. // `handledCPCount` is the number of code points that have been handled;
  18965. // `basicLength` is the number of basic code points.
  18966. // Finish the basic string - if it is not empty - with a delimiter
  18967. if (basicLength) {
  18968. output.push(delimiter);
  18969. }
  18970. // Main encoding loop:
  18971. while (handledCPCount < inputLength) {
  18972. // All non-basic code points < n have been handled already. Find the next
  18973. // larger one:
  18974. for (m = maxInt, j = 0; j < inputLength; ++j) {
  18975. currentValue = input[j];
  18976. if (currentValue >= n && currentValue < m) {
  18977. m = currentValue;
  18978. }
  18979. }
  18980. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  18981. // but guard against overflow
  18982. handledCPCountPlusOne = handledCPCount + 1;
  18983. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  18984. error('overflow');
  18985. }
  18986. delta += (m - n) * handledCPCountPlusOne;
  18987. n = m;
  18988. for (j = 0; j < inputLength; ++j) {
  18989. currentValue = input[j];
  18990. if (currentValue < n && ++delta > maxInt) {
  18991. error('overflow');
  18992. }
  18993. if (currentValue == n) {
  18994. // Represent delta as a generalized variable-length integer
  18995. for (q = delta, k = base; /* no condition */; k += base) {
  18996. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  18997. if (q < t) {
  18998. break;
  18999. }
  19000. qMinusT = q - t;
  19001. baseMinusT = base - t;
  19002. output.push(
  19003. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  19004. );
  19005. q = floor(qMinusT / baseMinusT);
  19006. }
  19007. output.push(stringFromCharCode(digitToBasic(q, 0)));
  19008. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  19009. delta = 0;
  19010. ++handledCPCount;
  19011. }
  19012. }
  19013. ++delta;
  19014. ++n;
  19015. }
  19016. return output.join('');
  19017. }
  19018. /**
  19019. * Converts a Punycode string representing a domain name or an email address
  19020. * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  19021. * it doesn't matter if you call it on a string that has already been
  19022. * converted to Unicode.
  19023. * @memberOf punycode
  19024. * @param {String} input The Punycoded domain name or email address to
  19025. * convert to Unicode.
  19026. * @returns {String} The Unicode representation of the given Punycode
  19027. * string.
  19028. */
  19029. function toUnicode(input) {
  19030. return mapDomain(input, function(string) {
  19031. return regexPunycode.test(string)
  19032. ? decode(string.slice(4).toLowerCase())
  19033. : string;
  19034. });
  19035. }
  19036. /**
  19037. * Converts a Unicode string representing a domain name or an email address to
  19038. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  19039. * i.e. it doesn't matter if you call it with a domain that's already in
  19040. * ASCII.
  19041. * @memberOf punycode
  19042. * @param {String} input The domain name or email address to convert, as a
  19043. * Unicode string.
  19044. * @returns {String} The Punycode representation of the given domain name or
  19045. * email address.
  19046. */
  19047. function toASCII(input) {
  19048. return mapDomain(input, function(string) {
  19049. return regexNonASCII.test(string)
  19050. ? 'xn--' + encode(string)
  19051. : string;
  19052. });
  19053. }
  19054. /*--------------------------------------------------------------------------*/
  19055. /** Define the public API */
  19056. punycode = {
  19057. /**
  19058. * A string representing the current Punycode.js version number.
  19059. * @memberOf punycode
  19060. * @type String
  19061. */
  19062. 'version': '1.4.1',
  19063. /**
  19064. * An object of methods to convert from JavaScript's internal character
  19065. * representation (UCS-2) to Unicode code points, and back.
  19066. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  19067. * @memberOf punycode
  19068. * @type Object
  19069. */
  19070. 'ucs2': {
  19071. 'decode': ucs2decode,
  19072. 'encode': ucs2encode
  19073. },
  19074. 'decode': decode,
  19075. 'encode': encode,
  19076. 'toASCII': toASCII,
  19077. 'toUnicode': toUnicode
  19078. };
  19079. /** Expose `punycode` */
  19080. // Some AMD build optimizers, like r.js, check for specific condition patterns
  19081. // like the following:
  19082. if (
  19083. typeof define == 'function' &&
  19084. typeof define.amd == 'object' &&
  19085. define.amd
  19086. ) {
  19087. define('punycode', function() {
  19088. return punycode;
  19089. });
  19090. } else if (freeExports && freeModule) {
  19091. if (module.exports == freeExports) {
  19092. // in Node.js, io.js, or RingoJS v0.8.0+
  19093. freeModule.exports = punycode;
  19094. } else {
  19095. // in Narwhal or RingoJS v0.7.0-
  19096. for (key in punycode) {
  19097. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  19098. }
  19099. }
  19100. } else {
  19101. // in Rhino or a web browser
  19102. root.punycode = punycode;
  19103. }
  19104. }(this));
  19105. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  19106. },{}],124:[function(require,module,exports){
  19107. // Copyright Joyent, Inc. and other Node contributors.
  19108. //
  19109. // Permission is hereby granted, free of charge, to any person obtaining a
  19110. // copy of this software and associated documentation files (the
  19111. // "Software"), to deal in the Software without restriction, including
  19112. // without limitation the rights to use, copy, modify, merge, publish,
  19113. // distribute, sublicense, and/or sell copies of the Software, and to permit
  19114. // persons to whom the Software is furnished to do so, subject to the
  19115. // following conditions:
  19116. //
  19117. // The above copyright notice and this permission notice shall be included
  19118. // in all copies or substantial portions of the Software.
  19119. //
  19120. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  19121. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19122. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  19123. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19124. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  19125. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  19126. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  19127. 'use strict';
  19128. // If obj.hasOwnProperty has been overridden, then calling
  19129. // obj.hasOwnProperty(prop) will break.
  19130. // See: https://github.com/joyent/node/issues/1707
  19131. function hasOwnProperty(obj, prop) {
  19132. return Object.prototype.hasOwnProperty.call(obj, prop);
  19133. }
  19134. module.exports = function(qs, sep, eq, options) {
  19135. sep = sep || '&';
  19136. eq = eq || '=';
  19137. var obj = {};
  19138. if (typeof qs !== 'string' || qs.length === 0) {
  19139. return obj;
  19140. }
  19141. var regexp = /\+/g;
  19142. qs = qs.split(sep);
  19143. var maxKeys = 1000;
  19144. if (options && typeof options.maxKeys === 'number') {
  19145. maxKeys = options.maxKeys;
  19146. }
  19147. var len = qs.length;
  19148. // maxKeys <= 0 means that we should not limit keys count
  19149. if (maxKeys > 0 && len > maxKeys) {
  19150. len = maxKeys;
  19151. }
  19152. for (var i = 0; i < len; ++i) {
  19153. var x = qs[i].replace(regexp, '%20'),
  19154. idx = x.indexOf(eq),
  19155. kstr, vstr, k, v;
  19156. if (idx >= 0) {
  19157. kstr = x.substr(0, idx);
  19158. vstr = x.substr(idx + 1);
  19159. } else {
  19160. kstr = x;
  19161. vstr = '';
  19162. }
  19163. k = decodeURIComponent(kstr);
  19164. v = decodeURIComponent(vstr);
  19165. if (!hasOwnProperty(obj, k)) {
  19166. obj[k] = v;
  19167. } else if (isArray(obj[k])) {
  19168. obj[k].push(v);
  19169. } else {
  19170. obj[k] = [obj[k], v];
  19171. }
  19172. }
  19173. return obj;
  19174. };
  19175. var isArray = Array.isArray || function (xs) {
  19176. return Object.prototype.toString.call(xs) === '[object Array]';
  19177. };
  19178. },{}],125:[function(require,module,exports){
  19179. // Copyright Joyent, Inc. and other Node contributors.
  19180. //
  19181. // Permission is hereby granted, free of charge, to any person obtaining a
  19182. // copy of this software and associated documentation files (the
  19183. // "Software"), to deal in the Software without restriction, including
  19184. // without limitation the rights to use, copy, modify, merge, publish,
  19185. // distribute, sublicense, and/or sell copies of the Software, and to permit
  19186. // persons to whom the Software is furnished to do so, subject to the
  19187. // following conditions:
  19188. //
  19189. // The above copyright notice and this permission notice shall be included
  19190. // in all copies or substantial portions of the Software.
  19191. //
  19192. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  19193. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19194. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  19195. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19196. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  19197. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  19198. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  19199. 'use strict';
  19200. var stringifyPrimitive = function(v) {
  19201. switch (typeof v) {
  19202. case 'string':
  19203. return v;
  19204. case 'boolean':
  19205. return v ? 'true' : 'false';
  19206. case 'number':
  19207. return isFinite(v) ? v : '';
  19208. default:
  19209. return '';
  19210. }
  19211. };
  19212. module.exports = function(obj, sep, eq, name) {
  19213. sep = sep || '&';
  19214. eq = eq || '=';
  19215. if (obj === null) {
  19216. obj = undefined;
  19217. }
  19218. if (typeof obj === 'object') {
  19219. return map(objectKeys(obj), function(k) {
  19220. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  19221. if (isArray(obj[k])) {
  19222. return map(obj[k], function(v) {
  19223. return ks + encodeURIComponent(stringifyPrimitive(v));
  19224. }).join(sep);
  19225. } else {
  19226. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  19227. }
  19228. }).join(sep);
  19229. }
  19230. if (!name) return '';
  19231. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  19232. encodeURIComponent(stringifyPrimitive(obj));
  19233. };
  19234. var isArray = Array.isArray || function (xs) {
  19235. return Object.prototype.toString.call(xs) === '[object Array]';
  19236. };
  19237. function map (xs, f) {
  19238. if (xs.map) return xs.map(f);
  19239. var res = [];
  19240. for (var i = 0; i < xs.length; i++) {
  19241. res.push(f(xs[i], i));
  19242. }
  19243. return res;
  19244. }
  19245. var objectKeys = Object.keys || function (obj) {
  19246. var res = [];
  19247. for (var key in obj) {
  19248. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  19249. }
  19250. return res;
  19251. };
  19252. },{}],126:[function(require,module,exports){
  19253. 'use strict';
  19254. exports.decode = exports.parse = require('./decode');
  19255. exports.encode = exports.stringify = require('./encode');
  19256. },{"./decode":124,"./encode":125}],127:[function(require,module,exports){
  19257. module.exports = require('./lib/_stream_duplex.js');
  19258. },{"./lib/_stream_duplex.js":128}],128:[function(require,module,exports){
  19259. // Copyright Joyent, Inc. and other Node contributors.
  19260. //
  19261. // Permission is hereby granted, free of charge, to any person obtaining a
  19262. // copy of this software and associated documentation files (the
  19263. // "Software"), to deal in the Software without restriction, including
  19264. // without limitation the rights to use, copy, modify, merge, publish,
  19265. // distribute, sublicense, and/or sell copies of the Software, and to permit
  19266. // persons to whom the Software is furnished to do so, subject to the
  19267. // following conditions:
  19268. //
  19269. // The above copyright notice and this permission notice shall be included
  19270. // in all copies or substantial portions of the Software.
  19271. //
  19272. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  19273. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19274. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  19275. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19276. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  19277. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  19278. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  19279. // a duplex stream is just a stream that is both readable and writable.
  19280. // Since JS doesn't have multiple prototypal inheritance, this class
  19281. // prototypally inherits from Readable, and then parasitically from
  19282. // Writable.
  19283. 'use strict';
  19284. /*<replacement>*/
  19285. var pna = require('process-nextick-args');
  19286. /*</replacement>*/
  19287. /*<replacement>*/
  19288. var objectKeys = Object.keys || function (obj) {
  19289. var keys = [];
  19290. for (var key in obj) {
  19291. keys.push(key);
  19292. }return keys;
  19293. };
  19294. /*</replacement>*/
  19295. module.exports = Duplex;
  19296. /*<replacement>*/
  19297. var util = Object.create(require('core-util-is'));
  19298. util.inherits = require('inherits');
  19299. /*</replacement>*/
  19300. var Readable = require('./_stream_readable');
  19301. var Writable = require('./_stream_writable');
  19302. util.inherits(Duplex, Readable);
  19303. {
  19304. // avoid scope creep, the keys array can then be collected
  19305. var keys = objectKeys(Writable.prototype);
  19306. for (var v = 0; v < keys.length; v++) {
  19307. var method = keys[v];
  19308. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  19309. }
  19310. }
  19311. function Duplex(options) {
  19312. if (!(this instanceof Duplex)) return new Duplex(options);
  19313. Readable.call(this, options);
  19314. Writable.call(this, options);
  19315. if (options && options.readable === false) this.readable = false;
  19316. if (options && options.writable === false) this.writable = false;
  19317. this.allowHalfOpen = true;
  19318. if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  19319. this.once('end', onend);
  19320. }
  19321. Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  19322. // making it explicit this property is not enumerable
  19323. // because otherwise some prototype manipulation in
  19324. // userland will fail
  19325. enumerable: false,
  19326. get: function () {
  19327. return this._writableState.highWaterMark;
  19328. }
  19329. });
  19330. // the no-half-open enforcer
  19331. function onend() {
  19332. // if we allow half-open state, or if the writable side ended,
  19333. // then we're ok.
  19334. if (this.allowHalfOpen || this._writableState.ended) return;
  19335. // no more data can be written.
  19336. // But allow more writes to happen in this tick.
  19337. pna.nextTick(onEndNT, this);
  19338. }
  19339. function onEndNT(self) {
  19340. self.end();
  19341. }
  19342. Object.defineProperty(Duplex.prototype, 'destroyed', {
  19343. get: function () {
  19344. if (this._readableState === undefined || this._writableState === undefined) {
  19345. return false;
  19346. }
  19347. return this._readableState.destroyed && this._writableState.destroyed;
  19348. },
  19349. set: function (value) {
  19350. // we ignore the value if the stream
  19351. // has not been initialized yet
  19352. if (this._readableState === undefined || this._writableState === undefined) {
  19353. return;
  19354. }
  19355. // backward compatibility, the user is explicitly
  19356. // managing destroyed
  19357. this._readableState.destroyed = value;
  19358. this._writableState.destroyed = value;
  19359. }
  19360. });
  19361. Duplex.prototype._destroy = function (err, cb) {
  19362. this.push(null);
  19363. this.end();
  19364. pna.nextTick(cb, err);
  19365. };
  19366. },{"./_stream_readable":130,"./_stream_writable":132,"core-util-is":18,"inherits":"inherits","process-nextick-args":121}],129:[function(require,module,exports){
  19367. // Copyright Joyent, Inc. and other Node contributors.
  19368. //
  19369. // Permission is hereby granted, free of charge, to any person obtaining a
  19370. // copy of this software and associated documentation files (the
  19371. // "Software"), to deal in the Software without restriction, including
  19372. // without limitation the rights to use, copy, modify, merge, publish,
  19373. // distribute, sublicense, and/or sell copies of the Software, and to permit
  19374. // persons to whom the Software is furnished to do so, subject to the
  19375. // following conditions:
  19376. //
  19377. // The above copyright notice and this permission notice shall be included
  19378. // in all copies or substantial portions of the Software.
  19379. //
  19380. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  19381. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19382. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  19383. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19384. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  19385. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  19386. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  19387. // a passthrough stream.
  19388. // basically just the most minimal sort of Transform stream.
  19389. // Every written chunk gets output as-is.
  19390. 'use strict';
  19391. module.exports = PassThrough;
  19392. var Transform = require('./_stream_transform');
  19393. /*<replacement>*/
  19394. var util = Object.create(require('core-util-is'));
  19395. util.inherits = require('inherits');
  19396. /*</replacement>*/
  19397. util.inherits(PassThrough, Transform);
  19398. function PassThrough(options) {
  19399. if (!(this instanceof PassThrough)) return new PassThrough(options);
  19400. Transform.call(this, options);
  19401. }
  19402. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  19403. cb(null, chunk);
  19404. };
  19405. },{"./_stream_transform":131,"core-util-is":18,"inherits":"inherits"}],130:[function(require,module,exports){
  19406. (function (process,global){
  19407. // Copyright Joyent, Inc. and other Node contributors.
  19408. //
  19409. // Permission is hereby granted, free of charge, to any person obtaining a
  19410. // copy of this software and associated documentation files (the
  19411. // "Software"), to deal in the Software without restriction, including
  19412. // without limitation the rights to use, copy, modify, merge, publish,
  19413. // distribute, sublicense, and/or sell copies of the Software, and to permit
  19414. // persons to whom the Software is furnished to do so, subject to the
  19415. // following conditions:
  19416. //
  19417. // The above copyright notice and this permission notice shall be included
  19418. // in all copies or substantial portions of the Software.
  19419. //
  19420. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  19421. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19422. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  19423. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19424. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  19425. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  19426. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  19427. 'use strict';
  19428. /*<replacement>*/
  19429. var pna = require('process-nextick-args');
  19430. /*</replacement>*/
  19431. module.exports = Readable;
  19432. /*<replacement>*/
  19433. var isArray = require('isarray');
  19434. /*</replacement>*/
  19435. /*<replacement>*/
  19436. var Duplex;
  19437. /*</replacement>*/
  19438. Readable.ReadableState = ReadableState;
  19439. /*<replacement>*/
  19440. var EE = require('events').EventEmitter;
  19441. var EElistenerCount = function (emitter, type) {
  19442. return emitter.listeners(type).length;
  19443. };
  19444. /*</replacement>*/
  19445. /*<replacement>*/
  19446. var Stream = require('./internal/streams/stream');
  19447. /*</replacement>*/
  19448. /*<replacement>*/
  19449. var Buffer = require('safe-buffer').Buffer;
  19450. var OurUint8Array = global.Uint8Array || function () {};
  19451. function _uint8ArrayToBuffer(chunk) {
  19452. return Buffer.from(chunk);
  19453. }
  19454. function _isUint8Array(obj) {
  19455. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  19456. }
  19457. /*</replacement>*/
  19458. /*<replacement>*/
  19459. var util = Object.create(require('core-util-is'));
  19460. util.inherits = require('inherits');
  19461. /*</replacement>*/
  19462. /*<replacement>*/
  19463. var debugUtil = require('util');
  19464. var debug = void 0;
  19465. if (debugUtil && debugUtil.debuglog) {
  19466. debug = debugUtil.debuglog('stream');
  19467. } else {
  19468. debug = function () {};
  19469. }
  19470. /*</replacement>*/
  19471. var BufferList = require('./internal/streams/BufferList');
  19472. var destroyImpl = require('./internal/streams/destroy');
  19473. var StringDecoder;
  19474. util.inherits(Readable, Stream);
  19475. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  19476. function prependListener(emitter, event, fn) {
  19477. // Sadly this is not cacheable as some libraries bundle their own
  19478. // event emitter implementation with them.
  19479. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
  19480. // This is a hack to make sure that our error handler is attached before any
  19481. // userland ones. NEVER DO THIS. This is here only because this code needs
  19482. // to continue to work with older versions of Node.js that do not include
  19483. // the prependListener() method. The goal is to eventually remove this hack.
  19484. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
  19485. }
  19486. function ReadableState(options, stream) {
  19487. Duplex = Duplex || require('./_stream_duplex');
  19488. options = options || {};
  19489. // Duplex streams are both readable and writable, but share
  19490. // the same options object.
  19491. // However, some cases require setting options to different
  19492. // values for the readable and the writable sides of the duplex stream.
  19493. // These options can be provided separately as readableXXX and writableXXX.
  19494. var isDuplex = stream instanceof Duplex;
  19495. // object stream flag. Used to make read(n) ignore n and to
  19496. // make all the buffer merging and length checks go away
  19497. this.objectMode = !!options.objectMode;
  19498. if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
  19499. // the point at which it stops calling _read() to fill the buffer
  19500. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  19501. var hwm = options.highWaterMark;
  19502. var readableHwm = options.readableHighWaterMark;
  19503. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  19504. if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
  19505. // cast to ints.
  19506. this.highWaterMark = Math.floor(this.highWaterMark);
  19507. // A linked list is used to store data chunks instead of an array because the
  19508. // linked list can remove elements from the beginning faster than
  19509. // array.shift()
  19510. this.buffer = new BufferList();
  19511. this.length = 0;
  19512. this.pipes = null;
  19513. this.pipesCount = 0;
  19514. this.flowing = null;
  19515. this.ended = false;
  19516. this.endEmitted = false;
  19517. this.reading = false;
  19518. // a flag to be able to tell if the event 'readable'/'data' is emitted
  19519. // immediately, or on a later tick. We set this to true at first, because
  19520. // any actions that shouldn't happen until "later" should generally also
  19521. // not happen before the first read call.
  19522. this.sync = true;
  19523. // whenever we return null, then we set a flag to say
  19524. // that we're awaiting a 'readable' event emission.
  19525. this.needReadable = false;
  19526. this.emittedReadable = false;
  19527. this.readableListening = false;
  19528. this.resumeScheduled = false;
  19529. // has it been destroyed
  19530. this.destroyed = false;
  19531. // Crypto is kind of old and crusty. Historically, its default string
  19532. // encoding is 'binary' so we have to make this configurable.
  19533. // Everything else in the universe uses 'utf8', though.
  19534. this.defaultEncoding = options.defaultEncoding || 'utf8';
  19535. // the number of writers that are awaiting a drain event in .pipe()s
  19536. this.awaitDrain = 0;
  19537. // if true, a maybeReadMore has been scheduled
  19538. this.readingMore = false;
  19539. this.decoder = null;
  19540. this.encoding = null;
  19541. if (options.encoding) {
  19542. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  19543. this.decoder = new StringDecoder(options.encoding);
  19544. this.encoding = options.encoding;
  19545. }
  19546. }
  19547. function Readable(options) {
  19548. Duplex = Duplex || require('./_stream_duplex');
  19549. if (!(this instanceof Readable)) return new Readable(options);
  19550. this._readableState = new ReadableState(options, this);
  19551. // legacy
  19552. this.readable = true;
  19553. if (options) {
  19554. if (typeof options.read === 'function') this._read = options.read;
  19555. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  19556. }
  19557. Stream.call(this);
  19558. }
  19559. Object.defineProperty(Readable.prototype, 'destroyed', {
  19560. get: function () {
  19561. if (this._readableState === undefined) {
  19562. return false;
  19563. }
  19564. return this._readableState.destroyed;
  19565. },
  19566. set: function (value) {
  19567. // we ignore the value if the stream
  19568. // has not been initialized yet
  19569. if (!this._readableState) {
  19570. return;
  19571. }
  19572. // backward compatibility, the user is explicitly
  19573. // managing destroyed
  19574. this._readableState.destroyed = value;
  19575. }
  19576. });
  19577. Readable.prototype.destroy = destroyImpl.destroy;
  19578. Readable.prototype._undestroy = destroyImpl.undestroy;
  19579. Readable.prototype._destroy = function (err, cb) {
  19580. this.push(null);
  19581. cb(err);
  19582. };
  19583. // Manually shove something into the read() buffer.
  19584. // This returns true if the highWaterMark has not been hit yet,
  19585. // similar to how Writable.write() returns true if you should
  19586. // write() some more.
  19587. Readable.prototype.push = function (chunk, encoding) {
  19588. var state = this._readableState;
  19589. var skipChunkCheck;
  19590. if (!state.objectMode) {
  19591. if (typeof chunk === 'string') {
  19592. encoding = encoding || state.defaultEncoding;
  19593. if (encoding !== state.encoding) {
  19594. chunk = Buffer.from(chunk, encoding);
  19595. encoding = '';
  19596. }
  19597. skipChunkCheck = true;
  19598. }
  19599. } else {
  19600. skipChunkCheck = true;
  19601. }
  19602. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  19603. };
  19604. // Unshift should *always* be something directly out of read()
  19605. Readable.prototype.unshift = function (chunk) {
  19606. return readableAddChunk(this, chunk, null, true, false);
  19607. };
  19608. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  19609. var state = stream._readableState;
  19610. if (chunk === null) {
  19611. state.reading = false;
  19612. onEofChunk(stream, state);
  19613. } else {
  19614. var er;
  19615. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  19616. if (er) {
  19617. stream.emit('error', er);
  19618. } else if (state.objectMode || chunk && chunk.length > 0) {
  19619. if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
  19620. chunk = _uint8ArrayToBuffer(chunk);
  19621. }
  19622. if (addToFront) {
  19623. if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
  19624. } else if (state.ended) {
  19625. stream.emit('error', new Error('stream.push() after EOF'));
  19626. } else {
  19627. state.reading = false;
  19628. if (state.decoder && !encoding) {
  19629. chunk = state.decoder.write(chunk);
  19630. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
  19631. } else {
  19632. addChunk(stream, state, chunk, false);
  19633. }
  19634. }
  19635. } else if (!addToFront) {
  19636. state.reading = false;
  19637. }
  19638. }
  19639. return needMoreData(state);
  19640. }
  19641. function addChunk(stream, state, chunk, addToFront) {
  19642. if (state.flowing && state.length === 0 && !state.sync) {
  19643. stream.emit('data', chunk);
  19644. stream.read(0);
  19645. } else {
  19646. // update the buffer info.
  19647. state.length += state.objectMode ? 1 : chunk.length;
  19648. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  19649. if (state.needReadable) emitReadable(stream);
  19650. }
  19651. maybeReadMore(stream, state);
  19652. }
  19653. function chunkInvalid(state, chunk) {
  19654. var er;
  19655. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  19656. er = new TypeError('Invalid non-string/buffer chunk');
  19657. }
  19658. return er;
  19659. }
  19660. // if it's past the high water mark, we can push in some more.
  19661. // Also, if we have no data yet, we can stand some
  19662. // more bytes. This is to work around cases where hwm=0,
  19663. // such as the repl. Also, if the push() triggered a
  19664. // readable event, and the user called read(largeNumber) such that
  19665. // needReadable was set, then we ought to push more, so that another
  19666. // 'readable' event will be triggered.
  19667. function needMoreData(state) {
  19668. return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
  19669. }
  19670. Readable.prototype.isPaused = function () {
  19671. return this._readableState.flowing === false;
  19672. };
  19673. // backwards compatibility.
  19674. Readable.prototype.setEncoding = function (enc) {
  19675. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  19676. this._readableState.decoder = new StringDecoder(enc);
  19677. this._readableState.encoding = enc;
  19678. return this;
  19679. };
  19680. // Don't raise the hwm > 8MB
  19681. var MAX_HWM = 0x800000;
  19682. function computeNewHighWaterMark(n) {
  19683. if (n >= MAX_HWM) {
  19684. n = MAX_HWM;
  19685. } else {
  19686. // Get the next highest power of 2 to prevent increasing hwm excessively in
  19687. // tiny amounts
  19688. n--;
  19689. n |= n >>> 1;
  19690. n |= n >>> 2;
  19691. n |= n >>> 4;
  19692. n |= n >>> 8;
  19693. n |= n >>> 16;
  19694. n++;
  19695. }
  19696. return n;
  19697. }
  19698. // This function is designed to be inlinable, so please take care when making
  19699. // changes to the function body.
  19700. function howMuchToRead(n, state) {
  19701. if (n <= 0 || state.length === 0 && state.ended) return 0;
  19702. if (state.objectMode) return 1;
  19703. if (n !== n) {
  19704. // Only flow one buffer at a time
  19705. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  19706. }
  19707. // If we're asking for more than the current hwm, then raise the hwm.
  19708. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  19709. if (n <= state.length) return n;
  19710. // Don't have enough
  19711. if (!state.ended) {
  19712. state.needReadable = true;
  19713. return 0;
  19714. }
  19715. return state.length;
  19716. }
  19717. // you can override either this method, or the async _read(n) below.
  19718. Readable.prototype.read = function (n) {
  19719. debug('read', n);
  19720. n = parseInt(n, 10);
  19721. var state = this._readableState;
  19722. var nOrig = n;
  19723. if (n !== 0) state.emittedReadable = false;
  19724. // if we're doing read(0) to trigger a readable event, but we
  19725. // already have a bunch of data in the buffer, then just trigger
  19726. // the 'readable' event and move on.
  19727. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
  19728. debug('read: emitReadable', state.length, state.ended);
  19729. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  19730. return null;
  19731. }
  19732. n = howMuchToRead(n, state);
  19733. // if we've ended, and we're now clear, then finish it up.
  19734. if (n === 0 && state.ended) {
  19735. if (state.length === 0) endReadable(this);
  19736. return null;
  19737. }
  19738. // All the actual chunk generation logic needs to be
  19739. // *below* the call to _read. The reason is that in certain
  19740. // synthetic stream cases, such as passthrough streams, _read
  19741. // may be a completely synchronous operation which may change
  19742. // the state of the read buffer, providing enough data when
  19743. // before there was *not* enough.
  19744. //
  19745. // So, the steps are:
  19746. // 1. Figure out what the state of things will be after we do
  19747. // a read from the buffer.
  19748. //
  19749. // 2. If that resulting state will trigger a _read, then call _read.
  19750. // Note that this may be asynchronous, or synchronous. Yes, it is
  19751. // deeply ugly to write APIs this way, but that still doesn't mean
  19752. // that the Readable class should behave improperly, as streams are
  19753. // designed to be sync/async agnostic.
  19754. // Take note if the _read call is sync or async (ie, if the read call
  19755. // has returned yet), so that we know whether or not it's safe to emit
  19756. // 'readable' etc.
  19757. //
  19758. // 3. Actually pull the requested chunks out of the buffer and return.
  19759. // if we need a readable event, then we need to do some reading.
  19760. var doRead = state.needReadable;
  19761. debug('need readable', doRead);
  19762. // if we currently have less than the highWaterMark, then also read some
  19763. if (state.length === 0 || state.length - n < state.highWaterMark) {
  19764. doRead = true;
  19765. debug('length less than watermark', doRead);
  19766. }
  19767. // however, if we've ended, then there's no point, and if we're already
  19768. // reading, then it's unnecessary.
  19769. if (state.ended || state.reading) {
  19770. doRead = false;
  19771. debug('reading or ended', doRead);
  19772. } else if (doRead) {
  19773. debug('do read');
  19774. state.reading = true;
  19775. state.sync = true;
  19776. // if the length is currently zero, then we *need* a readable event.
  19777. if (state.length === 0) state.needReadable = true;
  19778. // call internal read method
  19779. this._read(state.highWaterMark);
  19780. state.sync = false;
  19781. // If _read pushed data synchronously, then `reading` will be false,
  19782. // and we need to re-evaluate how much data we can return to the user.
  19783. if (!state.reading) n = howMuchToRead(nOrig, state);
  19784. }
  19785. var ret;
  19786. if (n > 0) ret = fromList(n, state);else ret = null;
  19787. if (ret === null) {
  19788. state.needReadable = true;
  19789. n = 0;
  19790. } else {
  19791. state.length -= n;
  19792. }
  19793. if (state.length === 0) {
  19794. // If we have nothing in the buffer, then we want to know
  19795. // as soon as we *do* get something into the buffer.
  19796. if (!state.ended) state.needReadable = true;
  19797. // If we tried to read() past the EOF, then emit end on the next tick.
  19798. if (nOrig !== n && state.ended) endReadable(this);
  19799. }
  19800. if (ret !== null) this.emit('data', ret);
  19801. return ret;
  19802. };
  19803. function onEofChunk(stream, state) {
  19804. if (state.ended) return;
  19805. if (state.decoder) {
  19806. var chunk = state.decoder.end();
  19807. if (chunk && chunk.length) {
  19808. state.buffer.push(chunk);
  19809. state.length += state.objectMode ? 1 : chunk.length;
  19810. }
  19811. }
  19812. state.ended = true;
  19813. // emit 'readable' now to make sure it gets picked up.
  19814. emitReadable(stream);
  19815. }
  19816. // Don't emit readable right away in sync mode, because this can trigger
  19817. // another read() call => stack overflow. This way, it might trigger
  19818. // a nextTick recursion warning, but that's not so bad.
  19819. function emitReadable(stream) {
  19820. var state = stream._readableState;
  19821. state.needReadable = false;
  19822. if (!state.emittedReadable) {
  19823. debug('emitReadable', state.flowing);
  19824. state.emittedReadable = true;
  19825. if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
  19826. }
  19827. }
  19828. function emitReadable_(stream) {
  19829. debug('emit readable');
  19830. stream.emit('readable');
  19831. flow(stream);
  19832. }
  19833. // at this point, the user has presumably seen the 'readable' event,
  19834. // and called read() to consume some data. that may have triggered
  19835. // in turn another _read(n) call, in which case reading = true if
  19836. // it's in progress.
  19837. // However, if we're not ended, or reading, and the length < hwm,
  19838. // then go ahead and try to read some more preemptively.
  19839. function maybeReadMore(stream, state) {
  19840. if (!state.readingMore) {
  19841. state.readingMore = true;
  19842. pna.nextTick(maybeReadMore_, stream, state);
  19843. }
  19844. }
  19845. function maybeReadMore_(stream, state) {
  19846. var len = state.length;
  19847. while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
  19848. debug('maybeReadMore read 0');
  19849. stream.read(0);
  19850. if (len === state.length)
  19851. // didn't get any data, stop spinning.
  19852. break;else len = state.length;
  19853. }
  19854. state.readingMore = false;
  19855. }
  19856. // abstract method. to be overridden in specific implementation classes.
  19857. // call cb(er, data) where data is <= n in length.
  19858. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  19859. // arbitrary, and perhaps not very meaningful.
  19860. Readable.prototype._read = function (n) {
  19861. this.emit('error', new Error('_read() is not implemented'));
  19862. };
  19863. Readable.prototype.pipe = function (dest, pipeOpts) {
  19864. var src = this;
  19865. var state = this._readableState;
  19866. switch (state.pipesCount) {
  19867. case 0:
  19868. state.pipes = dest;
  19869. break;
  19870. case 1:
  19871. state.pipes = [state.pipes, dest];
  19872. break;
  19873. default:
  19874. state.pipes.push(dest);
  19875. break;
  19876. }
  19877. state.pipesCount += 1;
  19878. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  19879. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  19880. var endFn = doEnd ? onend : unpipe;
  19881. if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
  19882. dest.on('unpipe', onunpipe);
  19883. function onunpipe(readable, unpipeInfo) {
  19884. debug('onunpipe');
  19885. if (readable === src) {
  19886. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  19887. unpipeInfo.hasUnpiped = true;
  19888. cleanup();
  19889. }
  19890. }
  19891. }
  19892. function onend() {
  19893. debug('onend');
  19894. dest.end();
  19895. }
  19896. // when the dest drains, it reduces the awaitDrain counter
  19897. // on the source. This would be more elegant with a .once()
  19898. // handler in flow(), but adding and removing repeatedly is
  19899. // too slow.
  19900. var ondrain = pipeOnDrain(src);
  19901. dest.on('drain', ondrain);
  19902. var cleanedUp = false;
  19903. function cleanup() {
  19904. debug('cleanup');
  19905. // cleanup event handlers once the pipe is broken
  19906. dest.removeListener('close', onclose);
  19907. dest.removeListener('finish', onfinish);
  19908. dest.removeListener('drain', ondrain);
  19909. dest.removeListener('error', onerror);
  19910. dest.removeListener('unpipe', onunpipe);
  19911. src.removeListener('end', onend);
  19912. src.removeListener('end', unpipe);
  19913. src.removeListener('data', ondata);
  19914. cleanedUp = true;
  19915. // if the reader is waiting for a drain event from this
  19916. // specific writer, then it would cause it to never start
  19917. // flowing again.
  19918. // So, if this is awaiting a drain, then we just call it now.
  19919. // If we don't know, then assume that we are waiting for one.
  19920. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  19921. }
  19922. // If the user pushes more data while we're writing to dest then we'll end up
  19923. // in ondata again. However, we only want to increase awaitDrain once because
  19924. // dest will only emit one 'drain' event for the multiple writes.
  19925. // => Introduce a guard on increasing awaitDrain.
  19926. var increasedAwaitDrain = false;
  19927. src.on('data', ondata);
  19928. function ondata(chunk) {
  19929. debug('ondata');
  19930. increasedAwaitDrain = false;
  19931. var ret = dest.write(chunk);
  19932. if (false === ret && !increasedAwaitDrain) {
  19933. // If the user unpiped during `dest.write()`, it is possible
  19934. // to get stuck in a permanently paused state if that write
  19935. // also returned false.
  19936. // => Check whether `dest` is still a piping destination.
  19937. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  19938. debug('false write response, pause', src._readableState.awaitDrain);
  19939. src._readableState.awaitDrain++;
  19940. increasedAwaitDrain = true;
  19941. }
  19942. src.pause();
  19943. }
  19944. }
  19945. // if the dest has an error, then stop piping into it.
  19946. // however, don't suppress the throwing behavior for this.
  19947. function onerror(er) {
  19948. debug('onerror', er);
  19949. unpipe();
  19950. dest.removeListener('error', onerror);
  19951. if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  19952. }
  19953. // Make sure our error handler is attached before userland ones.
  19954. prependListener(dest, 'error', onerror);
  19955. // Both close and finish should trigger unpipe, but only once.
  19956. function onclose() {
  19957. dest.removeListener('finish', onfinish);
  19958. unpipe();
  19959. }
  19960. dest.once('close', onclose);
  19961. function onfinish() {
  19962. debug('onfinish');
  19963. dest.removeListener('close', onclose);
  19964. unpipe();
  19965. }
  19966. dest.once('finish', onfinish);
  19967. function unpipe() {
  19968. debug('unpipe');
  19969. src.unpipe(dest);
  19970. }
  19971. // tell the dest that it's being piped to
  19972. dest.emit('pipe', src);
  19973. // start the flow if it hasn't been started already.
  19974. if (!state.flowing) {
  19975. debug('pipe resume');
  19976. src.resume();
  19977. }
  19978. return dest;
  19979. };
  19980. function pipeOnDrain(src) {
  19981. return function () {
  19982. var state = src._readableState;
  19983. debug('pipeOnDrain', state.awaitDrain);
  19984. if (state.awaitDrain) state.awaitDrain--;
  19985. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  19986. state.flowing = true;
  19987. flow(src);
  19988. }
  19989. };
  19990. }
  19991. Readable.prototype.unpipe = function (dest) {
  19992. var state = this._readableState;
  19993. var unpipeInfo = { hasUnpiped: false };
  19994. // if we're not piping anywhere, then do nothing.
  19995. if (state.pipesCount === 0) return this;
  19996. // just one destination. most common case.
  19997. if (state.pipesCount === 1) {
  19998. // passed in one, but it's not the right one.
  19999. if (dest && dest !== state.pipes) return this;
  20000. if (!dest) dest = state.pipes;
  20001. // got a match.
  20002. state.pipes = null;
  20003. state.pipesCount = 0;
  20004. state.flowing = false;
  20005. if (dest) dest.emit('unpipe', this, unpipeInfo);
  20006. return this;
  20007. }
  20008. // slow case. multiple pipe destinations.
  20009. if (!dest) {
  20010. // remove all.
  20011. var dests = state.pipes;
  20012. var len = state.pipesCount;
  20013. state.pipes = null;
  20014. state.pipesCount = 0;
  20015. state.flowing = false;
  20016. for (var i = 0; i < len; i++) {
  20017. dests[i].emit('unpipe', this, unpipeInfo);
  20018. }return this;
  20019. }
  20020. // try to find the right one.
  20021. var index = indexOf(state.pipes, dest);
  20022. if (index === -1) return this;
  20023. state.pipes.splice(index, 1);
  20024. state.pipesCount -= 1;
  20025. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  20026. dest.emit('unpipe', this, unpipeInfo);
  20027. return this;
  20028. };
  20029. // set up data events if they are asked for
  20030. // Ensure readable listeners eventually get something
  20031. Readable.prototype.on = function (ev, fn) {
  20032. var res = Stream.prototype.on.call(this, ev, fn);
  20033. if (ev === 'data') {
  20034. // Start flowing on next tick if stream isn't explicitly paused
  20035. if (this._readableState.flowing !== false) this.resume();
  20036. } else if (ev === 'readable') {
  20037. var state = this._readableState;
  20038. if (!state.endEmitted && !state.readableListening) {
  20039. state.readableListening = state.needReadable = true;
  20040. state.emittedReadable = false;
  20041. if (!state.reading) {
  20042. pna.nextTick(nReadingNextTick, this);
  20043. } else if (state.length) {
  20044. emitReadable(this);
  20045. }
  20046. }
  20047. }
  20048. return res;
  20049. };
  20050. Readable.prototype.addListener = Readable.prototype.on;
  20051. function nReadingNextTick(self) {
  20052. debug('readable nexttick read 0');
  20053. self.read(0);
  20054. }
  20055. // pause() and resume() are remnants of the legacy readable stream API
  20056. // If the user uses them, then switch into old mode.
  20057. Readable.prototype.resume = function () {
  20058. var state = this._readableState;
  20059. if (!state.flowing) {
  20060. debug('resume');
  20061. state.flowing = true;
  20062. resume(this, state);
  20063. }
  20064. return this;
  20065. };
  20066. function resume(stream, state) {
  20067. if (!state.resumeScheduled) {
  20068. state.resumeScheduled = true;
  20069. pna.nextTick(resume_, stream, state);
  20070. }
  20071. }
  20072. function resume_(stream, state) {
  20073. if (!state.reading) {
  20074. debug('resume read 0');
  20075. stream.read(0);
  20076. }
  20077. state.resumeScheduled = false;
  20078. state.awaitDrain = 0;
  20079. stream.emit('resume');
  20080. flow(stream);
  20081. if (state.flowing && !state.reading) stream.read(0);
  20082. }
  20083. Readable.prototype.pause = function () {
  20084. debug('call pause flowing=%j', this._readableState.flowing);
  20085. if (false !== this._readableState.flowing) {
  20086. debug('pause');
  20087. this._readableState.flowing = false;
  20088. this.emit('pause');
  20089. }
  20090. return this;
  20091. };
  20092. function flow(stream) {
  20093. var state = stream._readableState;
  20094. debug('flow', state.flowing);
  20095. while (state.flowing && stream.read() !== null) {}
  20096. }
  20097. // wrap an old-style stream as the async data source.
  20098. // This is *not* part of the readable stream interface.
  20099. // It is an ugly unfortunate mess of history.
  20100. Readable.prototype.wrap = function (stream) {
  20101. var _this = this;
  20102. var state = this._readableState;
  20103. var paused = false;
  20104. stream.on('end', function () {
  20105. debug('wrapped end');
  20106. if (state.decoder && !state.ended) {
  20107. var chunk = state.decoder.end();
  20108. if (chunk && chunk.length) _this.push(chunk);
  20109. }
  20110. _this.push(null);
  20111. });
  20112. stream.on('data', function (chunk) {
  20113. debug('wrapped data');
  20114. if (state.decoder) chunk = state.decoder.write(chunk);
  20115. // don't skip over falsy values in objectMode
  20116. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  20117. var ret = _this.push(chunk);
  20118. if (!ret) {
  20119. paused = true;
  20120. stream.pause();
  20121. }
  20122. });
  20123. // proxy all the other methods.
  20124. // important when wrapping filters and duplexes.
  20125. for (var i in stream) {
  20126. if (this[i] === undefined && typeof stream[i] === 'function') {
  20127. this[i] = function (method) {
  20128. return function () {
  20129. return stream[method].apply(stream, arguments);
  20130. };
  20131. }(i);
  20132. }
  20133. }
  20134. // proxy certain important events.
  20135. for (var n = 0; n < kProxyEvents.length; n++) {
  20136. stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  20137. }
  20138. // when we try to consume some more bytes, simply unpause the
  20139. // underlying stream.
  20140. this._read = function (n) {
  20141. debug('wrapped _read', n);
  20142. if (paused) {
  20143. paused = false;
  20144. stream.resume();
  20145. }
  20146. };
  20147. return this;
  20148. };
  20149. Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  20150. // making it explicit this property is not enumerable
  20151. // because otherwise some prototype manipulation in
  20152. // userland will fail
  20153. enumerable: false,
  20154. get: function () {
  20155. return this._readableState.highWaterMark;
  20156. }
  20157. });
  20158. // exposed for testing purposes only.
  20159. Readable._fromList = fromList;
  20160. // Pluck off n bytes from an array of buffers.
  20161. // Length is the combined lengths of all the buffers in the list.
  20162. // This function is designed to be inlinable, so please take care when making
  20163. // changes to the function body.
  20164. function fromList(n, state) {
  20165. // nothing buffered
  20166. if (state.length === 0) return null;
  20167. var ret;
  20168. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  20169. // read it all, truncate the list
  20170. if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
  20171. state.buffer.clear();
  20172. } else {
  20173. // read part of list
  20174. ret = fromListPartial(n, state.buffer, state.decoder);
  20175. }
  20176. return ret;
  20177. }
  20178. // Extracts only enough buffered data to satisfy the amount requested.
  20179. // This function is designed to be inlinable, so please take care when making
  20180. // changes to the function body.
  20181. function fromListPartial(n, list, hasStrings) {
  20182. var ret;
  20183. if (n < list.head.data.length) {
  20184. // slice is the same for buffers and strings
  20185. ret = list.head.data.slice(0, n);
  20186. list.head.data = list.head.data.slice(n);
  20187. } else if (n === list.head.data.length) {
  20188. // first chunk is a perfect match
  20189. ret = list.shift();
  20190. } else {
  20191. // result spans more than one buffer
  20192. ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  20193. }
  20194. return ret;
  20195. }
  20196. // Copies a specified amount of characters from the list of buffered data
  20197. // chunks.
  20198. // This function is designed to be inlinable, so please take care when making
  20199. // changes to the function body.
  20200. function copyFromBufferString(n, list) {
  20201. var p = list.head;
  20202. var c = 1;
  20203. var ret = p.data;
  20204. n -= ret.length;
  20205. while (p = p.next) {
  20206. var str = p.data;
  20207. var nb = n > str.length ? str.length : n;
  20208. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  20209. n -= nb;
  20210. if (n === 0) {
  20211. if (nb === str.length) {
  20212. ++c;
  20213. if (p.next) list.head = p.next;else list.head = list.tail = null;
  20214. } else {
  20215. list.head = p;
  20216. p.data = str.slice(nb);
  20217. }
  20218. break;
  20219. }
  20220. ++c;
  20221. }
  20222. list.length -= c;
  20223. return ret;
  20224. }
  20225. // Copies a specified amount of bytes from the list of buffered data chunks.
  20226. // This function is designed to be inlinable, so please take care when making
  20227. // changes to the function body.
  20228. function copyFromBuffer(n, list) {
  20229. var ret = Buffer.allocUnsafe(n);
  20230. var p = list.head;
  20231. var c = 1;
  20232. p.data.copy(ret);
  20233. n -= p.data.length;
  20234. while (p = p.next) {
  20235. var buf = p.data;
  20236. var nb = n > buf.length ? buf.length : n;
  20237. buf.copy(ret, ret.length - n, 0, nb);
  20238. n -= nb;
  20239. if (n === 0) {
  20240. if (nb === buf.length) {
  20241. ++c;
  20242. if (p.next) list.head = p.next;else list.head = list.tail = null;
  20243. } else {
  20244. list.head = p;
  20245. p.data = buf.slice(nb);
  20246. }
  20247. break;
  20248. }
  20249. ++c;
  20250. }
  20251. list.length -= c;
  20252. return ret;
  20253. }
  20254. function endReadable(stream) {
  20255. var state = stream._readableState;
  20256. // If we get here before consuming all the bytes, then that is a
  20257. // bug in node. Should never happen.
  20258. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
  20259. if (!state.endEmitted) {
  20260. state.ended = true;
  20261. pna.nextTick(endReadableNT, state, stream);
  20262. }
  20263. }
  20264. function endReadableNT(state, stream) {
  20265. // Check that we didn't get one last unshift.
  20266. if (!state.endEmitted && state.length === 0) {
  20267. state.endEmitted = true;
  20268. stream.readable = false;
  20269. stream.emit('end');
  20270. }
  20271. }
  20272. function indexOf(xs, x) {
  20273. for (var i = 0, l = xs.length; i < l; i++) {
  20274. if (xs[i] === x) return i;
  20275. }
  20276. return -1;
  20277. }
  20278. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  20279. },{"./_stream_duplex":128,"./internal/streams/BufferList":133,"./internal/streams/destroy":134,"./internal/streams/stream":135,"_process":122,"core-util-is":18,"events":21,"inherits":"inherits","isarray":25,"process-nextick-args":121,"safe-buffer":136,"string_decoder/":137,"util":16}],131:[function(require,module,exports){
  20280. // Copyright Joyent, Inc. and other Node contributors.
  20281. //
  20282. // Permission is hereby granted, free of charge, to any person obtaining a
  20283. // copy of this software and associated documentation files (the
  20284. // "Software"), to deal in the Software without restriction, including
  20285. // without limitation the rights to use, copy, modify, merge, publish,
  20286. // distribute, sublicense, and/or sell copies of the Software, and to permit
  20287. // persons to whom the Software is furnished to do so, subject to the
  20288. // following conditions:
  20289. //
  20290. // The above copyright notice and this permission notice shall be included
  20291. // in all copies or substantial portions of the Software.
  20292. //
  20293. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  20294. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  20295. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  20296. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  20297. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  20298. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  20299. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  20300. // a transform stream is a readable/writable stream where you do
  20301. // something with the data. Sometimes it's called a "filter",
  20302. // but that's not a great name for it, since that implies a thing where
  20303. // some bits pass through, and others are simply ignored. (That would
  20304. // be a valid example of a transform, of course.)
  20305. //
  20306. // While the output is causally related to the input, it's not a
  20307. // necessarily symmetric or synchronous transformation. For example,
  20308. // a zlib stream might take multiple plain-text writes(), and then
  20309. // emit a single compressed chunk some time in the future.
  20310. //
  20311. // Here's how this works:
  20312. //
  20313. // The Transform stream has all the aspects of the readable and writable
  20314. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  20315. // internally, and returns false if there's a lot of pending writes
  20316. // buffered up. When you call read(), that calls _read(n) until
  20317. // there's enough pending readable data buffered up.
  20318. //
  20319. // In a transform stream, the written data is placed in a buffer. When
  20320. // _read(n) is called, it transforms the queued up data, calling the
  20321. // buffered _write cb's as it consumes chunks. If consuming a single
  20322. // written chunk would result in multiple output chunks, then the first
  20323. // outputted bit calls the readcb, and subsequent chunks just go into
  20324. // the read buffer, and will cause it to emit 'readable' if necessary.
  20325. //
  20326. // This way, back-pressure is actually determined by the reading side,
  20327. // since _read has to be called to start processing a new chunk. However,
  20328. // a pathological inflate type of transform can cause excessive buffering
  20329. // here. For example, imagine a stream where every byte of input is
  20330. // interpreted as an integer from 0-255, and then results in that many
  20331. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  20332. // 1kb of data being output. In this case, you could write a very small
  20333. // amount of input, and end up with a very large amount of output. In
  20334. // such a pathological inflating mechanism, there'd be no way to tell
  20335. // the system to stop doing the transform. A single 4MB write could
  20336. // cause the system to run out of memory.
  20337. //
  20338. // However, even in such a pathological case, only a single written chunk
  20339. // would be consumed, and then the rest would wait (un-transformed) until
  20340. // the results of the previous transformed chunk were consumed.
  20341. 'use strict';
  20342. module.exports = Transform;
  20343. var Duplex = require('./_stream_duplex');
  20344. /*<replacement>*/
  20345. var util = Object.create(require('core-util-is'));
  20346. util.inherits = require('inherits');
  20347. /*</replacement>*/
  20348. util.inherits(Transform, Duplex);
  20349. function afterTransform(er, data) {
  20350. var ts = this._transformState;
  20351. ts.transforming = false;
  20352. var cb = ts.writecb;
  20353. if (!cb) {
  20354. return this.emit('error', new Error('write callback called multiple times'));
  20355. }
  20356. ts.writechunk = null;
  20357. ts.writecb = null;
  20358. if (data != null) // single equals check for both `null` and `undefined`
  20359. this.push(data);
  20360. cb(er);
  20361. var rs = this._readableState;
  20362. rs.reading = false;
  20363. if (rs.needReadable || rs.length < rs.highWaterMark) {
  20364. this._read(rs.highWaterMark);
  20365. }
  20366. }
  20367. function Transform(options) {
  20368. if (!(this instanceof Transform)) return new Transform(options);
  20369. Duplex.call(this, options);
  20370. this._transformState = {
  20371. afterTransform: afterTransform.bind(this),
  20372. needTransform: false,
  20373. transforming: false,
  20374. writecb: null,
  20375. writechunk: null,
  20376. writeencoding: null
  20377. };
  20378. // start out asking for a readable event once data is transformed.
  20379. this._readableState.needReadable = true;
  20380. // we have implemented the _read method, and done the other things
  20381. // that Readable wants before the first _read call, so unset the
  20382. // sync guard flag.
  20383. this._readableState.sync = false;
  20384. if (options) {
  20385. if (typeof options.transform === 'function') this._transform = options.transform;
  20386. if (typeof options.flush === 'function') this._flush = options.flush;
  20387. }
  20388. // When the writable side finishes, then flush out anything remaining.
  20389. this.on('prefinish', prefinish);
  20390. }
  20391. function prefinish() {
  20392. var _this = this;
  20393. if (typeof this._flush === 'function') {
  20394. this._flush(function (er, data) {
  20395. done(_this, er, data);
  20396. });
  20397. } else {
  20398. done(this, null, null);
  20399. }
  20400. }
  20401. Transform.prototype.push = function (chunk, encoding) {
  20402. this._transformState.needTransform = false;
  20403. return Duplex.prototype.push.call(this, chunk, encoding);
  20404. };
  20405. // This is the part where you do stuff!
  20406. // override this function in implementation classes.
  20407. // 'chunk' is an input chunk.
  20408. //
  20409. // Call `push(newChunk)` to pass along transformed output
  20410. // to the readable side. You may call 'push' zero or more times.
  20411. //
  20412. // Call `cb(err)` when you are done with this chunk. If you pass
  20413. // an error, then that'll put the hurt on the whole operation. If you
  20414. // never call cb(), then you'll never get another chunk.
  20415. Transform.prototype._transform = function (chunk, encoding, cb) {
  20416. throw new Error('_transform() is not implemented');
  20417. };
  20418. Transform.prototype._write = function (chunk, encoding, cb) {
  20419. var ts = this._transformState;
  20420. ts.writecb = cb;
  20421. ts.writechunk = chunk;
  20422. ts.writeencoding = encoding;
  20423. if (!ts.transforming) {
  20424. var rs = this._readableState;
  20425. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  20426. }
  20427. };
  20428. // Doesn't matter what the args are here.
  20429. // _transform does all the work.
  20430. // That we got here means that the readable side wants more data.
  20431. Transform.prototype._read = function (n) {
  20432. var ts = this._transformState;
  20433. if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
  20434. ts.transforming = true;
  20435. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  20436. } else {
  20437. // mark that we need a transform, so that any data that comes in
  20438. // will get processed, now that we've asked for it.
  20439. ts.needTransform = true;
  20440. }
  20441. };
  20442. Transform.prototype._destroy = function (err, cb) {
  20443. var _this2 = this;
  20444. Duplex.prototype._destroy.call(this, err, function (err2) {
  20445. cb(err2);
  20446. _this2.emit('close');
  20447. });
  20448. };
  20449. function done(stream, er, data) {
  20450. if (er) return stream.emit('error', er);
  20451. if (data != null) // single equals check for both `null` and `undefined`
  20452. stream.push(data);
  20453. // if there's nothing in the write buffer, then that means
  20454. // that nothing more will ever be provided
  20455. if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
  20456. if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
  20457. return stream.push(null);
  20458. }
  20459. },{"./_stream_duplex":128,"core-util-is":18,"inherits":"inherits"}],132:[function(require,module,exports){
  20460. (function (process,global,setImmediate){
  20461. // Copyright Joyent, Inc. and other Node contributors.
  20462. //
  20463. // Permission is hereby granted, free of charge, to any person obtaining a
  20464. // copy of this software and associated documentation files (the
  20465. // "Software"), to deal in the Software without restriction, including
  20466. // without limitation the rights to use, copy, modify, merge, publish,
  20467. // distribute, sublicense, and/or sell copies of the Software, and to permit
  20468. // persons to whom the Software is furnished to do so, subject to the
  20469. // following conditions:
  20470. //
  20471. // The above copyright notice and this permission notice shall be included
  20472. // in all copies or substantial portions of the Software.
  20473. //
  20474. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  20475. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  20476. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  20477. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  20478. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  20479. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  20480. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  20481. // A bit simpler than readable streams.
  20482. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  20483. // the drain event emission and buffering.
  20484. 'use strict';
  20485. /*<replacement>*/
  20486. var pna = require('process-nextick-args');
  20487. /*</replacement>*/
  20488. module.exports = Writable;
  20489. /* <replacement> */
  20490. function WriteReq(chunk, encoding, cb) {
  20491. this.chunk = chunk;
  20492. this.encoding = encoding;
  20493. this.callback = cb;
  20494. this.next = null;
  20495. }
  20496. // It seems a linked list but it is not
  20497. // there will be only 2 of these for each stream
  20498. function CorkedRequest(state) {
  20499. var _this = this;
  20500. this.next = null;
  20501. this.entry = null;
  20502. this.finish = function () {
  20503. onCorkedFinish(_this, state);
  20504. };
  20505. }
  20506. /* </replacement> */
  20507. /*<replacement>*/
  20508. var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
  20509. /*</replacement>*/
  20510. /*<replacement>*/
  20511. var Duplex;
  20512. /*</replacement>*/
  20513. Writable.WritableState = WritableState;
  20514. /*<replacement>*/
  20515. var util = Object.create(require('core-util-is'));
  20516. util.inherits = require('inherits');
  20517. /*</replacement>*/
  20518. /*<replacement>*/
  20519. var internalUtil = {
  20520. deprecate: require('util-deprecate')
  20521. };
  20522. /*</replacement>*/
  20523. /*<replacement>*/
  20524. var Stream = require('./internal/streams/stream');
  20525. /*</replacement>*/
  20526. /*<replacement>*/
  20527. var Buffer = require('safe-buffer').Buffer;
  20528. var OurUint8Array = global.Uint8Array || function () {};
  20529. function _uint8ArrayToBuffer(chunk) {
  20530. return Buffer.from(chunk);
  20531. }
  20532. function _isUint8Array(obj) {
  20533. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  20534. }
  20535. /*</replacement>*/
  20536. var destroyImpl = require('./internal/streams/destroy');
  20537. util.inherits(Writable, Stream);
  20538. function nop() {}
  20539. function WritableState(options, stream) {
  20540. Duplex = Duplex || require('./_stream_duplex');
  20541. options = options || {};
  20542. // Duplex streams are both readable and writable, but share
  20543. // the same options object.
  20544. // However, some cases require setting options to different
  20545. // values for the readable and the writable sides of the duplex stream.
  20546. // These options can be provided separately as readableXXX and writableXXX.
  20547. var isDuplex = stream instanceof Duplex;
  20548. // object stream flag to indicate whether or not this stream
  20549. // contains buffers or objects.
  20550. this.objectMode = !!options.objectMode;
  20551. if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
  20552. // the point at which write() starts returning false
  20553. // Note: 0 is a valid value, means that we always return false if
  20554. // the entire buffer is not flushed immediately on write()
  20555. var hwm = options.highWaterMark;
  20556. var writableHwm = options.writableHighWaterMark;
  20557. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  20558. if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
  20559. // cast to ints.
  20560. this.highWaterMark = Math.floor(this.highWaterMark);
  20561. // if _final has been called
  20562. this.finalCalled = false;
  20563. // drain event flag.
  20564. this.needDrain = false;
  20565. // at the start of calling end()
  20566. this.ending = false;
  20567. // when end() has been called, and returned
  20568. this.ended = false;
  20569. // when 'finish' is emitted
  20570. this.finished = false;
  20571. // has it been destroyed
  20572. this.destroyed = false;
  20573. // should we decode strings into buffers before passing to _write?
  20574. // this is here so that some node-core streams can optimize string
  20575. // handling at a lower level.
  20576. var noDecode = options.decodeStrings === false;
  20577. this.decodeStrings = !noDecode;
  20578. // Crypto is kind of old and crusty. Historically, its default string
  20579. // encoding is 'binary' so we have to make this configurable.
  20580. // Everything else in the universe uses 'utf8', though.
  20581. this.defaultEncoding = options.defaultEncoding || 'utf8';
  20582. // not an actual buffer we keep track of, but a measurement
  20583. // of how much we're waiting to get pushed to some underlying
  20584. // socket or file.
  20585. this.length = 0;
  20586. // a flag to see when we're in the middle of a write.
  20587. this.writing = false;
  20588. // when true all writes will be buffered until .uncork() call
  20589. this.corked = 0;
  20590. // a flag to be able to tell if the onwrite cb is called immediately,
  20591. // or on a later tick. We set this to true at first, because any
  20592. // actions that shouldn't happen until "later" should generally also
  20593. // not happen before the first write call.
  20594. this.sync = true;
  20595. // a flag to know if we're processing previously buffered items, which
  20596. // may call the _write() callback in the same tick, so that we don't
  20597. // end up in an overlapped onwrite situation.
  20598. this.bufferProcessing = false;
  20599. // the callback that's passed to _write(chunk,cb)
  20600. this.onwrite = function (er) {
  20601. onwrite(stream, er);
  20602. };
  20603. // the callback that the user supplies to write(chunk,encoding,cb)
  20604. this.writecb = null;
  20605. // the amount that is being written when _write is called.
  20606. this.writelen = 0;
  20607. this.bufferedRequest = null;
  20608. this.lastBufferedRequest = null;
  20609. // number of pending user-supplied write callbacks
  20610. // this must be 0 before 'finish' can be emitted
  20611. this.pendingcb = 0;
  20612. // emit prefinish if the only thing we're waiting for is _write cbs
  20613. // This is relevant for synchronous Transform streams
  20614. this.prefinished = false;
  20615. // True if the error was already emitted and should not be thrown again
  20616. this.errorEmitted = false;
  20617. // count buffered requests
  20618. this.bufferedRequestCount = 0;
  20619. // allocate the first CorkedRequest, there is always
  20620. // one allocated and free to use, and we maintain at most two
  20621. this.corkedRequestsFree = new CorkedRequest(this);
  20622. }
  20623. WritableState.prototype.getBuffer = function getBuffer() {
  20624. var current = this.bufferedRequest;
  20625. var out = [];
  20626. while (current) {
  20627. out.push(current);
  20628. current = current.next;
  20629. }
  20630. return out;
  20631. };
  20632. (function () {
  20633. try {
  20634. Object.defineProperty(WritableState.prototype, 'buffer', {
  20635. get: internalUtil.deprecate(function () {
  20636. return this.getBuffer();
  20637. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
  20638. });
  20639. } catch (_) {}
  20640. })();
  20641. // Test _writableState for inheritance to account for Duplex streams,
  20642. // whose prototype chain only points to Readable.
  20643. var realHasInstance;
  20644. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  20645. realHasInstance = Function.prototype[Symbol.hasInstance];
  20646. Object.defineProperty(Writable, Symbol.hasInstance, {
  20647. value: function (object) {
  20648. if (realHasInstance.call(this, object)) return true;
  20649. if (this !== Writable) return false;
  20650. return object && object._writableState instanceof WritableState;
  20651. }
  20652. });
  20653. } else {
  20654. realHasInstance = function (object) {
  20655. return object instanceof this;
  20656. };
  20657. }
  20658. function Writable(options) {
  20659. Duplex = Duplex || require('./_stream_duplex');
  20660. // Writable ctor is applied to Duplexes, too.
  20661. // `realHasInstance` is necessary because using plain `instanceof`
  20662. // would return false, as no `_writableState` property is attached.
  20663. // Trying to use the custom `instanceof` for Writable here will also break the
  20664. // Node.js LazyTransform implementation, which has a non-trivial getter for
  20665. // `_writableState` that would lead to infinite recursion.
  20666. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
  20667. return new Writable(options);
  20668. }
  20669. this._writableState = new WritableState(options, this);
  20670. // legacy.
  20671. this.writable = true;
  20672. if (options) {
  20673. if (typeof options.write === 'function') this._write = options.write;
  20674. if (typeof options.writev === 'function') this._writev = options.writev;
  20675. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  20676. if (typeof options.final === 'function') this._final = options.final;
  20677. }
  20678. Stream.call(this);
  20679. }
  20680. // Otherwise people can pipe Writable streams, which is just wrong.
  20681. Writable.prototype.pipe = function () {
  20682. this.emit('error', new Error('Cannot pipe, not readable'));
  20683. };
  20684. function writeAfterEnd(stream, cb) {
  20685. var er = new Error('write after end');
  20686. // TODO: defer error events consistently everywhere, not just the cb
  20687. stream.emit('error', er);
  20688. pna.nextTick(cb, er);
  20689. }
  20690. // Checks that a user-supplied chunk is valid, especially for the particular
  20691. // mode the stream is in. Currently this means that `null` is never accepted
  20692. // and undefined/non-string values are only allowed in object mode.
  20693. function validChunk(stream, state, chunk, cb) {
  20694. var valid = true;
  20695. var er = false;
  20696. if (chunk === null) {
  20697. er = new TypeError('May not write null values to stream');
  20698. } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  20699. er = new TypeError('Invalid non-string/buffer chunk');
  20700. }
  20701. if (er) {
  20702. stream.emit('error', er);
  20703. pna.nextTick(cb, er);
  20704. valid = false;
  20705. }
  20706. return valid;
  20707. }
  20708. Writable.prototype.write = function (chunk, encoding, cb) {
  20709. var state = this._writableState;
  20710. var ret = false;
  20711. var isBuf = !state.objectMode && _isUint8Array(chunk);
  20712. if (isBuf && !Buffer.isBuffer(chunk)) {
  20713. chunk = _uint8ArrayToBuffer(chunk);
  20714. }
  20715. if (typeof encoding === 'function') {
  20716. cb = encoding;
  20717. encoding = null;
  20718. }
  20719. if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  20720. if (typeof cb !== 'function') cb = nop;
  20721. if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
  20722. state.pendingcb++;
  20723. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  20724. }
  20725. return ret;
  20726. };
  20727. Writable.prototype.cork = function () {
  20728. var state = this._writableState;
  20729. state.corked++;
  20730. };
  20731. Writable.prototype.uncork = function () {
  20732. var state = this._writableState;
  20733. if (state.corked) {
  20734. state.corked--;
  20735. if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  20736. }
  20737. };
  20738. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  20739. // node::ParseEncoding() requires lower case.
  20740. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  20741. if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
  20742. this._writableState.defaultEncoding = encoding;
  20743. return this;
  20744. };
  20745. function decodeChunk(state, chunk, encoding) {
  20746. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  20747. chunk = Buffer.from(chunk, encoding);
  20748. }
  20749. return chunk;
  20750. }
  20751. Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  20752. // making it explicit this property is not enumerable
  20753. // because otherwise some prototype manipulation in
  20754. // userland will fail
  20755. enumerable: false,
  20756. get: function () {
  20757. return this._writableState.highWaterMark;
  20758. }
  20759. });
  20760. // if we're already writing something, then just put this
  20761. // in the queue, and wait our turn. Otherwise, call _write
  20762. // If we return false, then we need a drain event, so set that flag.
  20763. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  20764. if (!isBuf) {
  20765. var newChunk = decodeChunk(state, chunk, encoding);
  20766. if (chunk !== newChunk) {
  20767. isBuf = true;
  20768. encoding = 'buffer';
  20769. chunk = newChunk;
  20770. }
  20771. }
  20772. var len = state.objectMode ? 1 : chunk.length;
  20773. state.length += len;
  20774. var ret = state.length < state.highWaterMark;
  20775. // we must ensure that previous needDrain will not be reset to false.
  20776. if (!ret) state.needDrain = true;
  20777. if (state.writing || state.corked) {
  20778. var last = state.lastBufferedRequest;
  20779. state.lastBufferedRequest = {
  20780. chunk: chunk,
  20781. encoding: encoding,
  20782. isBuf: isBuf,
  20783. callback: cb,
  20784. next: null
  20785. };
  20786. if (last) {
  20787. last.next = state.lastBufferedRequest;
  20788. } else {
  20789. state.bufferedRequest = state.lastBufferedRequest;
  20790. }
  20791. state.bufferedRequestCount += 1;
  20792. } else {
  20793. doWrite(stream, state, false, len, chunk, encoding, cb);
  20794. }
  20795. return ret;
  20796. }
  20797. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  20798. state.writelen = len;
  20799. state.writecb = cb;
  20800. state.writing = true;
  20801. state.sync = true;
  20802. if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  20803. state.sync = false;
  20804. }
  20805. function onwriteError(stream, state, sync, er, cb) {
  20806. --state.pendingcb;
  20807. if (sync) {
  20808. // defer the callback if we are being called synchronously
  20809. // to avoid piling up things on the stack
  20810. pna.nextTick(cb, er);
  20811. // this can emit finish, and it will always happen
  20812. // after error
  20813. pna.nextTick(finishMaybe, stream, state);
  20814. stream._writableState.errorEmitted = true;
  20815. stream.emit('error', er);
  20816. } else {
  20817. // the caller expect this to happen before if
  20818. // it is async
  20819. cb(er);
  20820. stream._writableState.errorEmitted = true;
  20821. stream.emit('error', er);
  20822. // this can emit finish, but finish must
  20823. // always follow error
  20824. finishMaybe(stream, state);
  20825. }
  20826. }
  20827. function onwriteStateUpdate(state) {
  20828. state.writing = false;
  20829. state.writecb = null;
  20830. state.length -= state.writelen;
  20831. state.writelen = 0;
  20832. }
  20833. function onwrite(stream, er) {
  20834. var state = stream._writableState;
  20835. var sync = state.sync;
  20836. var cb = state.writecb;
  20837. onwriteStateUpdate(state);
  20838. if (er) onwriteError(stream, state, sync, er, cb);else {
  20839. // Check if we're actually ready to finish, but don't emit yet
  20840. var finished = needFinish(state);
  20841. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  20842. clearBuffer(stream, state);
  20843. }
  20844. if (sync) {
  20845. /*<replacement>*/
  20846. asyncWrite(afterWrite, stream, state, finished, cb);
  20847. /*</replacement>*/
  20848. } else {
  20849. afterWrite(stream, state, finished, cb);
  20850. }
  20851. }
  20852. }
  20853. function afterWrite(stream, state, finished, cb) {
  20854. if (!finished) onwriteDrain(stream, state);
  20855. state.pendingcb--;
  20856. cb();
  20857. finishMaybe(stream, state);
  20858. }
  20859. // Must force callback to be called on nextTick, so that we don't
  20860. // emit 'drain' before the write() consumer gets the 'false' return
  20861. // value, and has a chance to attach a 'drain' listener.
  20862. function onwriteDrain(stream, state) {
  20863. if (state.length === 0 && state.needDrain) {
  20864. state.needDrain = false;
  20865. stream.emit('drain');
  20866. }
  20867. }
  20868. // if there's something in the buffer waiting, then process it
  20869. function clearBuffer(stream, state) {
  20870. state.bufferProcessing = true;
  20871. var entry = state.bufferedRequest;
  20872. if (stream._writev && entry && entry.next) {
  20873. // Fast case, write everything using _writev()
  20874. var l = state.bufferedRequestCount;
  20875. var buffer = new Array(l);
  20876. var holder = state.corkedRequestsFree;
  20877. holder.entry = entry;
  20878. var count = 0;
  20879. var allBuffers = true;
  20880. while (entry) {
  20881. buffer[count] = entry;
  20882. if (!entry.isBuf) allBuffers = false;
  20883. entry = entry.next;
  20884. count += 1;
  20885. }
  20886. buffer.allBuffers = allBuffers;
  20887. doWrite(stream, state, true, state.length, buffer, '', holder.finish);
  20888. // doWrite is almost always async, defer these to save a bit of time
  20889. // as the hot path ends with doWrite
  20890. state.pendingcb++;
  20891. state.lastBufferedRequest = null;
  20892. if (holder.next) {
  20893. state.corkedRequestsFree = holder.next;
  20894. holder.next = null;
  20895. } else {
  20896. state.corkedRequestsFree = new CorkedRequest(state);
  20897. }
  20898. state.bufferedRequestCount = 0;
  20899. } else {
  20900. // Slow case, write chunks one-by-one
  20901. while (entry) {
  20902. var chunk = entry.chunk;
  20903. var encoding = entry.encoding;
  20904. var cb = entry.callback;
  20905. var len = state.objectMode ? 1 : chunk.length;
  20906. doWrite(stream, state, false, len, chunk, encoding, cb);
  20907. entry = entry.next;
  20908. state.bufferedRequestCount--;
  20909. // if we didn't call the onwrite immediately, then
  20910. // it means that we need to wait until it does.
  20911. // also, that means that the chunk and cb are currently
  20912. // being processed, so move the buffer counter past them.
  20913. if (state.writing) {
  20914. break;
  20915. }
  20916. }
  20917. if (entry === null) state.lastBufferedRequest = null;
  20918. }
  20919. state.bufferedRequest = entry;
  20920. state.bufferProcessing = false;
  20921. }
  20922. Writable.prototype._write = function (chunk, encoding, cb) {
  20923. cb(new Error('_write() is not implemented'));
  20924. };
  20925. Writable.prototype._writev = null;
  20926. Writable.prototype.end = function (chunk, encoding, cb) {
  20927. var state = this._writableState;
  20928. if (typeof chunk === 'function') {
  20929. cb = chunk;
  20930. chunk = null;
  20931. encoding = null;
  20932. } else if (typeof encoding === 'function') {
  20933. cb = encoding;
  20934. encoding = null;
  20935. }
  20936. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
  20937. // .end() fully uncorks
  20938. if (state.corked) {
  20939. state.corked = 1;
  20940. this.uncork();
  20941. }
  20942. // ignore unnecessary end() calls.
  20943. if (!state.ending && !state.finished) endWritable(this, state, cb);
  20944. };
  20945. function needFinish(state) {
  20946. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  20947. }
  20948. function callFinal(stream, state) {
  20949. stream._final(function (err) {
  20950. state.pendingcb--;
  20951. if (err) {
  20952. stream.emit('error', err);
  20953. }
  20954. state.prefinished = true;
  20955. stream.emit('prefinish');
  20956. finishMaybe(stream, state);
  20957. });
  20958. }
  20959. function prefinish(stream, state) {
  20960. if (!state.prefinished && !state.finalCalled) {
  20961. if (typeof stream._final === 'function') {
  20962. state.pendingcb++;
  20963. state.finalCalled = true;
  20964. pna.nextTick(callFinal, stream, state);
  20965. } else {
  20966. state.prefinished = true;
  20967. stream.emit('prefinish');
  20968. }
  20969. }
  20970. }
  20971. function finishMaybe(stream, state) {
  20972. var need = needFinish(state);
  20973. if (need) {
  20974. prefinish(stream, state);
  20975. if (state.pendingcb === 0) {
  20976. state.finished = true;
  20977. stream.emit('finish');
  20978. }
  20979. }
  20980. return need;
  20981. }
  20982. function endWritable(stream, state, cb) {
  20983. state.ending = true;
  20984. finishMaybe(stream, state);
  20985. if (cb) {
  20986. if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
  20987. }
  20988. state.ended = true;
  20989. stream.writable = false;
  20990. }
  20991. function onCorkedFinish(corkReq, state, err) {
  20992. var entry = corkReq.entry;
  20993. corkReq.entry = null;
  20994. while (entry) {
  20995. var cb = entry.callback;
  20996. state.pendingcb--;
  20997. cb(err);
  20998. entry = entry.next;
  20999. }
  21000. if (state.corkedRequestsFree) {
  21001. state.corkedRequestsFree.next = corkReq;
  21002. } else {
  21003. state.corkedRequestsFree = corkReq;
  21004. }
  21005. }
  21006. Object.defineProperty(Writable.prototype, 'destroyed', {
  21007. get: function () {
  21008. if (this._writableState === undefined) {
  21009. return false;
  21010. }
  21011. return this._writableState.destroyed;
  21012. },
  21013. set: function (value) {
  21014. // we ignore the value if the stream
  21015. // has not been initialized yet
  21016. if (!this._writableState) {
  21017. return;
  21018. }
  21019. // backward compatibility, the user is explicitly
  21020. // managing destroyed
  21021. this._writableState.destroyed = value;
  21022. }
  21023. });
  21024. Writable.prototype.destroy = destroyImpl.destroy;
  21025. Writable.prototype._undestroy = destroyImpl.undestroy;
  21026. Writable.prototype._destroy = function (err, cb) {
  21027. this.end();
  21028. cb(err);
  21029. };
  21030. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
  21031. },{"./_stream_duplex":128,"./internal/streams/destroy":134,"./internal/streams/stream":135,"_process":122,"core-util-is":18,"inherits":"inherits","process-nextick-args":121,"safe-buffer":136,"timers":146,"util-deprecate":149}],133:[function(require,module,exports){
  21032. 'use strict';
  21033. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  21034. var Buffer = require('safe-buffer').Buffer;
  21035. var util = require('util');
  21036. function copyBuffer(src, target, offset) {
  21037. src.copy(target, offset);
  21038. }
  21039. module.exports = function () {
  21040. function BufferList() {
  21041. _classCallCheck(this, BufferList);
  21042. this.head = null;
  21043. this.tail = null;
  21044. this.length = 0;
  21045. }
  21046. BufferList.prototype.push = function push(v) {
  21047. var entry = { data: v, next: null };
  21048. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  21049. this.tail = entry;
  21050. ++this.length;
  21051. };
  21052. BufferList.prototype.unshift = function unshift(v) {
  21053. var entry = { data: v, next: this.head };
  21054. if (this.length === 0) this.tail = entry;
  21055. this.head = entry;
  21056. ++this.length;
  21057. };
  21058. BufferList.prototype.shift = function shift() {
  21059. if (this.length === 0) return;
  21060. var ret = this.head.data;
  21061. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  21062. --this.length;
  21063. return ret;
  21064. };
  21065. BufferList.prototype.clear = function clear() {
  21066. this.head = this.tail = null;
  21067. this.length = 0;
  21068. };
  21069. BufferList.prototype.join = function join(s) {
  21070. if (this.length === 0) return '';
  21071. var p = this.head;
  21072. var ret = '' + p.data;
  21073. while (p = p.next) {
  21074. ret += s + p.data;
  21075. }return ret;
  21076. };
  21077. BufferList.prototype.concat = function concat(n) {
  21078. if (this.length === 0) return Buffer.alloc(0);
  21079. if (this.length === 1) return this.head.data;
  21080. var ret = Buffer.allocUnsafe(n >>> 0);
  21081. var p = this.head;
  21082. var i = 0;
  21083. while (p) {
  21084. copyBuffer(p.data, ret, i);
  21085. i += p.data.length;
  21086. p = p.next;
  21087. }
  21088. return ret;
  21089. };
  21090. return BufferList;
  21091. }();
  21092. if (util && util.inspect && util.inspect.custom) {
  21093. module.exports.prototype[util.inspect.custom] = function () {
  21094. var obj = util.inspect({ length: this.length });
  21095. return this.constructor.name + ' ' + obj;
  21096. };
  21097. }
  21098. },{"safe-buffer":136,"util":16}],134:[function(require,module,exports){
  21099. 'use strict';
  21100. /*<replacement>*/
  21101. var pna = require('process-nextick-args');
  21102. /*</replacement>*/
  21103. // undocumented cb() API, needed for core, not for public API
  21104. function destroy(err, cb) {
  21105. var _this = this;
  21106. var readableDestroyed = this._readableState && this._readableState.destroyed;
  21107. var writableDestroyed = this._writableState && this._writableState.destroyed;
  21108. if (readableDestroyed || writableDestroyed) {
  21109. if (cb) {
  21110. cb(err);
  21111. } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
  21112. pna.nextTick(emitErrorNT, this, err);
  21113. }
  21114. return this;
  21115. }
  21116. // we set destroyed to true before firing error callbacks in order
  21117. // to make it re-entrance safe in case destroy() is called within callbacks
  21118. if (this._readableState) {
  21119. this._readableState.destroyed = true;
  21120. }
  21121. // if this is a duplex stream mark the writable part as destroyed as well
  21122. if (this._writableState) {
  21123. this._writableState.destroyed = true;
  21124. }
  21125. this._destroy(err || null, function (err) {
  21126. if (!cb && err) {
  21127. pna.nextTick(emitErrorNT, _this, err);
  21128. if (_this._writableState) {
  21129. _this._writableState.errorEmitted = true;
  21130. }
  21131. } else if (cb) {
  21132. cb(err);
  21133. }
  21134. });
  21135. return this;
  21136. }
  21137. function undestroy() {
  21138. if (this._readableState) {
  21139. this._readableState.destroyed = false;
  21140. this._readableState.reading = false;
  21141. this._readableState.ended = false;
  21142. this._readableState.endEmitted = false;
  21143. }
  21144. if (this._writableState) {
  21145. this._writableState.destroyed = false;
  21146. this._writableState.ended = false;
  21147. this._writableState.ending = false;
  21148. this._writableState.finished = false;
  21149. this._writableState.errorEmitted = false;
  21150. }
  21151. }
  21152. function emitErrorNT(self, err) {
  21153. self.emit('error', err);
  21154. }
  21155. module.exports = {
  21156. destroy: destroy,
  21157. undestroy: undestroy
  21158. };
  21159. },{"process-nextick-args":121}],135:[function(require,module,exports){
  21160. module.exports = require('events').EventEmitter;
  21161. },{"events":21}],136:[function(require,module,exports){
  21162. /* eslint-disable node/no-deprecated-api */
  21163. var buffer = require('buffer')
  21164. var Buffer = buffer.Buffer
  21165. // alternative to using Object.keys for old browsers
  21166. function copyProps (src, dst) {
  21167. for (var key in src) {
  21168. dst[key] = src[key]
  21169. }
  21170. }
  21171. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  21172. module.exports = buffer
  21173. } else {
  21174. // Copy properties from require('buffer')
  21175. copyProps(buffer, exports)
  21176. exports.Buffer = SafeBuffer
  21177. }
  21178. function SafeBuffer (arg, encodingOrOffset, length) {
  21179. return Buffer(arg, encodingOrOffset, length)
  21180. }
  21181. // Copy static methods from Buffer
  21182. copyProps(Buffer, SafeBuffer)
  21183. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  21184. if (typeof arg === 'number') {
  21185. throw new TypeError('Argument must not be a number')
  21186. }
  21187. return Buffer(arg, encodingOrOffset, length)
  21188. }
  21189. SafeBuffer.alloc = function (size, fill, encoding) {
  21190. if (typeof size !== 'number') {
  21191. throw new TypeError('Argument must be a number')
  21192. }
  21193. var buf = Buffer(size)
  21194. if (fill !== undefined) {
  21195. if (typeof encoding === 'string') {
  21196. buf.fill(fill, encoding)
  21197. } else {
  21198. buf.fill(fill)
  21199. }
  21200. } else {
  21201. buf.fill(0)
  21202. }
  21203. return buf
  21204. }
  21205. SafeBuffer.allocUnsafe = function (size) {
  21206. if (typeof size !== 'number') {
  21207. throw new TypeError('Argument must be a number')
  21208. }
  21209. return Buffer(size)
  21210. }
  21211. SafeBuffer.allocUnsafeSlow = function (size) {
  21212. if (typeof size !== 'number') {
  21213. throw new TypeError('Argument must be a number')
  21214. }
  21215. return buffer.SlowBuffer(size)
  21216. }
  21217. },{"buffer":17}],137:[function(require,module,exports){
  21218. // Copyright Joyent, Inc. and other Node contributors.
  21219. //
  21220. // Permission is hereby granted, free of charge, to any person obtaining a
  21221. // copy of this software and associated documentation files (the
  21222. // "Software"), to deal in the Software without restriction, including
  21223. // without limitation the rights to use, copy, modify, merge, publish,
  21224. // distribute, sublicense, and/or sell copies of the Software, and to permit
  21225. // persons to whom the Software is furnished to do so, subject to the
  21226. // following conditions:
  21227. //
  21228. // The above copyright notice and this permission notice shall be included
  21229. // in all copies or substantial portions of the Software.
  21230. //
  21231. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  21232. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  21233. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  21234. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  21235. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  21236. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  21237. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  21238. 'use strict';
  21239. /*<replacement>*/
  21240. var Buffer = require('safe-buffer').Buffer;
  21241. /*</replacement>*/
  21242. var isEncoding = Buffer.isEncoding || function (encoding) {
  21243. encoding = '' + encoding;
  21244. switch (encoding && encoding.toLowerCase()) {
  21245. case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
  21246. return true;
  21247. default:
  21248. return false;
  21249. }
  21250. };
  21251. function _normalizeEncoding(enc) {
  21252. if (!enc) return 'utf8';
  21253. var retried;
  21254. while (true) {
  21255. switch (enc) {
  21256. case 'utf8':
  21257. case 'utf-8':
  21258. return 'utf8';
  21259. case 'ucs2':
  21260. case 'ucs-2':
  21261. case 'utf16le':
  21262. case 'utf-16le':
  21263. return 'utf16le';
  21264. case 'latin1':
  21265. case 'binary':
  21266. return 'latin1';
  21267. case 'base64':
  21268. case 'ascii':
  21269. case 'hex':
  21270. return enc;
  21271. default:
  21272. if (retried) return; // undefined
  21273. enc = ('' + enc).toLowerCase();
  21274. retried = true;
  21275. }
  21276. }
  21277. };
  21278. // Do not cache `Buffer.isEncoding` when checking encoding names as some
  21279. // modules monkey-patch it to support additional encodings
  21280. function normalizeEncoding(enc) {
  21281. var nenc = _normalizeEncoding(enc);
  21282. if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  21283. return nenc || enc;
  21284. }
  21285. // StringDecoder provides an interface for efficiently splitting a series of
  21286. // buffers into a series of JS strings without breaking apart multi-byte
  21287. // characters.
  21288. exports.StringDecoder = StringDecoder;
  21289. function StringDecoder(encoding) {
  21290. this.encoding = normalizeEncoding(encoding);
  21291. var nb;
  21292. switch (this.encoding) {
  21293. case 'utf16le':
  21294. this.text = utf16Text;
  21295. this.end = utf16End;
  21296. nb = 4;
  21297. break;
  21298. case 'utf8':
  21299. this.fillLast = utf8FillLast;
  21300. nb = 4;
  21301. break;
  21302. case 'base64':
  21303. this.text = base64Text;
  21304. this.end = base64End;
  21305. nb = 3;
  21306. break;
  21307. default:
  21308. this.write = simpleWrite;
  21309. this.end = simpleEnd;
  21310. return;
  21311. }
  21312. this.lastNeed = 0;
  21313. this.lastTotal = 0;
  21314. this.lastChar = Buffer.allocUnsafe(nb);
  21315. }
  21316. StringDecoder.prototype.write = function (buf) {
  21317. if (buf.length === 0) return '';
  21318. var r;
  21319. var i;
  21320. if (this.lastNeed) {
  21321. r = this.fillLast(buf);
  21322. if (r === undefined) return '';
  21323. i = this.lastNeed;
  21324. this.lastNeed = 0;
  21325. } else {
  21326. i = 0;
  21327. }
  21328. if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  21329. return r || '';
  21330. };
  21331. StringDecoder.prototype.end = utf8End;
  21332. // Returns only complete characters in a Buffer
  21333. StringDecoder.prototype.text = utf8Text;
  21334. // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
  21335. StringDecoder.prototype.fillLast = function (buf) {
  21336. if (this.lastNeed <= buf.length) {
  21337. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
  21338. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  21339. }
  21340. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  21341. this.lastNeed -= buf.length;
  21342. };
  21343. // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
  21344. // continuation byte. If an invalid byte is detected, -2 is returned.
  21345. function utf8CheckByte(byte) {
  21346. if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
  21347. return byte >> 6 === 0x02 ? -1 : -2;
  21348. }
  21349. // Checks at most 3 bytes at the end of a Buffer in order to detect an
  21350. // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
  21351. // needed to complete the UTF-8 character (if applicable) are returned.
  21352. function utf8CheckIncomplete(self, buf, i) {
  21353. var j = buf.length - 1;
  21354. if (j < i) return 0;
  21355. var nb = utf8CheckByte(buf[j]);
  21356. if (nb >= 0) {
  21357. if (nb > 0) self.lastNeed = nb - 1;
  21358. return nb;
  21359. }
  21360. if (--j < i || nb === -2) return 0;
  21361. nb = utf8CheckByte(buf[j]);
  21362. if (nb >= 0) {
  21363. if (nb > 0) self.lastNeed = nb - 2;
  21364. return nb;
  21365. }
  21366. if (--j < i || nb === -2) return 0;
  21367. nb = utf8CheckByte(buf[j]);
  21368. if (nb >= 0) {
  21369. if (nb > 0) {
  21370. if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
  21371. }
  21372. return nb;
  21373. }
  21374. return 0;
  21375. }
  21376. // Validates as many continuation bytes for a multi-byte UTF-8 character as
  21377. // needed or are available. If we see a non-continuation byte where we expect
  21378. // one, we "replace" the validated continuation bytes we've seen so far with
  21379. // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
  21380. // behavior. The continuation byte check is included three times in the case
  21381. // where all of the continuation bytes for a character exist in the same buffer.
  21382. // It is also done this way as a slight performance increase instead of using a
  21383. // loop.
  21384. function utf8CheckExtraBytes(self, buf, p) {
  21385. if ((buf[0] & 0xC0) !== 0x80) {
  21386. self.lastNeed = 0;
  21387. return '\ufffd';
  21388. }
  21389. if (self.lastNeed > 1 && buf.length > 1) {
  21390. if ((buf[1] & 0xC0) !== 0x80) {
  21391. self.lastNeed = 1;
  21392. return '\ufffd';
  21393. }
  21394. if (self.lastNeed > 2 && buf.length > 2) {
  21395. if ((buf[2] & 0xC0) !== 0x80) {
  21396. self.lastNeed = 2;
  21397. return '\ufffd';
  21398. }
  21399. }
  21400. }
  21401. }
  21402. // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
  21403. function utf8FillLast(buf) {
  21404. var p = this.lastTotal - this.lastNeed;
  21405. var r = utf8CheckExtraBytes(this, buf, p);
  21406. if (r !== undefined) return r;
  21407. if (this.lastNeed <= buf.length) {
  21408. buf.copy(this.lastChar, p, 0, this.lastNeed);
  21409. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  21410. }
  21411. buf.copy(this.lastChar, p, 0, buf.length);
  21412. this.lastNeed -= buf.length;
  21413. }
  21414. // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
  21415. // partial character, the character's bytes are buffered until the required
  21416. // number of bytes are available.
  21417. function utf8Text(buf, i) {
  21418. var total = utf8CheckIncomplete(this, buf, i);
  21419. if (!this.lastNeed) return buf.toString('utf8', i);
  21420. this.lastTotal = total;
  21421. var end = buf.length - (total - this.lastNeed);
  21422. buf.copy(this.lastChar, 0, end);
  21423. return buf.toString('utf8', i, end);
  21424. }
  21425. // For UTF-8, a replacement character is added when ending on a partial
  21426. // character.
  21427. function utf8End(buf) {
  21428. var r = buf && buf.length ? this.write(buf) : '';
  21429. if (this.lastNeed) return r + '\ufffd';
  21430. return r;
  21431. }
  21432. // UTF-16LE typically needs two bytes per character, but even if we have an even
  21433. // number of bytes available, we need to check if we end on a leading/high
  21434. // surrogate. In that case, we need to wait for the next two bytes in order to
  21435. // decode the last character properly.
  21436. function utf16Text(buf, i) {
  21437. if ((buf.length - i) % 2 === 0) {
  21438. var r = buf.toString('utf16le', i);
  21439. if (r) {
  21440. var c = r.charCodeAt(r.length - 1);
  21441. if (c >= 0xD800 && c <= 0xDBFF) {
  21442. this.lastNeed = 2;
  21443. this.lastTotal = 4;
  21444. this.lastChar[0] = buf[buf.length - 2];
  21445. this.lastChar[1] = buf[buf.length - 1];
  21446. return r.slice(0, -1);
  21447. }
  21448. }
  21449. return r;
  21450. }
  21451. this.lastNeed = 1;
  21452. this.lastTotal = 2;
  21453. this.lastChar[0] = buf[buf.length - 1];
  21454. return buf.toString('utf16le', i, buf.length - 1);
  21455. }
  21456. // For UTF-16LE we do not explicitly append special replacement characters if we
  21457. // end on a partial character, we simply let v8 handle that.
  21458. function utf16End(buf) {
  21459. var r = buf && buf.length ? this.write(buf) : '';
  21460. if (this.lastNeed) {
  21461. var end = this.lastTotal - this.lastNeed;
  21462. return r + this.lastChar.toString('utf16le', 0, end);
  21463. }
  21464. return r;
  21465. }
  21466. function base64Text(buf, i) {
  21467. var n = (buf.length - i) % 3;
  21468. if (n === 0) return buf.toString('base64', i);
  21469. this.lastNeed = 3 - n;
  21470. this.lastTotal = 3;
  21471. if (n === 1) {
  21472. this.lastChar[0] = buf[buf.length - 1];
  21473. } else {
  21474. this.lastChar[0] = buf[buf.length - 2];
  21475. this.lastChar[1] = buf[buf.length - 1];
  21476. }
  21477. return buf.toString('base64', i, buf.length - n);
  21478. }
  21479. function base64End(buf) {
  21480. var r = buf && buf.length ? this.write(buf) : '';
  21481. if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  21482. return r;
  21483. }
  21484. // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
  21485. function simpleWrite(buf) {
  21486. return buf.toString(this.encoding);
  21487. }
  21488. function simpleEnd(buf) {
  21489. return buf && buf.length ? this.write(buf) : '';
  21490. }
  21491. },{"safe-buffer":136}],138:[function(require,module,exports){
  21492. module.exports = require('./readable').PassThrough
  21493. },{"./readable":139}],139:[function(require,module,exports){
  21494. exports = module.exports = require('./lib/_stream_readable.js');
  21495. exports.Stream = exports;
  21496. exports.Readable = exports;
  21497. exports.Writable = require('./lib/_stream_writable.js');
  21498. exports.Duplex = require('./lib/_stream_duplex.js');
  21499. exports.Transform = require('./lib/_stream_transform.js');
  21500. exports.PassThrough = require('./lib/_stream_passthrough.js');
  21501. },{"./lib/_stream_duplex.js":128,"./lib/_stream_passthrough.js":129,"./lib/_stream_readable.js":130,"./lib/_stream_transform.js":131,"./lib/_stream_writable.js":132}],140:[function(require,module,exports){
  21502. module.exports = require('./readable').Transform
  21503. },{"./readable":139}],141:[function(require,module,exports){
  21504. module.exports = require('./lib/_stream_writable.js');
  21505. },{"./lib/_stream_writable.js":132}],142:[function(require,module,exports){
  21506. var EventEmitter = require('events').EventEmitter
  21507. var backoff = require('backoff')
  21508. module.exports =
  21509. function (createConnection) {
  21510. return function (opts, onConnect) {
  21511. onConnect = 'function' == typeof opts ? opts : onConnect
  21512. opts = 'object' == typeof opts ? opts : {initialDelay: 1e3, maxDelay: 30e3}
  21513. if(!onConnect)
  21514. onConnect = opts.onConnect
  21515. var emitter = new EventEmitter()
  21516. emitter.connected = false
  21517. emitter.reconnect = true
  21518. if(onConnect)
  21519. //use "connection" to match core (net) api.
  21520. emitter.on('connection', onConnect)
  21521. var backoffMethod = (backoff[opts.type] || backoff.fibonacci) (opts)
  21522. if(opts.failAfter)
  21523. backoffMethod.failAfter(opts.failAfter);
  21524. backoffMethod.on('backoff', function (n, d, e) {
  21525. emitter.emit('backoff', n, d, e)
  21526. })
  21527. backoffMethod.on('fail', function (e) {
  21528. emitter.disconnect()
  21529. emitter.emit('fail', e)
  21530. })
  21531. var args
  21532. function attempt (n, delay) {
  21533. if(emitter.connected) return
  21534. if(!emitter.reconnect) return
  21535. emitter.emit('reconnect', n, delay)
  21536. var con = createConnection.apply(emitter, args)
  21537. emitter._connection = con
  21538. function onError (err) {
  21539. con.removeListener('error', onError)
  21540. try
  21541. {
  21542. emitter.emit('error', err)
  21543. }
  21544. catch(e){}
  21545. onDisconnect(err)
  21546. }
  21547. function onDisconnect (err) {
  21548. emitter.connected = false
  21549. con.removeListener('close', onDisconnect)
  21550. con.removeListener('end' , onDisconnect)
  21551. //hack to make http not crash.
  21552. //HTTP IS THE WORST PROTOCOL.
  21553. if(con.constructor.name == 'Request')
  21554. con.on('error', function () {})
  21555. //emit disconnect before checking reconnect, so user has a chance to decide not to.
  21556. emitter.emit('disconnect', err)
  21557. if(!emitter.reconnect) return
  21558. try { backoffMethod.backoff(err) } catch (_) { }
  21559. }
  21560. con
  21561. .on('error', onError)
  21562. .on('close', onDisconnect)
  21563. .on('end' , onDisconnect)
  21564. function emitConnect()
  21565. {
  21566. emitter.connected = true
  21567. emitter.emit('connection', con)
  21568. emitter.emit('connect', con)
  21569. }
  21570. if(opts.immediate || con.constructor.name == 'Request') {
  21571. emitConnect()
  21572. con.once('data', function () {
  21573. //this is the only way to know for sure that data is coming...
  21574. backoffMethod.reset()
  21575. })
  21576. } else {
  21577. con
  21578. .once('connect', function () {
  21579. backoffMethod.reset()
  21580. if(onConnect)
  21581. con.removeListener('connect', onConnect)
  21582. emitConnect()
  21583. })
  21584. }
  21585. }
  21586. emitter.connect =
  21587. emitter.listen = function () {
  21588. this.reconnect = true
  21589. if(emitter.connected) return
  21590. backoffMethod.reset()
  21591. backoffMethod.on('ready', attempt)
  21592. args = args || [].slice.call(arguments)
  21593. attempt(0, 0)
  21594. return emitter
  21595. }
  21596. //force reconnection
  21597. emitter.disconnect = function () {
  21598. this.reconnect = false
  21599. if(emitter._connection)
  21600. emitter._connection.end()
  21601. return emitter
  21602. }
  21603. return emitter
  21604. }
  21605. }
  21606. },{"backoff":9,"events":21}],143:[function(require,module,exports){
  21607. var websocket = require('websocket-stream');
  21608. var inject = require('reconnect-core');
  21609. module.exports = inject(function () {
  21610. // Create new websocket-stream instance
  21611. var args = [].slice.call(arguments);
  21612. var ws = websocket.apply(null, args);
  21613. // Copy buffer from old websocket-stream instance on the new one
  21614. var prevCon = this.prevCon;
  21615. if(prevCon && prevCon._buffer)
  21616. ws._buffer = prevCon._buffer;
  21617. this.prevCon = ws;
  21618. // Return new websocket-stream instance
  21619. return ws;
  21620. });
  21621. },{"reconnect-core":142,"websocket-stream":152}],144:[function(require,module,exports){
  21622. // Copyright Joyent, Inc. and other Node contributors.
  21623. //
  21624. // Permission is hereby granted, free of charge, to any person obtaining a
  21625. // copy of this software and associated documentation files (the
  21626. // "Software"), to deal in the Software without restriction, including
  21627. // without limitation the rights to use, copy, modify, merge, publish,
  21628. // distribute, sublicense, and/or sell copies of the Software, and to permit
  21629. // persons to whom the Software is furnished to do so, subject to the
  21630. // following conditions:
  21631. //
  21632. // The above copyright notice and this permission notice shall be included
  21633. // in all copies or substantial portions of the Software.
  21634. //
  21635. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  21636. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  21637. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  21638. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  21639. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  21640. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  21641. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  21642. module.exports = Stream;
  21643. var EE = require('events').EventEmitter;
  21644. var inherits = require('inherits');
  21645. inherits(Stream, EE);
  21646. Stream.Readable = require('readable-stream/readable.js');
  21647. Stream.Writable = require('readable-stream/writable.js');
  21648. Stream.Duplex = require('readable-stream/duplex.js');
  21649. Stream.Transform = require('readable-stream/transform.js');
  21650. Stream.PassThrough = require('readable-stream/passthrough.js');
  21651. // Backwards-compat with node 0.4.x
  21652. Stream.Stream = Stream;
  21653. // old-style streams. Note that the pipe method (the only relevant
  21654. // part of this class) is overridden in the Readable class.
  21655. function Stream() {
  21656. EE.call(this);
  21657. }
  21658. Stream.prototype.pipe = function(dest, options) {
  21659. var source = this;
  21660. function ondata(chunk) {
  21661. if (dest.writable) {
  21662. if (false === dest.write(chunk) && source.pause) {
  21663. source.pause();
  21664. }
  21665. }
  21666. }
  21667. source.on('data', ondata);
  21668. function ondrain() {
  21669. if (source.readable && source.resume) {
  21670. source.resume();
  21671. }
  21672. }
  21673. dest.on('drain', ondrain);
  21674. // If the 'end' option is not supplied, dest.end() will be called when
  21675. // source gets the 'end' or 'close' events. Only dest.end() once.
  21676. if (!dest._isStdio && (!options || options.end !== false)) {
  21677. source.on('end', onend);
  21678. source.on('close', onclose);
  21679. }
  21680. var didOnEnd = false;
  21681. function onend() {
  21682. if (didOnEnd) return;
  21683. didOnEnd = true;
  21684. dest.end();
  21685. }
  21686. function onclose() {
  21687. if (didOnEnd) return;
  21688. didOnEnd = true;
  21689. if (typeof dest.destroy === 'function') dest.destroy();
  21690. }
  21691. // don't leave dangling pipes when there are errors.
  21692. function onerror(er) {
  21693. cleanup();
  21694. if (EE.listenerCount(this, 'error') === 0) {
  21695. throw er; // Unhandled stream error in pipe.
  21696. }
  21697. }
  21698. source.on('error', onerror);
  21699. dest.on('error', onerror);
  21700. // remove all the event listeners that were added.
  21701. function cleanup() {
  21702. source.removeListener('data', ondata);
  21703. dest.removeListener('drain', ondrain);
  21704. source.removeListener('end', onend);
  21705. source.removeListener('close', onclose);
  21706. source.removeListener('error', onerror);
  21707. dest.removeListener('error', onerror);
  21708. source.removeListener('end', cleanup);
  21709. source.removeListener('close', cleanup);
  21710. dest.removeListener('close', cleanup);
  21711. }
  21712. source.on('end', cleanup);
  21713. source.on('close', cleanup);
  21714. dest.on('close', cleanup);
  21715. dest.emit('pipe', source);
  21716. // Allow for unix-like usage: A.pipe(B).pipe(C)
  21717. return dest;
  21718. };
  21719. },{"events":21,"inherits":"inherits","readable-stream/duplex.js":127,"readable-stream/passthrough.js":138,"readable-stream/readable.js":139,"readable-stream/transform.js":140,"readable-stream/writable.js":141}],145:[function(require,module,exports){
  21720. (function (process){
  21721. var Stream = require('stream')
  21722. // through
  21723. //
  21724. // a stream that does nothing but re-emit the input.
  21725. // useful for aggregating a series of changing but not ending streams into one stream)
  21726. exports = module.exports = through
  21727. through.through = through
  21728. //create a readable writable stream.
  21729. function through (write, end, opts) {
  21730. write = write || function (data) { this.queue(data) }
  21731. end = end || function () { this.queue(null) }
  21732. var ended = false, destroyed = false, buffer = [], _ended = false
  21733. var stream = new Stream()
  21734. stream.readable = stream.writable = true
  21735. stream.paused = false
  21736. // stream.autoPause = !(opts && opts.autoPause === false)
  21737. stream.autoDestroy = !(opts && opts.autoDestroy === false)
  21738. stream.write = function (data) {
  21739. write.call(this, data)
  21740. return !stream.paused
  21741. }
  21742. function drain() {
  21743. while(buffer.length && !stream.paused) {
  21744. var data = buffer.shift()
  21745. if(null === data)
  21746. return stream.emit('end')
  21747. else
  21748. stream.emit('data', data)
  21749. }
  21750. }
  21751. stream.queue = stream.push = function (data) {
  21752. // console.error(ended)
  21753. if(_ended) return stream
  21754. if(data === null) _ended = true
  21755. buffer.push(data)
  21756. drain()
  21757. return stream
  21758. }
  21759. //this will be registered as the first 'end' listener
  21760. //must call destroy next tick, to make sure we're after any
  21761. //stream piped from here.
  21762. //this is only a problem if end is not emitted synchronously.
  21763. //a nicer way to do this is to make sure this is the last listener for 'end'
  21764. stream.on('end', function () {
  21765. stream.readable = false
  21766. if(!stream.writable && stream.autoDestroy)
  21767. process.nextTick(function () {
  21768. stream.destroy()
  21769. })
  21770. })
  21771. function _end () {
  21772. stream.writable = false
  21773. end.call(stream)
  21774. if(!stream.readable && stream.autoDestroy)
  21775. stream.destroy()
  21776. }
  21777. stream.end = function (data) {
  21778. if(ended) return
  21779. ended = true
  21780. if(arguments.length) stream.write(data)
  21781. _end() // will emit or queue
  21782. return stream
  21783. }
  21784. stream.destroy = function () {
  21785. if(destroyed) return
  21786. destroyed = true
  21787. ended = true
  21788. buffer.length = 0
  21789. stream.writable = stream.readable = false
  21790. stream.emit('close')
  21791. return stream
  21792. }
  21793. stream.pause = function () {
  21794. if(stream.paused) return
  21795. stream.paused = true
  21796. return stream
  21797. }
  21798. stream.resume = function () {
  21799. if(stream.paused) {
  21800. stream.paused = false
  21801. stream.emit('resume')
  21802. }
  21803. drain()
  21804. //may have become paused again,
  21805. //as drain emits 'data'.
  21806. if(!stream.paused)
  21807. stream.emit('drain')
  21808. return stream
  21809. }
  21810. return stream
  21811. }
  21812. }).call(this,require('_process'))
  21813. },{"_process":122,"stream":144}],146:[function(require,module,exports){
  21814. (function (setImmediate,clearImmediate){
  21815. var nextTick = require('process/browser.js').nextTick;
  21816. var apply = Function.prototype.apply;
  21817. var slice = Array.prototype.slice;
  21818. var immediateIds = {};
  21819. var nextImmediateId = 0;
  21820. // DOM APIs, for completeness
  21821. exports.setTimeout = function() {
  21822. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  21823. };
  21824. exports.setInterval = function() {
  21825. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  21826. };
  21827. exports.clearTimeout =
  21828. exports.clearInterval = function(timeout) { timeout.close(); };
  21829. function Timeout(id, clearFn) {
  21830. this._id = id;
  21831. this._clearFn = clearFn;
  21832. }
  21833. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  21834. Timeout.prototype.close = function() {
  21835. this._clearFn.call(window, this._id);
  21836. };
  21837. // Does not start the time, just sets up the members needed.
  21838. exports.enroll = function(item, msecs) {
  21839. clearTimeout(item._idleTimeoutId);
  21840. item._idleTimeout = msecs;
  21841. };
  21842. exports.unenroll = function(item) {
  21843. clearTimeout(item._idleTimeoutId);
  21844. item._idleTimeout = -1;
  21845. };
  21846. exports._unrefActive = exports.active = function(item) {
  21847. clearTimeout(item._idleTimeoutId);
  21848. var msecs = item._idleTimeout;
  21849. if (msecs >= 0) {
  21850. item._idleTimeoutId = setTimeout(function onTimeout() {
  21851. if (item._onTimeout)
  21852. item._onTimeout();
  21853. }, msecs);
  21854. }
  21855. };
  21856. // That's not how node.js implements it but the exposed api is the same.
  21857. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  21858. var id = nextImmediateId++;
  21859. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  21860. immediateIds[id] = true;
  21861. nextTick(function onNextTick() {
  21862. if (immediateIds[id]) {
  21863. // fn.call() is faster so we optimize for the common use-case
  21864. // @see http://jsperf.com/call-apply-segu
  21865. if (args) {
  21866. fn.apply(null, args);
  21867. } else {
  21868. fn.call(null);
  21869. }
  21870. // Prevent ids from leaking
  21871. exports.clearImmediate(id);
  21872. }
  21873. });
  21874. return id;
  21875. };
  21876. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  21877. delete immediateIds[id];
  21878. };
  21879. }).call(this,require("timers").setImmediate,require("timers").clearImmediate)
  21880. },{"process/browser.js":122,"timers":146}],147:[function(require,module,exports){
  21881. // Copyright Joyent, Inc. and other Node contributors.
  21882. //
  21883. // Permission is hereby granted, free of charge, to any person obtaining a
  21884. // copy of this software and associated documentation files (the
  21885. // "Software"), to deal in the Software without restriction, including
  21886. // without limitation the rights to use, copy, modify, merge, publish,
  21887. // distribute, sublicense, and/or sell copies of the Software, and to permit
  21888. // persons to whom the Software is furnished to do so, subject to the
  21889. // following conditions:
  21890. //
  21891. // The above copyright notice and this permission notice shall be included
  21892. // in all copies or substantial portions of the Software.
  21893. //
  21894. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  21895. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  21896. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  21897. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  21898. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  21899. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  21900. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  21901. 'use strict';
  21902. var punycode = require('punycode');
  21903. var util = require('./util');
  21904. exports.parse = urlParse;
  21905. exports.resolve = urlResolve;
  21906. exports.resolveObject = urlResolveObject;
  21907. exports.format = urlFormat;
  21908. exports.Url = Url;
  21909. function Url() {
  21910. this.protocol = null;
  21911. this.slashes = null;
  21912. this.auth = null;
  21913. this.host = null;
  21914. this.port = null;
  21915. this.hostname = null;
  21916. this.hash = null;
  21917. this.search = null;
  21918. this.query = null;
  21919. this.pathname = null;
  21920. this.path = null;
  21921. this.href = null;
  21922. }
  21923. // Reference: RFC 3986, RFC 1808, RFC 2396
  21924. // define these here so at least they only have to be
  21925. // compiled once on the first module load.
  21926. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  21927. portPattern = /:[0-9]*$/,
  21928. // Special case for a simple path URL
  21929. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  21930. // RFC 2396: characters reserved for delimiting URLs.
  21931. // We actually just auto-escape these.
  21932. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  21933. // RFC 2396: characters not allowed for various reasons.
  21934. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  21935. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  21936. autoEscape = ['\''].concat(unwise),
  21937. // Characters that are never ever allowed in a hostname.
  21938. // Note that any invalid chars are also handled, but these
  21939. // are the ones that are *expected* to be seen, so we fast-path
  21940. // them.
  21941. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  21942. hostEndingChars = ['/', '?', '#'],
  21943. hostnameMaxLen = 255,
  21944. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  21945. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  21946. // protocols that can allow "unsafe" and "unwise" chars.
  21947. unsafeProtocol = {
  21948. 'javascript': true,
  21949. 'javascript:': true
  21950. },
  21951. // protocols that never have a hostname.
  21952. hostlessProtocol = {
  21953. 'javascript': true,
  21954. 'javascript:': true
  21955. },
  21956. // protocols that always contain a // bit.
  21957. slashedProtocol = {
  21958. 'http': true,
  21959. 'https': true,
  21960. 'ftp': true,
  21961. 'gopher': true,
  21962. 'file': true,
  21963. 'http:': true,
  21964. 'https:': true,
  21965. 'ftp:': true,
  21966. 'gopher:': true,
  21967. 'file:': true
  21968. },
  21969. querystring = require('querystring');
  21970. function urlParse(url, parseQueryString, slashesDenoteHost) {
  21971. if (url && util.isObject(url) && url instanceof Url) return url;
  21972. var u = new Url;
  21973. u.parse(url, parseQueryString, slashesDenoteHost);
  21974. return u;
  21975. }
  21976. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  21977. if (!util.isString(url)) {
  21978. throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  21979. }
  21980. // Copy chrome, IE, opera backslash-handling behavior.
  21981. // Back slashes before the query string get converted to forward slashes
  21982. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  21983. var queryIndex = url.indexOf('?'),
  21984. splitter =
  21985. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  21986. uSplit = url.split(splitter),
  21987. slashRegex = /\\/g;
  21988. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  21989. url = uSplit.join(splitter);
  21990. var rest = url;
  21991. // trim before proceeding.
  21992. // This is to support parse stuff like " http://foo.com \n"
  21993. rest = rest.trim();
  21994. if (!slashesDenoteHost && url.split('#').length === 1) {
  21995. // Try fast path regexp
  21996. var simplePath = simplePathPattern.exec(rest);
  21997. if (simplePath) {
  21998. this.path = rest;
  21999. this.href = rest;
  22000. this.pathname = simplePath[1];
  22001. if (simplePath[2]) {
  22002. this.search = simplePath[2];
  22003. if (parseQueryString) {
  22004. this.query = querystring.parse(this.search.substr(1));
  22005. } else {
  22006. this.query = this.search.substr(1);
  22007. }
  22008. } else if (parseQueryString) {
  22009. this.search = '';
  22010. this.query = {};
  22011. }
  22012. return this;
  22013. }
  22014. }
  22015. var proto = protocolPattern.exec(rest);
  22016. if (proto) {
  22017. proto = proto[0];
  22018. var lowerProto = proto.toLowerCase();
  22019. this.protocol = lowerProto;
  22020. rest = rest.substr(proto.length);
  22021. }
  22022. // figure out if it's got a host
  22023. // user@server is *always* interpreted as a hostname, and url
  22024. // resolution will treat //foo/bar as host=foo,path=bar because that's
  22025. // how the browser resolves relative URLs.
  22026. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  22027. var slashes = rest.substr(0, 2) === '//';
  22028. if (slashes && !(proto && hostlessProtocol[proto])) {
  22029. rest = rest.substr(2);
  22030. this.slashes = true;
  22031. }
  22032. }
  22033. if (!hostlessProtocol[proto] &&
  22034. (slashes || (proto && !slashedProtocol[proto]))) {
  22035. // there's a hostname.
  22036. // the first instance of /, ?, ;, or # ends the host.
  22037. //
  22038. // If there is an @ in the hostname, then non-host chars *are* allowed
  22039. // to the left of the last @ sign, unless some host-ending character
  22040. // comes *before* the @-sign.
  22041. // URLs are obnoxious.
  22042. //
  22043. // ex:
  22044. // http://a@b@c/ => user:a@b host:c
  22045. // http://a@b?@c => user:a host:c path:/?@c
  22046. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  22047. // Review our test case against browsers more comprehensively.
  22048. // find the first instance of any hostEndingChars
  22049. var hostEnd = -1;
  22050. for (var i = 0; i < hostEndingChars.length; i++) {
  22051. var hec = rest.indexOf(hostEndingChars[i]);
  22052. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  22053. hostEnd = hec;
  22054. }
  22055. // at this point, either we have an explicit point where the
  22056. // auth portion cannot go past, or the last @ char is the decider.
  22057. var auth, atSign;
  22058. if (hostEnd === -1) {
  22059. // atSign can be anywhere.
  22060. atSign = rest.lastIndexOf('@');
  22061. } else {
  22062. // atSign must be in auth portion.
  22063. // http://a@b/c@d => host:b auth:a path:/c@d
  22064. atSign = rest.lastIndexOf('@', hostEnd);
  22065. }
  22066. // Now we have a portion which is definitely the auth.
  22067. // Pull that off.
  22068. if (atSign !== -1) {
  22069. auth = rest.slice(0, atSign);
  22070. rest = rest.slice(atSign + 1);
  22071. this.auth = decodeURIComponent(auth);
  22072. }
  22073. // the host is the remaining to the left of the first non-host char
  22074. hostEnd = -1;
  22075. for (var i = 0; i < nonHostChars.length; i++) {
  22076. var hec = rest.indexOf(nonHostChars[i]);
  22077. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  22078. hostEnd = hec;
  22079. }
  22080. // if we still have not hit it, then the entire thing is a host.
  22081. if (hostEnd === -1)
  22082. hostEnd = rest.length;
  22083. this.host = rest.slice(0, hostEnd);
  22084. rest = rest.slice(hostEnd);
  22085. // pull out port.
  22086. this.parseHost();
  22087. // we've indicated that there is a hostname,
  22088. // so even if it's empty, it has to be present.
  22089. this.hostname = this.hostname || '';
  22090. // if hostname begins with [ and ends with ]
  22091. // assume that it's an IPv6 address.
  22092. var ipv6Hostname = this.hostname[0] === '[' &&
  22093. this.hostname[this.hostname.length - 1] === ']';
  22094. // validate a little.
  22095. if (!ipv6Hostname) {
  22096. var hostparts = this.hostname.split(/\./);
  22097. for (var i = 0, l = hostparts.length; i < l; i++) {
  22098. var part = hostparts[i];
  22099. if (!part) continue;
  22100. if (!part.match(hostnamePartPattern)) {
  22101. var newpart = '';
  22102. for (var j = 0, k = part.length; j < k; j++) {
  22103. if (part.charCodeAt(j) > 127) {
  22104. // we replace non-ASCII char with a temporary placeholder
  22105. // we need this to make sure size of hostname is not
  22106. // broken by replacing non-ASCII by nothing
  22107. newpart += 'x';
  22108. } else {
  22109. newpart += part[j];
  22110. }
  22111. }
  22112. // we test again with ASCII char only
  22113. if (!newpart.match(hostnamePartPattern)) {
  22114. var validParts = hostparts.slice(0, i);
  22115. var notHost = hostparts.slice(i + 1);
  22116. var bit = part.match(hostnamePartStart);
  22117. if (bit) {
  22118. validParts.push(bit[1]);
  22119. notHost.unshift(bit[2]);
  22120. }
  22121. if (notHost.length) {
  22122. rest = '/' + notHost.join('.') + rest;
  22123. }
  22124. this.hostname = validParts.join('.');
  22125. break;
  22126. }
  22127. }
  22128. }
  22129. }
  22130. if (this.hostname.length > hostnameMaxLen) {
  22131. this.hostname = '';
  22132. } else {
  22133. // hostnames are always lower case.
  22134. this.hostname = this.hostname.toLowerCase();
  22135. }
  22136. if (!ipv6Hostname) {
  22137. // IDNA Support: Returns a punycoded representation of "domain".
  22138. // It only converts parts of the domain name that
  22139. // have non-ASCII characters, i.e. it doesn't matter if
  22140. // you call it with a domain that already is ASCII-only.
  22141. this.hostname = punycode.toASCII(this.hostname);
  22142. }
  22143. var p = this.port ? ':' + this.port : '';
  22144. var h = this.hostname || '';
  22145. this.host = h + p;
  22146. this.href += this.host;
  22147. // strip [ and ] from the hostname
  22148. // the host field still retains them, though
  22149. if (ipv6Hostname) {
  22150. this.hostname = this.hostname.substr(1, this.hostname.length - 2);
  22151. if (rest[0] !== '/') {
  22152. rest = '/' + rest;
  22153. }
  22154. }
  22155. }
  22156. // now rest is set to the post-host stuff.
  22157. // chop off any delim chars.
  22158. if (!unsafeProtocol[lowerProto]) {
  22159. // First, make 100% sure that any "autoEscape" chars get
  22160. // escaped, even if encodeURIComponent doesn't think they
  22161. // need to be.
  22162. for (var i = 0, l = autoEscape.length; i < l; i++) {
  22163. var ae = autoEscape[i];
  22164. if (rest.indexOf(ae) === -1)
  22165. continue;
  22166. var esc = encodeURIComponent(ae);
  22167. if (esc === ae) {
  22168. esc = escape(ae);
  22169. }
  22170. rest = rest.split(ae).join(esc);
  22171. }
  22172. }
  22173. // chop off from the tail first.
  22174. var hash = rest.indexOf('#');
  22175. if (hash !== -1) {
  22176. // got a fragment string.
  22177. this.hash = rest.substr(hash);
  22178. rest = rest.slice(0, hash);
  22179. }
  22180. var qm = rest.indexOf('?');
  22181. if (qm !== -1) {
  22182. this.search = rest.substr(qm);
  22183. this.query = rest.substr(qm + 1);
  22184. if (parseQueryString) {
  22185. this.query = querystring.parse(this.query);
  22186. }
  22187. rest = rest.slice(0, qm);
  22188. } else if (parseQueryString) {
  22189. // no query string, but parseQueryString still requested
  22190. this.search = '';
  22191. this.query = {};
  22192. }
  22193. if (rest) this.pathname = rest;
  22194. if (slashedProtocol[lowerProto] &&
  22195. this.hostname && !this.pathname) {
  22196. this.pathname = '/';
  22197. }
  22198. //to support http.request
  22199. if (this.pathname || this.search) {
  22200. var p = this.pathname || '';
  22201. var s = this.search || '';
  22202. this.path = p + s;
  22203. }
  22204. // finally, reconstruct the href based on what has been validated.
  22205. this.href = this.format();
  22206. return this;
  22207. };
  22208. // format a parsed object into a url string
  22209. function urlFormat(obj) {
  22210. // ensure it's an object, and not a string url.
  22211. // If it's an obj, this is a no-op.
  22212. // this way, you can call url_format() on strings
  22213. // to clean up potentially wonky urls.
  22214. if (util.isString(obj)) obj = urlParse(obj);
  22215. if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
  22216. return obj.format();
  22217. }
  22218. Url.prototype.format = function() {
  22219. var auth = this.auth || '';
  22220. if (auth) {
  22221. auth = encodeURIComponent(auth);
  22222. auth = auth.replace(/%3A/i, ':');
  22223. auth += '@';
  22224. }
  22225. var protocol = this.protocol || '',
  22226. pathname = this.pathname || '',
  22227. hash = this.hash || '',
  22228. host = false,
  22229. query = '';
  22230. if (this.host) {
  22231. host = auth + this.host;
  22232. } else if (this.hostname) {
  22233. host = auth + (this.hostname.indexOf(':') === -1 ?
  22234. this.hostname :
  22235. '[' + this.hostname + ']');
  22236. if (this.port) {
  22237. host += ':' + this.port;
  22238. }
  22239. }
  22240. if (this.query &&
  22241. util.isObject(this.query) &&
  22242. Object.keys(this.query).length) {
  22243. query = querystring.stringify(this.query);
  22244. }
  22245. var search = this.search || (query && ('?' + query)) || '';
  22246. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  22247. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  22248. // unless they had them to begin with.
  22249. if (this.slashes ||
  22250. (!protocol || slashedProtocol[protocol]) && host !== false) {
  22251. host = '//' + (host || '');
  22252. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  22253. } else if (!host) {
  22254. host = '';
  22255. }
  22256. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  22257. if (search && search.charAt(0) !== '?') search = '?' + search;
  22258. pathname = pathname.replace(/[?#]/g, function(match) {
  22259. return encodeURIComponent(match);
  22260. });
  22261. search = search.replace('#', '%23');
  22262. return protocol + host + pathname + search + hash;
  22263. };
  22264. function urlResolve(source, relative) {
  22265. return urlParse(source, false, true).resolve(relative);
  22266. }
  22267. Url.prototype.resolve = function(relative) {
  22268. return this.resolveObject(urlParse(relative, false, true)).format();
  22269. };
  22270. function urlResolveObject(source, relative) {
  22271. if (!source) return relative;
  22272. return urlParse(source, false, true).resolveObject(relative);
  22273. }
  22274. Url.prototype.resolveObject = function(relative) {
  22275. if (util.isString(relative)) {
  22276. var rel = new Url();
  22277. rel.parse(relative, false, true);
  22278. relative = rel;
  22279. }
  22280. var result = new Url();
  22281. var tkeys = Object.keys(this);
  22282. for (var tk = 0; tk < tkeys.length; tk++) {
  22283. var tkey = tkeys[tk];
  22284. result[tkey] = this[tkey];
  22285. }
  22286. // hash is always overridden, no matter what.
  22287. // even href="" will remove it.
  22288. result.hash = relative.hash;
  22289. // if the relative url is empty, then there's nothing left to do here.
  22290. if (relative.href === '') {
  22291. result.href = result.format();
  22292. return result;
  22293. }
  22294. // hrefs like //foo/bar always cut to the protocol.
  22295. if (relative.slashes && !relative.protocol) {
  22296. // take everything except the protocol from relative
  22297. var rkeys = Object.keys(relative);
  22298. for (var rk = 0; rk < rkeys.length; rk++) {
  22299. var rkey = rkeys[rk];
  22300. if (rkey !== 'protocol')
  22301. result[rkey] = relative[rkey];
  22302. }
  22303. //urlParse appends trailing / to urls like http://www.example.com
  22304. if (slashedProtocol[result.protocol] &&
  22305. result.hostname && !result.pathname) {
  22306. result.path = result.pathname = '/';
  22307. }
  22308. result.href = result.format();
  22309. return result;
  22310. }
  22311. if (relative.protocol && relative.protocol !== result.protocol) {
  22312. // if it's a known url protocol, then changing
  22313. // the protocol does weird things
  22314. // first, if it's not file:, then we MUST have a host,
  22315. // and if there was a path
  22316. // to begin with, then we MUST have a path.
  22317. // if it is file:, then the host is dropped,
  22318. // because that's known to be hostless.
  22319. // anything else is assumed to be absolute.
  22320. if (!slashedProtocol[relative.protocol]) {
  22321. var keys = Object.keys(relative);
  22322. for (var v = 0; v < keys.length; v++) {
  22323. var k = keys[v];
  22324. result[k] = relative[k];
  22325. }
  22326. result.href = result.format();
  22327. return result;
  22328. }
  22329. result.protocol = relative.protocol;
  22330. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  22331. var relPath = (relative.pathname || '').split('/');
  22332. while (relPath.length && !(relative.host = relPath.shift()));
  22333. if (!relative.host) relative.host = '';
  22334. if (!relative.hostname) relative.hostname = '';
  22335. if (relPath[0] !== '') relPath.unshift('');
  22336. if (relPath.length < 2) relPath.unshift('');
  22337. result.pathname = relPath.join('/');
  22338. } else {
  22339. result.pathname = relative.pathname;
  22340. }
  22341. result.search = relative.search;
  22342. result.query = relative.query;
  22343. result.host = relative.host || '';
  22344. result.auth = relative.auth;
  22345. result.hostname = relative.hostname || relative.host;
  22346. result.port = relative.port;
  22347. // to support http.request
  22348. if (result.pathname || result.search) {
  22349. var p = result.pathname || '';
  22350. var s = result.search || '';
  22351. result.path = p + s;
  22352. }
  22353. result.slashes = result.slashes || relative.slashes;
  22354. result.href = result.format();
  22355. return result;
  22356. }
  22357. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  22358. isRelAbs = (
  22359. relative.host ||
  22360. relative.pathname && relative.pathname.charAt(0) === '/'
  22361. ),
  22362. mustEndAbs = (isRelAbs || isSourceAbs ||
  22363. (result.host && relative.pathname)),
  22364. removeAllDots = mustEndAbs,
  22365. srcPath = result.pathname && result.pathname.split('/') || [],
  22366. relPath = relative.pathname && relative.pathname.split('/') || [],
  22367. psychotic = result.protocol && !slashedProtocol[result.protocol];
  22368. // if the url is a non-slashed url, then relative
  22369. // links like ../.. should be able
  22370. // to crawl up to the hostname, as well. This is strange.
  22371. // result.protocol has already been set by now.
  22372. // Later on, put the first path part into the host field.
  22373. if (psychotic) {
  22374. result.hostname = '';
  22375. result.port = null;
  22376. if (result.host) {
  22377. if (srcPath[0] === '') srcPath[0] = result.host;
  22378. else srcPath.unshift(result.host);
  22379. }
  22380. result.host = '';
  22381. if (relative.protocol) {
  22382. relative.hostname = null;
  22383. relative.port = null;
  22384. if (relative.host) {
  22385. if (relPath[0] === '') relPath[0] = relative.host;
  22386. else relPath.unshift(relative.host);
  22387. }
  22388. relative.host = null;
  22389. }
  22390. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  22391. }
  22392. if (isRelAbs) {
  22393. // it's absolute.
  22394. result.host = (relative.host || relative.host === '') ?
  22395. relative.host : result.host;
  22396. result.hostname = (relative.hostname || relative.hostname === '') ?
  22397. relative.hostname : result.hostname;
  22398. result.search = relative.search;
  22399. result.query = relative.query;
  22400. srcPath = relPath;
  22401. // fall through to the dot-handling below.
  22402. } else if (relPath.length) {
  22403. // it's relative
  22404. // throw away the existing file, and take the new path instead.
  22405. if (!srcPath) srcPath = [];
  22406. srcPath.pop();
  22407. srcPath = srcPath.concat(relPath);
  22408. result.search = relative.search;
  22409. result.query = relative.query;
  22410. } else if (!util.isNullOrUndefined(relative.search)) {
  22411. // just pull out the search.
  22412. // like href='?foo'.
  22413. // Put this after the other two cases because it simplifies the booleans
  22414. if (psychotic) {
  22415. result.hostname = result.host = srcPath.shift();
  22416. //occationaly the auth can get stuck only in host
  22417. //this especially happens in cases like
  22418. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  22419. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  22420. result.host.split('@') : false;
  22421. if (authInHost) {
  22422. result.auth = authInHost.shift();
  22423. result.host = result.hostname = authInHost.shift();
  22424. }
  22425. }
  22426. result.search = relative.search;
  22427. result.query = relative.query;
  22428. //to support http.request
  22429. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  22430. result.path = (result.pathname ? result.pathname : '') +
  22431. (result.search ? result.search : '');
  22432. }
  22433. result.href = result.format();
  22434. return result;
  22435. }
  22436. if (!srcPath.length) {
  22437. // no path at all. easy.
  22438. // we've already handled the other stuff above.
  22439. result.pathname = null;
  22440. //to support http.request
  22441. if (result.search) {
  22442. result.path = '/' + result.search;
  22443. } else {
  22444. result.path = null;
  22445. }
  22446. result.href = result.format();
  22447. return result;
  22448. }
  22449. // if a url ENDs in . or .., then it must get a trailing slash.
  22450. // however, if it ends in anything else non-slashy,
  22451. // then it must NOT get a trailing slash.
  22452. var last = srcPath.slice(-1)[0];
  22453. var hasTrailingSlash = (
  22454. (result.host || relative.host || srcPath.length > 1) &&
  22455. (last === '.' || last === '..') || last === '');
  22456. // strip single dots, resolve double dots to parent dir
  22457. // if the path tries to go above the root, `up` ends up > 0
  22458. var up = 0;
  22459. for (var i = srcPath.length; i >= 0; i--) {
  22460. last = srcPath[i];
  22461. if (last === '.') {
  22462. srcPath.splice(i, 1);
  22463. } else if (last === '..') {
  22464. srcPath.splice(i, 1);
  22465. up++;
  22466. } else if (up) {
  22467. srcPath.splice(i, 1);
  22468. up--;
  22469. }
  22470. }
  22471. // if the path is allowed to go above the root, restore leading ..s
  22472. if (!mustEndAbs && !removeAllDots) {
  22473. for (; up--; up) {
  22474. srcPath.unshift('..');
  22475. }
  22476. }
  22477. if (mustEndAbs && srcPath[0] !== '' &&
  22478. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  22479. srcPath.unshift('');
  22480. }
  22481. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  22482. srcPath.push('');
  22483. }
  22484. var isAbsolute = srcPath[0] === '' ||
  22485. (srcPath[0] && srcPath[0].charAt(0) === '/');
  22486. // put the host back
  22487. if (psychotic) {
  22488. result.hostname = result.host = isAbsolute ? '' :
  22489. srcPath.length ? srcPath.shift() : '';
  22490. //occationaly the auth can get stuck only in host
  22491. //this especially happens in cases like
  22492. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  22493. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  22494. result.host.split('@') : false;
  22495. if (authInHost) {
  22496. result.auth = authInHost.shift();
  22497. result.host = result.hostname = authInHost.shift();
  22498. }
  22499. }
  22500. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  22501. if (mustEndAbs && !isAbsolute) {
  22502. srcPath.unshift('');
  22503. }
  22504. if (!srcPath.length) {
  22505. result.pathname = null;
  22506. result.path = null;
  22507. } else {
  22508. result.pathname = srcPath.join('/');
  22509. }
  22510. //to support request.http
  22511. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  22512. result.path = (result.pathname ? result.pathname : '') +
  22513. (result.search ? result.search : '');
  22514. }
  22515. result.auth = relative.auth || result.auth;
  22516. result.slashes = result.slashes || relative.slashes;
  22517. result.href = result.format();
  22518. return result;
  22519. };
  22520. Url.prototype.parseHost = function() {
  22521. var host = this.host;
  22522. var port = portPattern.exec(host);
  22523. if (port) {
  22524. port = port[0];
  22525. if (port !== ':') {
  22526. this.port = port.substr(1);
  22527. }
  22528. host = host.substr(0, host.length - port.length);
  22529. }
  22530. if (host) this.hostname = host;
  22531. };
  22532. },{"./util":148,"punycode":123,"querystring":126}],148:[function(require,module,exports){
  22533. 'use strict';
  22534. module.exports = {
  22535. isString: function(arg) {
  22536. return typeof(arg) === 'string';
  22537. },
  22538. isObject: function(arg) {
  22539. return typeof(arg) === 'object' && arg !== null;
  22540. },
  22541. isNull: function(arg) {
  22542. return arg === null;
  22543. },
  22544. isNullOrUndefined: function(arg) {
  22545. return arg == null;
  22546. }
  22547. };
  22548. },{}],149:[function(require,module,exports){
  22549. (function (global){
  22550. /**
  22551. * Module exports.
  22552. */
  22553. module.exports = deprecate;
  22554. /**
  22555. * Mark that a method should not be used.
  22556. * Returns a modified function which warns once by default.
  22557. *
  22558. * If `localStorage.noDeprecation = true` is set, then it is a no-op.
  22559. *
  22560. * If `localStorage.throwDeprecation = true` is set, then deprecated functions
  22561. * will throw an Error when invoked.
  22562. *
  22563. * If `localStorage.traceDeprecation = true` is set, then deprecated functions
  22564. * will invoke `console.trace()` instead of `console.error()`.
  22565. *
  22566. * @param {Function} fn - the function to deprecate
  22567. * @param {String} msg - the string to print to the console when `fn` is invoked
  22568. * @returns {Function} a new "deprecated" version of `fn`
  22569. * @api public
  22570. */
  22571. function deprecate (fn, msg) {
  22572. if (config('noDeprecation')) {
  22573. return fn;
  22574. }
  22575. var warned = false;
  22576. function deprecated() {
  22577. if (!warned) {
  22578. if (config('throwDeprecation')) {
  22579. throw new Error(msg);
  22580. } else if (config('traceDeprecation')) {
  22581. console.trace(msg);
  22582. } else {
  22583. console.warn(msg);
  22584. }
  22585. warned = true;
  22586. }
  22587. return fn.apply(this, arguments);
  22588. }
  22589. return deprecated;
  22590. }
  22591. /**
  22592. * Checks `localStorage` for boolean values for the given `name`.
  22593. *
  22594. * @param {String} name
  22595. * @returns {Boolean}
  22596. * @api private
  22597. */
  22598. function config (name) {
  22599. // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  22600. try {
  22601. if (!global.localStorage) return false;
  22602. } catch (_) {
  22603. return false;
  22604. }
  22605. var val = global.localStorage[name];
  22606. if (null == val) return false;
  22607. return String(val).toLowerCase() === 'true';
  22608. }
  22609. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  22610. },{}],150:[function(require,module,exports){
  22611. module.exports = function isBuffer(arg) {
  22612. return arg && typeof arg === 'object'
  22613. && typeof arg.copy === 'function'
  22614. && typeof arg.fill === 'function'
  22615. && typeof arg.readUInt8 === 'function';
  22616. }
  22617. },{}],151:[function(require,module,exports){
  22618. (function (process,global){
  22619. // Copyright Joyent, Inc. and other Node contributors.
  22620. //
  22621. // Permission is hereby granted, free of charge, to any person obtaining a
  22622. // copy of this software and associated documentation files (the
  22623. // "Software"), to deal in the Software without restriction, including
  22624. // without limitation the rights to use, copy, modify, merge, publish,
  22625. // distribute, sublicense, and/or sell copies of the Software, and to permit
  22626. // persons to whom the Software is furnished to do so, subject to the
  22627. // following conditions:
  22628. //
  22629. // The above copyright notice and this permission notice shall be included
  22630. // in all copies or substantial portions of the Software.
  22631. //
  22632. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  22633. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22634. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  22635. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  22636. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22637. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  22638. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  22639. var formatRegExp = /%[sdj%]/g;
  22640. exports.format = function(f) {
  22641. if (!isString(f)) {
  22642. var objects = [];
  22643. for (var i = 0; i < arguments.length; i++) {
  22644. objects.push(inspect(arguments[i]));
  22645. }
  22646. return objects.join(' ');
  22647. }
  22648. var i = 1;
  22649. var args = arguments;
  22650. var len = args.length;
  22651. var str = String(f).replace(formatRegExp, function(x) {
  22652. if (x === '%%') return '%';
  22653. if (i >= len) return x;
  22654. switch (x) {
  22655. case '%s': return String(args[i++]);
  22656. case '%d': return Number(args[i++]);
  22657. case '%j':
  22658. try {
  22659. return JSON.stringify(args[i++]);
  22660. } catch (_) {
  22661. return '[Circular]';
  22662. }
  22663. default:
  22664. return x;
  22665. }
  22666. });
  22667. for (var x = args[i]; i < len; x = args[++i]) {
  22668. if (isNull(x) || !isObject(x)) {
  22669. str += ' ' + x;
  22670. } else {
  22671. str += ' ' + inspect(x);
  22672. }
  22673. }
  22674. return str;
  22675. };
  22676. // Mark that a method should not be used.
  22677. // Returns a modified function which warns once by default.
  22678. // If --no-deprecation is set, then it is a no-op.
  22679. exports.deprecate = function(fn, msg) {
  22680. // Allow for deprecating things in the process of starting up.
  22681. if (isUndefined(global.process)) {
  22682. return function() {
  22683. return exports.deprecate(fn, msg).apply(this, arguments);
  22684. };
  22685. }
  22686. if (process.noDeprecation === true) {
  22687. return fn;
  22688. }
  22689. var warned = false;
  22690. function deprecated() {
  22691. if (!warned) {
  22692. if (process.throwDeprecation) {
  22693. throw new Error(msg);
  22694. } else if (process.traceDeprecation) {
  22695. console.trace(msg);
  22696. } else {
  22697. console.error(msg);
  22698. }
  22699. warned = true;
  22700. }
  22701. return fn.apply(this, arguments);
  22702. }
  22703. return deprecated;
  22704. };
  22705. var debugs = {};
  22706. var debugEnviron;
  22707. exports.debuglog = function(set) {
  22708. if (isUndefined(debugEnviron))
  22709. debugEnviron = process.env.NODE_DEBUG || '';
  22710. set = set.toUpperCase();
  22711. if (!debugs[set]) {
  22712. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  22713. var pid = process.pid;
  22714. debugs[set] = function() {
  22715. var msg = exports.format.apply(exports, arguments);
  22716. console.error('%s %d: %s', set, pid, msg);
  22717. };
  22718. } else {
  22719. debugs[set] = function() {};
  22720. }
  22721. }
  22722. return debugs[set];
  22723. };
  22724. /**
  22725. * Echos the value of a value. Trys to print the value out
  22726. * in the best way possible given the different types.
  22727. *
  22728. * @param {Object} obj The object to print out.
  22729. * @param {Object} opts Optional options object that alters the output.
  22730. */
  22731. /* legacy: obj, showHidden, depth, colors*/
  22732. function inspect(obj, opts) {
  22733. // default options
  22734. var ctx = {
  22735. seen: [],
  22736. stylize: stylizeNoColor
  22737. };
  22738. // legacy...
  22739. if (arguments.length >= 3) ctx.depth = arguments[2];
  22740. if (arguments.length >= 4) ctx.colors = arguments[3];
  22741. if (isBoolean(opts)) {
  22742. // legacy...
  22743. ctx.showHidden = opts;
  22744. } else if (opts) {
  22745. // got an "options" object
  22746. exports._extend(ctx, opts);
  22747. }
  22748. // set default options
  22749. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  22750. if (isUndefined(ctx.depth)) ctx.depth = 2;
  22751. if (isUndefined(ctx.colors)) ctx.colors = false;
  22752. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  22753. if (ctx.colors) ctx.stylize = stylizeWithColor;
  22754. return formatValue(ctx, obj, ctx.depth);
  22755. }
  22756. exports.inspect = inspect;
  22757. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  22758. inspect.colors = {
  22759. 'bold' : [1, 22],
  22760. 'italic' : [3, 23],
  22761. 'underline' : [4, 24],
  22762. 'inverse' : [7, 27],
  22763. 'white' : [37, 39],
  22764. 'grey' : [90, 39],
  22765. 'black' : [30, 39],
  22766. 'blue' : [34, 39],
  22767. 'cyan' : [36, 39],
  22768. 'green' : [32, 39],
  22769. 'magenta' : [35, 39],
  22770. 'red' : [31, 39],
  22771. 'yellow' : [33, 39]
  22772. };
  22773. // Don't use 'blue' not visible on cmd.exe
  22774. inspect.styles = {
  22775. 'special': 'cyan',
  22776. 'number': 'yellow',
  22777. 'boolean': 'yellow',
  22778. 'undefined': 'grey',
  22779. 'null': 'bold',
  22780. 'string': 'green',
  22781. 'date': 'magenta',
  22782. // "name": intentionally not styling
  22783. 'regexp': 'red'
  22784. };
  22785. function stylizeWithColor(str, styleType) {
  22786. var style = inspect.styles[styleType];
  22787. if (style) {
  22788. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  22789. '\u001b[' + inspect.colors[style][1] + 'm';
  22790. } else {
  22791. return str;
  22792. }
  22793. }
  22794. function stylizeNoColor(str, styleType) {
  22795. return str;
  22796. }
  22797. function arrayToHash(array) {
  22798. var hash = {};
  22799. array.forEach(function(val, idx) {
  22800. hash[val] = true;
  22801. });
  22802. return hash;
  22803. }
  22804. function formatValue(ctx, value, recurseTimes) {
  22805. // Provide a hook for user-specified inspect functions.
  22806. // Check that value is an object with an inspect function on it
  22807. if (ctx.customInspect &&
  22808. value &&
  22809. isFunction(value.inspect) &&
  22810. // Filter out the util module, it's inspect function is special
  22811. value.inspect !== exports.inspect &&
  22812. // Also filter out any prototype objects using the circular check.
  22813. !(value.constructor && value.constructor.prototype === value)) {
  22814. var ret = value.inspect(recurseTimes, ctx);
  22815. if (!isString(ret)) {
  22816. ret = formatValue(ctx, ret, recurseTimes);
  22817. }
  22818. return ret;
  22819. }
  22820. // Primitive types cannot have properties
  22821. var primitive = formatPrimitive(ctx, value);
  22822. if (primitive) {
  22823. return primitive;
  22824. }
  22825. // Look up the keys of the object.
  22826. var keys = Object.keys(value);
  22827. var visibleKeys = arrayToHash(keys);
  22828. if (ctx.showHidden) {
  22829. keys = Object.getOwnPropertyNames(value);
  22830. }
  22831. // IE doesn't make error fields non-enumerable
  22832. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  22833. if (isError(value)
  22834. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  22835. return formatError(value);
  22836. }
  22837. // Some type of object without properties can be shortcutted.
  22838. if (keys.length === 0) {
  22839. if (isFunction(value)) {
  22840. var name = value.name ? ': ' + value.name : '';
  22841. return ctx.stylize('[Function' + name + ']', 'special');
  22842. }
  22843. if (isRegExp(value)) {
  22844. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  22845. }
  22846. if (isDate(value)) {
  22847. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  22848. }
  22849. if (isError(value)) {
  22850. return formatError(value);
  22851. }
  22852. }
  22853. var base = '', array = false, braces = ['{', '}'];
  22854. // Make Array say that they are Array
  22855. if (isArray(value)) {
  22856. array = true;
  22857. braces = ['[', ']'];
  22858. }
  22859. // Make functions say that they are functions
  22860. if (isFunction(value)) {
  22861. var n = value.name ? ': ' + value.name : '';
  22862. base = ' [Function' + n + ']';
  22863. }
  22864. // Make RegExps say that they are RegExps
  22865. if (isRegExp(value)) {
  22866. base = ' ' + RegExp.prototype.toString.call(value);
  22867. }
  22868. // Make dates with properties first say the date
  22869. if (isDate(value)) {
  22870. base = ' ' + Date.prototype.toUTCString.call(value);
  22871. }
  22872. // Make error with message first say the error
  22873. if (isError(value)) {
  22874. base = ' ' + formatError(value);
  22875. }
  22876. if (keys.length === 0 && (!array || value.length == 0)) {
  22877. return braces[0] + base + braces[1];
  22878. }
  22879. if (recurseTimes < 0) {
  22880. if (isRegExp(value)) {
  22881. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  22882. } else {
  22883. return ctx.stylize('[Object]', 'special');
  22884. }
  22885. }
  22886. ctx.seen.push(value);
  22887. var output;
  22888. if (array) {
  22889. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  22890. } else {
  22891. output = keys.map(function(key) {
  22892. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  22893. });
  22894. }
  22895. ctx.seen.pop();
  22896. return reduceToSingleString(output, base, braces);
  22897. }
  22898. function formatPrimitive(ctx, value) {
  22899. if (isUndefined(value))
  22900. return ctx.stylize('undefined', 'undefined');
  22901. if (isString(value)) {
  22902. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  22903. .replace(/'/g, "\\'")
  22904. .replace(/\\"/g, '"') + '\'';
  22905. return ctx.stylize(simple, 'string');
  22906. }
  22907. if (isNumber(value))
  22908. return ctx.stylize('' + value, 'number');
  22909. if (isBoolean(value))
  22910. return ctx.stylize('' + value, 'boolean');
  22911. // For some reason typeof null is "object", so special case here.
  22912. if (isNull(value))
  22913. return ctx.stylize('null', 'null');
  22914. }
  22915. function formatError(value) {
  22916. return '[' + Error.prototype.toString.call(value) + ']';
  22917. }
  22918. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  22919. var output = [];
  22920. for (var i = 0, l = value.length; i < l; ++i) {
  22921. if (hasOwnProperty(value, String(i))) {
  22922. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  22923. String(i), true));
  22924. } else {
  22925. output.push('');
  22926. }
  22927. }
  22928. keys.forEach(function(key) {
  22929. if (!key.match(/^\d+$/)) {
  22930. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  22931. key, true));
  22932. }
  22933. });
  22934. return output;
  22935. }
  22936. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  22937. var name, str, desc;
  22938. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  22939. if (desc.get) {
  22940. if (desc.set) {
  22941. str = ctx.stylize('[Getter/Setter]', 'special');
  22942. } else {
  22943. str = ctx.stylize('[Getter]', 'special');
  22944. }
  22945. } else {
  22946. if (desc.set) {
  22947. str = ctx.stylize('[Setter]', 'special');
  22948. }
  22949. }
  22950. if (!hasOwnProperty(visibleKeys, key)) {
  22951. name = '[' + key + ']';
  22952. }
  22953. if (!str) {
  22954. if (ctx.seen.indexOf(desc.value) < 0) {
  22955. if (isNull(recurseTimes)) {
  22956. str = formatValue(ctx, desc.value, null);
  22957. } else {
  22958. str = formatValue(ctx, desc.value, recurseTimes - 1);
  22959. }
  22960. if (str.indexOf('\n') > -1) {
  22961. if (array) {
  22962. str = str.split('\n').map(function(line) {
  22963. return ' ' + line;
  22964. }).join('\n').substr(2);
  22965. } else {
  22966. str = '\n' + str.split('\n').map(function(line) {
  22967. return ' ' + line;
  22968. }).join('\n');
  22969. }
  22970. }
  22971. } else {
  22972. str = ctx.stylize('[Circular]', 'special');
  22973. }
  22974. }
  22975. if (isUndefined(name)) {
  22976. if (array && key.match(/^\d+$/)) {
  22977. return str;
  22978. }
  22979. name = JSON.stringify('' + key);
  22980. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  22981. name = name.substr(1, name.length - 2);
  22982. name = ctx.stylize(name, 'name');
  22983. } else {
  22984. name = name.replace(/'/g, "\\'")
  22985. .replace(/\\"/g, '"')
  22986. .replace(/(^"|"$)/g, "'");
  22987. name = ctx.stylize(name, 'string');
  22988. }
  22989. }
  22990. return name + ': ' + str;
  22991. }
  22992. function reduceToSingleString(output, base, braces) {
  22993. var numLinesEst = 0;
  22994. var length = output.reduce(function(prev, cur) {
  22995. numLinesEst++;
  22996. if (cur.indexOf('\n') >= 0) numLinesEst++;
  22997. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  22998. }, 0);
  22999. if (length > 60) {
  23000. return braces[0] +
  23001. (base === '' ? '' : base + '\n ') +
  23002. ' ' +
  23003. output.join(',\n ') +
  23004. ' ' +
  23005. braces[1];
  23006. }
  23007. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  23008. }
  23009. // NOTE: These type checking functions intentionally don't use `instanceof`
  23010. // because it is fragile and can be easily faked with `Object.create()`.
  23011. function isArray(ar) {
  23012. return Array.isArray(ar);
  23013. }
  23014. exports.isArray = isArray;
  23015. function isBoolean(arg) {
  23016. return typeof arg === 'boolean';
  23017. }
  23018. exports.isBoolean = isBoolean;
  23019. function isNull(arg) {
  23020. return arg === null;
  23021. }
  23022. exports.isNull = isNull;
  23023. function isNullOrUndefined(arg) {
  23024. return arg == null;
  23025. }
  23026. exports.isNullOrUndefined = isNullOrUndefined;
  23027. function isNumber(arg) {
  23028. return typeof arg === 'number';
  23029. }
  23030. exports.isNumber = isNumber;
  23031. function isString(arg) {
  23032. return typeof arg === 'string';
  23033. }
  23034. exports.isString = isString;
  23035. function isSymbol(arg) {
  23036. return typeof arg === 'symbol';
  23037. }
  23038. exports.isSymbol = isSymbol;
  23039. function isUndefined(arg) {
  23040. return arg === void 0;
  23041. }
  23042. exports.isUndefined = isUndefined;
  23043. function isRegExp(re) {
  23044. return isObject(re) && objectToString(re) === '[object RegExp]';
  23045. }
  23046. exports.isRegExp = isRegExp;
  23047. function isObject(arg) {
  23048. return typeof arg === 'object' && arg !== null;
  23049. }
  23050. exports.isObject = isObject;
  23051. function isDate(d) {
  23052. return isObject(d) && objectToString(d) === '[object Date]';
  23053. }
  23054. exports.isDate = isDate;
  23055. function isError(e) {
  23056. return isObject(e) &&
  23057. (objectToString(e) === '[object Error]' || e instanceof Error);
  23058. }
  23059. exports.isError = isError;
  23060. function isFunction(arg) {
  23061. return typeof arg === 'function';
  23062. }
  23063. exports.isFunction = isFunction;
  23064. function isPrimitive(arg) {
  23065. return arg === null ||
  23066. typeof arg === 'boolean' ||
  23067. typeof arg === 'number' ||
  23068. typeof arg === 'string' ||
  23069. typeof arg === 'symbol' || // ES6 symbol
  23070. typeof arg === 'undefined';
  23071. }
  23072. exports.isPrimitive = isPrimitive;
  23073. exports.isBuffer = require('./support/isBuffer');
  23074. function objectToString(o) {
  23075. return Object.prototype.toString.call(o);
  23076. }
  23077. function pad(n) {
  23078. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  23079. }
  23080. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  23081. 'Oct', 'Nov', 'Dec'];
  23082. // 26 Feb 16:19:34
  23083. function timestamp() {
  23084. var d = new Date();
  23085. var time = [pad(d.getHours()),
  23086. pad(d.getMinutes()),
  23087. pad(d.getSeconds())].join(':');
  23088. return [d.getDate(), months[d.getMonth()], time].join(' ');
  23089. }
  23090. // log is just a thin wrapper to console.log that prepends a timestamp
  23091. exports.log = function() {
  23092. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  23093. };
  23094. /**
  23095. * Inherit the prototype methods from one constructor into another.
  23096. *
  23097. * The Function.prototype.inherits from lang.js rewritten as a standalone
  23098. * function (not on Function.prototype). NOTE: If this file is to be loaded
  23099. * during bootstrapping this function needs to be rewritten using some native
  23100. * functions as prototype setup using normal JavaScript does not work as
  23101. * expected during bootstrapping (see mirror.js in r114903).
  23102. *
  23103. * @param {function} ctor Constructor function which needs to inherit the
  23104. * prototype.
  23105. * @param {function} superCtor Constructor function to inherit prototype from.
  23106. */
  23107. exports.inherits = require('inherits');
  23108. exports._extend = function(origin, add) {
  23109. // Don't do anything if add isn't an object
  23110. if (!add || !isObject(add)) return origin;
  23111. var keys = Object.keys(add);
  23112. var i = keys.length;
  23113. while (i--) {
  23114. origin[keys[i]] = add[keys[i]];
  23115. }
  23116. return origin;
  23117. };
  23118. function hasOwnProperty(obj, prop) {
  23119. return Object.prototype.hasOwnProperty.call(obj, prop);
  23120. }
  23121. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  23122. },{"./support/isBuffer":150,"_process":122,"inherits":"inherits"}],152:[function(require,module,exports){
  23123. (function (process){
  23124. var through = require('through')
  23125. var isBuffer = require('isbuffer')
  23126. var WebSocketPoly = require('ws')
  23127. function WebsocketStream(server, options) {
  23128. if (!(this instanceof WebsocketStream)) return new WebsocketStream(server, options)
  23129. this.stream = through(this.write.bind(this), this.end.bind(this))
  23130. this.stream.websocketStream = this
  23131. this.options = options || {}
  23132. this._buffer = []
  23133. if (typeof server === "object") {
  23134. this.ws = server
  23135. this.ws.on('message', this.onMessage.bind(this))
  23136. this.ws.on('error', this.onError.bind(this))
  23137. this.ws.on('close', this.onClose.bind(this))
  23138. this.ws.on('open', this.onOpen.bind(this))
  23139. if (this.ws.readyState === 1) this._open = true
  23140. } else {
  23141. var opts = (process.title === 'browser') ? this.options.protocol : this.options
  23142. this.ws = new WebSocketPoly(server, opts)
  23143. this.ws.binaryType = this.options.binaryType || 'arraybuffer'
  23144. this.ws.onmessage = this.onMessage.bind(this)
  23145. this.ws.onerror = this.onError.bind(this)
  23146. this.ws.onclose = this.onClose.bind(this)
  23147. this.ws.onopen = this.onOpen.bind(this)
  23148. }
  23149. return this.stream
  23150. }
  23151. module.exports = WebsocketStream
  23152. module.exports.WebsocketStream = WebsocketStream
  23153. WebsocketStream.prototype.onMessage = function(e) {
  23154. var data = e
  23155. if (typeof data.data !== 'undefined') data = data.data
  23156. // type must be a Typed Array (ArrayBufferView)
  23157. var type = this.options.type
  23158. if (type && data instanceof ArrayBuffer) data = new type(data)
  23159. this.stream.queue(data)
  23160. }
  23161. WebsocketStream.prototype.onError = function(err) {
  23162. this.stream.emit('error', err)
  23163. }
  23164. WebsocketStream.prototype.onClose = function(err) {
  23165. if (this._destroy) return
  23166. this.stream.emit('end')
  23167. this.stream.emit('close')
  23168. }
  23169. WebsocketStream.prototype.onOpen = function(err) {
  23170. if (this._destroy) return
  23171. this._open = true
  23172. for (var i = 0; i < this._buffer.length; i++) {
  23173. this._write(this._buffer[i])
  23174. }
  23175. this._buffer = undefined
  23176. this.stream.emit('open')
  23177. this.stream.emit('connect')
  23178. if (this._end) this.ws.close()
  23179. }
  23180. WebsocketStream.prototype.write = function(data) {
  23181. if (!this._open) {
  23182. this._buffer.push(data)
  23183. } else {
  23184. this._write(data)
  23185. }
  23186. }
  23187. WebsocketStream.prototype._write = function(data) {
  23188. if (this.ws.readyState == 1)
  23189. // we are connected
  23190. typeof WebSocket != 'undefined' && this.ws instanceof WebSocket
  23191. ? this.ws.send(data)
  23192. : this.ws.send(data, { binary : isBuffer(data) })
  23193. else
  23194. this.stream.emit('error', 'Not connected')
  23195. }
  23196. WebsocketStream.prototype.end = function(data) {
  23197. if (data !== undefined) this.stream.queue(data)
  23198. if (this._open) this.ws.close()
  23199. this._end = true
  23200. }
  23201. }).call(this,require('_process'))
  23202. },{"_process":122,"isbuffer":26,"through":145,"ws":153}],153:[function(require,module,exports){
  23203. /**
  23204. * Module dependencies.
  23205. */
  23206. var global = (function() { return this; })();
  23207. /**
  23208. * WebSocket constructor.
  23209. */
  23210. var WebSocket = global.WebSocket || global.MozWebSocket;
  23211. /**
  23212. * Module exports.
  23213. */
  23214. module.exports = WebSocket ? ws : null;
  23215. /**
  23216. * WebSocket constructor.
  23217. *
  23218. * The third `opts` options object gets ignored in web browsers, since it's
  23219. * non-standard, and throws a TypeError if passed to the constructor.
  23220. * See: https://github.com/einaros/ws/issues/227
  23221. *
  23222. * @param {String} uri
  23223. * @param {Array} protocols (optional)
  23224. * @param {Object) opts (optional)
  23225. * @api public
  23226. */
  23227. function ws(uri, protocols, opts) {
  23228. var instance;
  23229. if (protocols) {
  23230. instance = new WebSocket(uri, protocols);
  23231. } else {
  23232. instance = new WebSocket(uri);
  23233. }
  23234. return instance;
  23235. }
  23236. if (WebSocket) ws.prototype = WebSocket.prototype;
  23237. },{}],154:[function(require,module,exports){
  23238. 'use strict';
  23239. module.exports = function() {
  23240. throw new Error(
  23241. 'ws does not work in the browser. Browser clients must use the native ' +
  23242. 'WebSocket object'
  23243. );
  23244. };
  23245. },{}],"async":[function(require,module,exports){
  23246. (function (process,global,setImmediate){
  23247. (function (global, factory) {
  23248. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  23249. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  23250. (factory((global.async = global.async || {})));
  23251. }(this, (function (exports) { 'use strict';
  23252. function slice(arrayLike, start) {
  23253. start = start|0;
  23254. var newLen = Math.max(arrayLike.length - start, 0);
  23255. var newArr = Array(newLen);
  23256. for(var idx = 0; idx < newLen; idx++) {
  23257. newArr[idx] = arrayLike[start + idx];
  23258. }
  23259. return newArr;
  23260. }
  23261. /**
  23262. * Creates a continuation function with some arguments already applied.
  23263. *
  23264. * Useful as a shorthand when combined with other control flow functions. Any
  23265. * arguments passed to the returned function are added to the arguments
  23266. * originally passed to apply.
  23267. *
  23268. * @name apply
  23269. * @static
  23270. * @memberOf module:Utils
  23271. * @method
  23272. * @category Util
  23273. * @param {Function} fn - The function you want to eventually apply all
  23274. * arguments to. Invokes with (arguments...).
  23275. * @param {...*} arguments... - Any number of arguments to automatically apply
  23276. * when the continuation is called.
  23277. * @returns {Function} the partially-applied function
  23278. * @example
  23279. *
  23280. * // using apply
  23281. * async.parallel([
  23282. * async.apply(fs.writeFile, 'testfile1', 'test1'),
  23283. * async.apply(fs.writeFile, 'testfile2', 'test2')
  23284. * ]);
  23285. *
  23286. *
  23287. * // the same process without using apply
  23288. * async.parallel([
  23289. * function(callback) {
  23290. * fs.writeFile('testfile1', 'test1', callback);
  23291. * },
  23292. * function(callback) {
  23293. * fs.writeFile('testfile2', 'test2', callback);
  23294. * }
  23295. * ]);
  23296. *
  23297. * // It's possible to pass any number of additional arguments when calling the
  23298. * // continuation:
  23299. *
  23300. * node> var fn = async.apply(sys.puts, 'one');
  23301. * node> fn('two', 'three');
  23302. * one
  23303. * two
  23304. * three
  23305. */
  23306. var apply = function(fn/*, ...args*/) {
  23307. var args = slice(arguments, 1);
  23308. return function(/*callArgs*/) {
  23309. var callArgs = slice(arguments);
  23310. return fn.apply(null, args.concat(callArgs));
  23311. };
  23312. };
  23313. var initialParams = function (fn) {
  23314. return function (/*...args, callback*/) {
  23315. var args = slice(arguments);
  23316. var callback = args.pop();
  23317. fn.call(this, args, callback);
  23318. };
  23319. };
  23320. /**
  23321. * Checks if `value` is the
  23322. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  23323. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  23324. *
  23325. * @static
  23326. * @memberOf _
  23327. * @since 0.1.0
  23328. * @category Lang
  23329. * @param {*} value The value to check.
  23330. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  23331. * @example
  23332. *
  23333. * _.isObject({});
  23334. * // => true
  23335. *
  23336. * _.isObject([1, 2, 3]);
  23337. * // => true
  23338. *
  23339. * _.isObject(_.noop);
  23340. * // => true
  23341. *
  23342. * _.isObject(null);
  23343. * // => false
  23344. */
  23345. function isObject(value) {
  23346. var type = typeof value;
  23347. return value != null && (type == 'object' || type == 'function');
  23348. }
  23349. var hasSetImmediate = typeof setImmediate === 'function' && setImmediate;
  23350. var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function';
  23351. function fallback(fn) {
  23352. setTimeout(fn, 0);
  23353. }
  23354. function wrap(defer) {
  23355. return function (fn/*, ...args*/) {
  23356. var args = slice(arguments, 1);
  23357. defer(function () {
  23358. fn.apply(null, args);
  23359. });
  23360. };
  23361. }
  23362. var _defer;
  23363. if (hasSetImmediate) {
  23364. _defer = setImmediate;
  23365. } else if (hasNextTick) {
  23366. _defer = process.nextTick;
  23367. } else {
  23368. _defer = fallback;
  23369. }
  23370. var setImmediate$1 = wrap(_defer);
  23371. /**
  23372. * Take a sync function and make it async, passing its return value to a
  23373. * callback. This is useful for plugging sync functions into a waterfall,
  23374. * series, or other async functions. Any arguments passed to the generated
  23375. * function will be passed to the wrapped function (except for the final
  23376. * callback argument). Errors thrown will be passed to the callback.
  23377. *
  23378. * If the function passed to `asyncify` returns a Promise, that promises's
  23379. * resolved/rejected state will be used to call the callback, rather than simply
  23380. * the synchronous return value.
  23381. *
  23382. * This also means you can asyncify ES2017 `async` functions.
  23383. *
  23384. * @name asyncify
  23385. * @static
  23386. * @memberOf module:Utils
  23387. * @method
  23388. * @alias wrapSync
  23389. * @category Util
  23390. * @param {Function} func - The synchronous function, or Promise-returning
  23391. * function to convert to an {@link AsyncFunction}.
  23392. * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be
  23393. * invoked with `(args..., callback)`.
  23394. * @example
  23395. *
  23396. * // passing a regular synchronous function
  23397. * async.waterfall([
  23398. * async.apply(fs.readFile, filename, "utf8"),
  23399. * async.asyncify(JSON.parse),
  23400. * function (data, next) {
  23401. * // data is the result of parsing the text.
  23402. * // If there was a parsing error, it would have been caught.
  23403. * }
  23404. * ], callback);
  23405. *
  23406. * // passing a function returning a promise
  23407. * async.waterfall([
  23408. * async.apply(fs.readFile, filename, "utf8"),
  23409. * async.asyncify(function (contents) {
  23410. * return db.model.create(contents);
  23411. * }),
  23412. * function (model, next) {
  23413. * // `model` is the instantiated model object.
  23414. * // If there was an error, this function would be skipped.
  23415. * }
  23416. * ], callback);
  23417. *
  23418. * // es2017 example, though `asyncify` is not needed if your JS environment
  23419. * // supports async functions out of the box
  23420. * var q = async.queue(async.asyncify(async function(file) {
  23421. * var intermediateStep = await processFile(file);
  23422. * return await somePromise(intermediateStep)
  23423. * }));
  23424. *
  23425. * q.push(files);
  23426. */
  23427. function asyncify(func) {
  23428. return initialParams(function (args, callback) {
  23429. var result;
  23430. try {
  23431. result = func.apply(this, args);
  23432. } catch (e) {
  23433. return callback(e);
  23434. }
  23435. // if result is Promise object
  23436. if (isObject(result) && typeof result.then === 'function') {
  23437. result.then(function(value) {
  23438. invokeCallback(callback, null, value);
  23439. }, function(err) {
  23440. invokeCallback(callback, err.message ? err : new Error(err));
  23441. });
  23442. } else {
  23443. callback(null, result);
  23444. }
  23445. });
  23446. }
  23447. function invokeCallback(callback, error, value) {
  23448. try {
  23449. callback(error, value);
  23450. } catch (e) {
  23451. setImmediate$1(rethrow, e);
  23452. }
  23453. }
  23454. function rethrow(error) {
  23455. throw error;
  23456. }
  23457. var supportsSymbol = typeof Symbol === 'function';
  23458. function isAsync(fn) {
  23459. return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction';
  23460. }
  23461. function wrapAsync(asyncFn) {
  23462. return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn;
  23463. }
  23464. function applyEach$1(eachfn) {
  23465. return function(fns/*, ...args*/) {
  23466. var args = slice(arguments, 1);
  23467. var go = initialParams(function(args, callback) {
  23468. var that = this;
  23469. return eachfn(fns, function (fn, cb) {
  23470. wrapAsync(fn).apply(that, args.concat(cb));
  23471. }, callback);
  23472. });
  23473. if (args.length) {
  23474. return go.apply(this, args);
  23475. }
  23476. else {
  23477. return go;
  23478. }
  23479. };
  23480. }
  23481. /** Detect free variable `global` from Node.js. */
  23482. var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
  23483. /** Detect free variable `self`. */
  23484. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  23485. /** Used as a reference to the global object. */
  23486. var root = freeGlobal || freeSelf || Function('return this')();
  23487. /** Built-in value references. */
  23488. var Symbol$1 = root.Symbol;
  23489. /** Used for built-in method references. */
  23490. var objectProto = Object.prototype;
  23491. /** Used to check objects for own properties. */
  23492. var hasOwnProperty = objectProto.hasOwnProperty;
  23493. /**
  23494. * Used to resolve the
  23495. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  23496. * of values.
  23497. */
  23498. var nativeObjectToString = objectProto.toString;
  23499. /** Built-in value references. */
  23500. var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined;
  23501. /**
  23502. * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
  23503. *
  23504. * @private
  23505. * @param {*} value The value to query.
  23506. * @returns {string} Returns the raw `toStringTag`.
  23507. */
  23508. function getRawTag(value) {
  23509. var isOwn = hasOwnProperty.call(value, symToStringTag$1),
  23510. tag = value[symToStringTag$1];
  23511. try {
  23512. value[symToStringTag$1] = undefined;
  23513. var unmasked = true;
  23514. } catch (e) {}
  23515. var result = nativeObjectToString.call(value);
  23516. if (unmasked) {
  23517. if (isOwn) {
  23518. value[symToStringTag$1] = tag;
  23519. } else {
  23520. delete value[symToStringTag$1];
  23521. }
  23522. }
  23523. return result;
  23524. }
  23525. /** Used for built-in method references. */
  23526. var objectProto$1 = Object.prototype;
  23527. /**
  23528. * Used to resolve the
  23529. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  23530. * of values.
  23531. */
  23532. var nativeObjectToString$1 = objectProto$1.toString;
  23533. /**
  23534. * Converts `value` to a string using `Object.prototype.toString`.
  23535. *
  23536. * @private
  23537. * @param {*} value The value to convert.
  23538. * @returns {string} Returns the converted string.
  23539. */
  23540. function objectToString(value) {
  23541. return nativeObjectToString$1.call(value);
  23542. }
  23543. /** `Object#toString` result references. */
  23544. var nullTag = '[object Null]';
  23545. var undefinedTag = '[object Undefined]';
  23546. /** Built-in value references. */
  23547. var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined;
  23548. /**
  23549. * The base implementation of `getTag` without fallbacks for buggy environments.
  23550. *
  23551. * @private
  23552. * @param {*} value The value to query.
  23553. * @returns {string} Returns the `toStringTag`.
  23554. */
  23555. function baseGetTag(value) {
  23556. if (value == null) {
  23557. return value === undefined ? undefinedTag : nullTag;
  23558. }
  23559. return (symToStringTag && symToStringTag in Object(value))
  23560. ? getRawTag(value)
  23561. : objectToString(value);
  23562. }
  23563. /** `Object#toString` result references. */
  23564. var asyncTag = '[object AsyncFunction]';
  23565. var funcTag = '[object Function]';
  23566. var genTag = '[object GeneratorFunction]';
  23567. var proxyTag = '[object Proxy]';
  23568. /**
  23569. * Checks if `value` is classified as a `Function` object.
  23570. *
  23571. * @static
  23572. * @memberOf _
  23573. * @since 0.1.0
  23574. * @category Lang
  23575. * @param {*} value The value to check.
  23576. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  23577. * @example
  23578. *
  23579. * _.isFunction(_);
  23580. * // => true
  23581. *
  23582. * _.isFunction(/abc/);
  23583. * // => false
  23584. */
  23585. function isFunction(value) {
  23586. if (!isObject(value)) {
  23587. return false;
  23588. }
  23589. // The use of `Object#toString` avoids issues with the `typeof` operator
  23590. // in Safari 9 which returns 'object' for typed arrays and other constructors.
  23591. var tag = baseGetTag(value);
  23592. return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
  23593. }
  23594. /** Used as references for various `Number` constants. */
  23595. var MAX_SAFE_INTEGER = 9007199254740991;
  23596. /**
  23597. * Checks if `value` is a valid array-like length.
  23598. *
  23599. * **Note:** This method is loosely based on
  23600. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  23601. *
  23602. * @static
  23603. * @memberOf _
  23604. * @since 4.0.0
  23605. * @category Lang
  23606. * @param {*} value The value to check.
  23607. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  23608. * @example
  23609. *
  23610. * _.isLength(3);
  23611. * // => true
  23612. *
  23613. * _.isLength(Number.MIN_VALUE);
  23614. * // => false
  23615. *
  23616. * _.isLength(Infinity);
  23617. * // => false
  23618. *
  23619. * _.isLength('3');
  23620. * // => false
  23621. */
  23622. function isLength(value) {
  23623. return typeof value == 'number' &&
  23624. value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  23625. }
  23626. /**
  23627. * Checks if `value` is array-like. A value is considered array-like if it's
  23628. * not a function and has a `value.length` that's an integer greater than or
  23629. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  23630. *
  23631. * @static
  23632. * @memberOf _
  23633. * @since 4.0.0
  23634. * @category Lang
  23635. * @param {*} value The value to check.
  23636. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  23637. * @example
  23638. *
  23639. * _.isArrayLike([1, 2, 3]);
  23640. * // => true
  23641. *
  23642. * _.isArrayLike(document.body.children);
  23643. * // => true
  23644. *
  23645. * _.isArrayLike('abc');
  23646. * // => true
  23647. *
  23648. * _.isArrayLike(_.noop);
  23649. * // => false
  23650. */
  23651. function isArrayLike(value) {
  23652. return value != null && isLength(value.length) && !isFunction(value);
  23653. }
  23654. // A temporary value used to identify if the loop should be broken.
  23655. // See #1064, #1293
  23656. var breakLoop = {};
  23657. /**
  23658. * This method returns `undefined`.
  23659. *
  23660. * @static
  23661. * @memberOf _
  23662. * @since 2.3.0
  23663. * @category Util
  23664. * @example
  23665. *
  23666. * _.times(2, _.noop);
  23667. * // => [undefined, undefined]
  23668. */
  23669. function noop() {
  23670. // No operation performed.
  23671. }
  23672. function once(fn) {
  23673. return function () {
  23674. if (fn === null) return;
  23675. var callFn = fn;
  23676. fn = null;
  23677. callFn.apply(this, arguments);
  23678. };
  23679. }
  23680. var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator;
  23681. var getIterator = function (coll) {
  23682. return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol]();
  23683. };
  23684. /**
  23685. * The base implementation of `_.times` without support for iteratee shorthands
  23686. * or max array length checks.
  23687. *
  23688. * @private
  23689. * @param {number} n The number of times to invoke `iteratee`.
  23690. * @param {Function} iteratee The function invoked per iteration.
  23691. * @returns {Array} Returns the array of results.
  23692. */
  23693. function baseTimes(n, iteratee) {
  23694. var index = -1,
  23695. result = Array(n);
  23696. while (++index < n) {
  23697. result[index] = iteratee(index);
  23698. }
  23699. return result;
  23700. }
  23701. /**
  23702. * Checks if `value` is object-like. A value is object-like if it's not `null`
  23703. * and has a `typeof` result of "object".
  23704. *
  23705. * @static
  23706. * @memberOf _
  23707. * @since 4.0.0
  23708. * @category Lang
  23709. * @param {*} value The value to check.
  23710. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  23711. * @example
  23712. *
  23713. * _.isObjectLike({});
  23714. * // => true
  23715. *
  23716. * _.isObjectLike([1, 2, 3]);
  23717. * // => true
  23718. *
  23719. * _.isObjectLike(_.noop);
  23720. * // => false
  23721. *
  23722. * _.isObjectLike(null);
  23723. * // => false
  23724. */
  23725. function isObjectLike(value) {
  23726. return value != null && typeof value == 'object';
  23727. }
  23728. /** `Object#toString` result references. */
  23729. var argsTag = '[object Arguments]';
  23730. /**
  23731. * The base implementation of `_.isArguments`.
  23732. *
  23733. * @private
  23734. * @param {*} value The value to check.
  23735. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  23736. */
  23737. function baseIsArguments(value) {
  23738. return isObjectLike(value) && baseGetTag(value) == argsTag;
  23739. }
  23740. /** Used for built-in method references. */
  23741. var objectProto$3 = Object.prototype;
  23742. /** Used to check objects for own properties. */
  23743. var hasOwnProperty$2 = objectProto$3.hasOwnProperty;
  23744. /** Built-in value references. */
  23745. var propertyIsEnumerable = objectProto$3.propertyIsEnumerable;
  23746. /**
  23747. * Checks if `value` is likely an `arguments` object.
  23748. *
  23749. * @static
  23750. * @memberOf _
  23751. * @since 0.1.0
  23752. * @category Lang
  23753. * @param {*} value The value to check.
  23754. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  23755. * else `false`.
  23756. * @example
  23757. *
  23758. * _.isArguments(function() { return arguments; }());
  23759. * // => true
  23760. *
  23761. * _.isArguments([1, 2, 3]);
  23762. * // => false
  23763. */
  23764. var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
  23765. return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') &&
  23766. !propertyIsEnumerable.call(value, 'callee');
  23767. };
  23768. /**
  23769. * Checks if `value` is classified as an `Array` object.
  23770. *
  23771. * @static
  23772. * @memberOf _
  23773. * @since 0.1.0
  23774. * @category Lang
  23775. * @param {*} value The value to check.
  23776. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  23777. * @example
  23778. *
  23779. * _.isArray([1, 2, 3]);
  23780. * // => true
  23781. *
  23782. * _.isArray(document.body.children);
  23783. * // => false
  23784. *
  23785. * _.isArray('abc');
  23786. * // => false
  23787. *
  23788. * _.isArray(_.noop);
  23789. * // => false
  23790. */
  23791. var isArray = Array.isArray;
  23792. /**
  23793. * This method returns `false`.
  23794. *
  23795. * @static
  23796. * @memberOf _
  23797. * @since 4.13.0
  23798. * @category Util
  23799. * @returns {boolean} Returns `false`.
  23800. * @example
  23801. *
  23802. * _.times(2, _.stubFalse);
  23803. * // => [false, false]
  23804. */
  23805. function stubFalse() {
  23806. return false;
  23807. }
  23808. /** Detect free variable `exports`. */
  23809. var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
  23810. /** Detect free variable `module`. */
  23811. var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
  23812. /** Detect the popular CommonJS extension `module.exports`. */
  23813. var moduleExports = freeModule && freeModule.exports === freeExports;
  23814. /** Built-in value references. */
  23815. var Buffer = moduleExports ? root.Buffer : undefined;
  23816. /* Built-in method references for those with the same name as other `lodash` methods. */
  23817. var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
  23818. /**
  23819. * Checks if `value` is a buffer.
  23820. *
  23821. * @static
  23822. * @memberOf _
  23823. * @since 4.3.0
  23824. * @category Lang
  23825. * @param {*} value The value to check.
  23826. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
  23827. * @example
  23828. *
  23829. * _.isBuffer(new Buffer(2));
  23830. * // => true
  23831. *
  23832. * _.isBuffer(new Uint8Array(2));
  23833. * // => false
  23834. */
  23835. var isBuffer = nativeIsBuffer || stubFalse;
  23836. /** Used as references for various `Number` constants. */
  23837. var MAX_SAFE_INTEGER$1 = 9007199254740991;
  23838. /** Used to detect unsigned integer values. */
  23839. var reIsUint = /^(?:0|[1-9]\d*)$/;
  23840. /**
  23841. * Checks if `value` is a valid array-like index.
  23842. *
  23843. * @private
  23844. * @param {*} value The value to check.
  23845. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  23846. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  23847. */
  23848. function isIndex(value, length) {
  23849. var type = typeof value;
  23850. length = length == null ? MAX_SAFE_INTEGER$1 : length;
  23851. return !!length &&
  23852. (type == 'number' ||
  23853. (type != 'symbol' && reIsUint.test(value))) &&
  23854. (value > -1 && value % 1 == 0 && value < length);
  23855. }
  23856. /** `Object#toString` result references. */
  23857. var argsTag$1 = '[object Arguments]';
  23858. var arrayTag = '[object Array]';
  23859. var boolTag = '[object Boolean]';
  23860. var dateTag = '[object Date]';
  23861. var errorTag = '[object Error]';
  23862. var funcTag$1 = '[object Function]';
  23863. var mapTag = '[object Map]';
  23864. var numberTag = '[object Number]';
  23865. var objectTag = '[object Object]';
  23866. var regexpTag = '[object RegExp]';
  23867. var setTag = '[object Set]';
  23868. var stringTag = '[object String]';
  23869. var weakMapTag = '[object WeakMap]';
  23870. var arrayBufferTag = '[object ArrayBuffer]';
  23871. var dataViewTag = '[object DataView]';
  23872. var float32Tag = '[object Float32Array]';
  23873. var float64Tag = '[object Float64Array]';
  23874. var int8Tag = '[object Int8Array]';
  23875. var int16Tag = '[object Int16Array]';
  23876. var int32Tag = '[object Int32Array]';
  23877. var uint8Tag = '[object Uint8Array]';
  23878. var uint8ClampedTag = '[object Uint8ClampedArray]';
  23879. var uint16Tag = '[object Uint16Array]';
  23880. var uint32Tag = '[object Uint32Array]';
  23881. /** Used to identify `toStringTag` values of typed arrays. */
  23882. var typedArrayTags = {};
  23883. typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
  23884. typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
  23885. typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
  23886. typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
  23887. typedArrayTags[uint32Tag] = true;
  23888. typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] =
  23889. typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
  23890. typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
  23891. typedArrayTags[errorTag] = typedArrayTags[funcTag$1] =
  23892. typedArrayTags[mapTag] = typedArrayTags[numberTag] =
  23893. typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
  23894. typedArrayTags[setTag] = typedArrayTags[stringTag] =
  23895. typedArrayTags[weakMapTag] = false;
  23896. /**
  23897. * The base implementation of `_.isTypedArray` without Node.js optimizations.
  23898. *
  23899. * @private
  23900. * @param {*} value The value to check.
  23901. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  23902. */
  23903. function baseIsTypedArray(value) {
  23904. return isObjectLike(value) &&
  23905. isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
  23906. }
  23907. /**
  23908. * The base implementation of `_.unary` without support for storing metadata.
  23909. *
  23910. * @private
  23911. * @param {Function} func The function to cap arguments for.
  23912. * @returns {Function} Returns the new capped function.
  23913. */
  23914. function baseUnary(func) {
  23915. return function(value) {
  23916. return func(value);
  23917. };
  23918. }
  23919. /** Detect free variable `exports`. */
  23920. var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports;
  23921. /** Detect free variable `module`. */
  23922. var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module;
  23923. /** Detect the popular CommonJS extension `module.exports`. */
  23924. var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1;
  23925. /** Detect free variable `process` from Node.js. */
  23926. var freeProcess = moduleExports$1 && freeGlobal.process;
  23927. /** Used to access faster Node.js helpers. */
  23928. var nodeUtil = (function() {
  23929. try {
  23930. // Use `util.types` for Node.js 10+.
  23931. var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types;
  23932. if (types) {
  23933. return types;
  23934. }
  23935. // Legacy `process.binding('util')` for Node.js < 10.
  23936. return freeProcess && freeProcess.binding && freeProcess.binding('util');
  23937. } catch (e) {}
  23938. }());
  23939. /* Node.js helper references. */
  23940. var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
  23941. /**
  23942. * Checks if `value` is classified as a typed array.
  23943. *
  23944. * @static
  23945. * @memberOf _
  23946. * @since 3.0.0
  23947. * @category Lang
  23948. * @param {*} value The value to check.
  23949. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  23950. * @example
  23951. *
  23952. * _.isTypedArray(new Uint8Array);
  23953. * // => true
  23954. *
  23955. * _.isTypedArray([]);
  23956. * // => false
  23957. */
  23958. var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
  23959. /** Used for built-in method references. */
  23960. var objectProto$2 = Object.prototype;
  23961. /** Used to check objects for own properties. */
  23962. var hasOwnProperty$1 = objectProto$2.hasOwnProperty;
  23963. /**
  23964. * Creates an array of the enumerable property names of the array-like `value`.
  23965. *
  23966. * @private
  23967. * @param {*} value The value to query.
  23968. * @param {boolean} inherited Specify returning inherited property names.
  23969. * @returns {Array} Returns the array of property names.
  23970. */
  23971. function arrayLikeKeys(value, inherited) {
  23972. var isArr = isArray(value),
  23973. isArg = !isArr && isArguments(value),
  23974. isBuff = !isArr && !isArg && isBuffer(value),
  23975. isType = !isArr && !isArg && !isBuff && isTypedArray(value),
  23976. skipIndexes = isArr || isArg || isBuff || isType,
  23977. result = skipIndexes ? baseTimes(value.length, String) : [],
  23978. length = result.length;
  23979. for (var key in value) {
  23980. if ((inherited || hasOwnProperty$1.call(value, key)) &&
  23981. !(skipIndexes && (
  23982. // Safari 9 has enumerable `arguments.length` in strict mode.
  23983. key == 'length' ||
  23984. // Node.js 0.10 has enumerable non-index properties on buffers.
  23985. (isBuff && (key == 'offset' || key == 'parent')) ||
  23986. // PhantomJS 2 has enumerable non-index properties on typed arrays.
  23987. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
  23988. // Skip index properties.
  23989. isIndex(key, length)
  23990. ))) {
  23991. result.push(key);
  23992. }
  23993. }
  23994. return result;
  23995. }
  23996. /** Used for built-in method references. */
  23997. var objectProto$5 = Object.prototype;
  23998. /**
  23999. * Checks if `value` is likely a prototype object.
  24000. *
  24001. * @private
  24002. * @param {*} value The value to check.
  24003. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
  24004. */
  24005. function isPrototype(value) {
  24006. var Ctor = value && value.constructor,
  24007. proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5;
  24008. return value === proto;
  24009. }
  24010. /**
  24011. * Creates a unary function that invokes `func` with its argument transformed.
  24012. *
  24013. * @private
  24014. * @param {Function} func The function to wrap.
  24015. * @param {Function} transform The argument transform.
  24016. * @returns {Function} Returns the new function.
  24017. */
  24018. function overArg(func, transform) {
  24019. return function(arg) {
  24020. return func(transform(arg));
  24021. };
  24022. }
  24023. /* Built-in method references for those with the same name as other `lodash` methods. */
  24024. var nativeKeys = overArg(Object.keys, Object);
  24025. /** Used for built-in method references. */
  24026. var objectProto$4 = Object.prototype;
  24027. /** Used to check objects for own properties. */
  24028. var hasOwnProperty$3 = objectProto$4.hasOwnProperty;
  24029. /**
  24030. * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
  24031. *
  24032. * @private
  24033. * @param {Object} object The object to query.
  24034. * @returns {Array} Returns the array of property names.
  24035. */
  24036. function baseKeys(object) {
  24037. if (!isPrototype(object)) {
  24038. return nativeKeys(object);
  24039. }
  24040. var result = [];
  24041. for (var key in Object(object)) {
  24042. if (hasOwnProperty$3.call(object, key) && key != 'constructor') {
  24043. result.push(key);
  24044. }
  24045. }
  24046. return result;
  24047. }
  24048. /**
  24049. * Creates an array of the own enumerable property names of `object`.
  24050. *
  24051. * **Note:** Non-object values are coerced to objects. See the
  24052. * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  24053. * for more details.
  24054. *
  24055. * @static
  24056. * @since 0.1.0
  24057. * @memberOf _
  24058. * @category Object
  24059. * @param {Object} object The object to query.
  24060. * @returns {Array} Returns the array of property names.
  24061. * @example
  24062. *
  24063. * function Foo() {
  24064. * this.a = 1;
  24065. * this.b = 2;
  24066. * }
  24067. *
  24068. * Foo.prototype.c = 3;
  24069. *
  24070. * _.keys(new Foo);
  24071. * // => ['a', 'b'] (iteration order is not guaranteed)
  24072. *
  24073. * _.keys('hi');
  24074. * // => ['0', '1']
  24075. */
  24076. function keys(object) {
  24077. return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
  24078. }
  24079. function createArrayIterator(coll) {
  24080. var i = -1;
  24081. var len = coll.length;
  24082. return function next() {
  24083. return ++i < len ? {value: coll[i], key: i} : null;
  24084. }
  24085. }
  24086. function createES2015Iterator(iterator) {
  24087. var i = -1;
  24088. return function next() {
  24089. var item = iterator.next();
  24090. if (item.done)
  24091. return null;
  24092. i++;
  24093. return {value: item.value, key: i};
  24094. }
  24095. }
  24096. function createObjectIterator(obj) {
  24097. var okeys = keys(obj);
  24098. var i = -1;
  24099. var len = okeys.length;
  24100. return function next() {
  24101. var key = okeys[++i];
  24102. return i < len ? {value: obj[key], key: key} : null;
  24103. };
  24104. }
  24105. function iterator(coll) {
  24106. if (isArrayLike(coll)) {
  24107. return createArrayIterator(coll);
  24108. }
  24109. var iterator = getIterator(coll);
  24110. return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);
  24111. }
  24112. function onlyOnce(fn) {
  24113. return function() {
  24114. if (fn === null) throw new Error("Callback was already called.");
  24115. var callFn = fn;
  24116. fn = null;
  24117. callFn.apply(this, arguments);
  24118. };
  24119. }
  24120. function _eachOfLimit(limit) {
  24121. return function (obj, iteratee, callback) {
  24122. callback = once(callback || noop);
  24123. if (limit <= 0 || !obj) {
  24124. return callback(null);
  24125. }
  24126. var nextElem = iterator(obj);
  24127. var done = false;
  24128. var running = 0;
  24129. var looping = false;
  24130. function iterateeCallback(err, value) {
  24131. running -= 1;
  24132. if (err) {
  24133. done = true;
  24134. callback(err);
  24135. }
  24136. else if (value === breakLoop || (done && running <= 0)) {
  24137. done = true;
  24138. return callback(null);
  24139. }
  24140. else if (!looping) {
  24141. replenish();
  24142. }
  24143. }
  24144. function replenish () {
  24145. looping = true;
  24146. while (running < limit && !done) {
  24147. var elem = nextElem();
  24148. if (elem === null) {
  24149. done = true;
  24150. if (running <= 0) {
  24151. callback(null);
  24152. }
  24153. return;
  24154. }
  24155. running += 1;
  24156. iteratee(elem.value, elem.key, onlyOnce(iterateeCallback));
  24157. }
  24158. looping = false;
  24159. }
  24160. replenish();
  24161. };
  24162. }
  24163. /**
  24164. * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a
  24165. * time.
  24166. *
  24167. * @name eachOfLimit
  24168. * @static
  24169. * @memberOf module:Collections
  24170. * @method
  24171. * @see [async.eachOf]{@link module:Collections.eachOf}
  24172. * @alias forEachOfLimit
  24173. * @category Collection
  24174. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  24175. * @param {number} limit - The maximum number of async operations at a time.
  24176. * @param {AsyncFunction} iteratee - An async function to apply to each
  24177. * item in `coll`. The `key` is the item's key, or index in the case of an
  24178. * array.
  24179. * Invoked with (item, key, callback).
  24180. * @param {Function} [callback] - A callback which is called when all
  24181. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  24182. */
  24183. function eachOfLimit(coll, limit, iteratee, callback) {
  24184. _eachOfLimit(limit)(coll, wrapAsync(iteratee), callback);
  24185. }
  24186. function doLimit(fn, limit) {
  24187. return function (iterable, iteratee, callback) {
  24188. return fn(iterable, limit, iteratee, callback);
  24189. };
  24190. }
  24191. // eachOf implementation optimized for array-likes
  24192. function eachOfArrayLike(coll, iteratee, callback) {
  24193. callback = once(callback || noop);
  24194. var index = 0,
  24195. completed = 0,
  24196. length = coll.length;
  24197. if (length === 0) {
  24198. callback(null);
  24199. }
  24200. function iteratorCallback(err, value) {
  24201. if (err) {
  24202. callback(err);
  24203. } else if ((++completed === length) || value === breakLoop) {
  24204. callback(null);
  24205. }
  24206. }
  24207. for (; index < length; index++) {
  24208. iteratee(coll[index], index, onlyOnce(iteratorCallback));
  24209. }
  24210. }
  24211. // a generic version of eachOf which can handle array, object, and iterator cases.
  24212. var eachOfGeneric = doLimit(eachOfLimit, Infinity);
  24213. /**
  24214. * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument
  24215. * to the iteratee.
  24216. *
  24217. * @name eachOf
  24218. * @static
  24219. * @memberOf module:Collections
  24220. * @method
  24221. * @alias forEachOf
  24222. * @category Collection
  24223. * @see [async.each]{@link module:Collections.each}
  24224. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  24225. * @param {AsyncFunction} iteratee - A function to apply to each
  24226. * item in `coll`.
  24227. * The `key` is the item's key, or index in the case of an array.
  24228. * Invoked with (item, key, callback).
  24229. * @param {Function} [callback] - A callback which is called when all
  24230. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  24231. * @example
  24232. *
  24233. * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"};
  24234. * var configs = {};
  24235. *
  24236. * async.forEachOf(obj, function (value, key, callback) {
  24237. * fs.readFile(__dirname + value, "utf8", function (err, data) {
  24238. * if (err) return callback(err);
  24239. * try {
  24240. * configs[key] = JSON.parse(data);
  24241. * } catch (e) {
  24242. * return callback(e);
  24243. * }
  24244. * callback();
  24245. * });
  24246. * }, function (err) {
  24247. * if (err) console.error(err.message);
  24248. * // configs is now a map of JSON data
  24249. * doSomethingWith(configs);
  24250. * });
  24251. */
  24252. var eachOf = function(coll, iteratee, callback) {
  24253. var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric;
  24254. eachOfImplementation(coll, wrapAsync(iteratee), callback);
  24255. };
  24256. function doParallel(fn) {
  24257. return function (obj, iteratee, callback) {
  24258. return fn(eachOf, obj, wrapAsync(iteratee), callback);
  24259. };
  24260. }
  24261. function _asyncMap(eachfn, arr, iteratee, callback) {
  24262. callback = callback || noop;
  24263. arr = arr || [];
  24264. var results = [];
  24265. var counter = 0;
  24266. var _iteratee = wrapAsync(iteratee);
  24267. eachfn(arr, function (value, _, callback) {
  24268. var index = counter++;
  24269. _iteratee(value, function (err, v) {
  24270. results[index] = v;
  24271. callback(err);
  24272. });
  24273. }, function (err) {
  24274. callback(err, results);
  24275. });
  24276. }
  24277. /**
  24278. * Produces a new collection of values by mapping each value in `coll` through
  24279. * the `iteratee` function. The `iteratee` is called with an item from `coll`
  24280. * and a callback for when it has finished processing. Each of these callback
  24281. * takes 2 arguments: an `error`, and the transformed item from `coll`. If
  24282. * `iteratee` passes an error to its callback, the main `callback` (for the
  24283. * `map` function) is immediately called with the error.
  24284. *
  24285. * Note, that since this function applies the `iteratee` to each item in
  24286. * parallel, there is no guarantee that the `iteratee` functions will complete
  24287. * in order. However, the results array will be in the same order as the
  24288. * original `coll`.
  24289. *
  24290. * If `map` is passed an Object, the results will be an Array. The results
  24291. * will roughly be in the order of the original Objects' keys (but this can
  24292. * vary across JavaScript engines).
  24293. *
  24294. * @name map
  24295. * @static
  24296. * @memberOf module:Collections
  24297. * @method
  24298. * @category Collection
  24299. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  24300. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  24301. * `coll`.
  24302. * The iteratee should complete with the transformed item.
  24303. * Invoked with (item, callback).
  24304. * @param {Function} [callback] - A callback which is called when all `iteratee`
  24305. * functions have finished, or an error occurs. Results is an Array of the
  24306. * transformed items from the `coll`. Invoked with (err, results).
  24307. * @example
  24308. *
  24309. * async.map(['file1','file2','file3'], fs.stat, function(err, results) {
  24310. * // results is now an array of stats for each file
  24311. * });
  24312. */
  24313. var map = doParallel(_asyncMap);
  24314. /**
  24315. * Applies the provided arguments to each function in the array, calling
  24316. * `callback` after all functions have completed. If you only provide the first
  24317. * argument, `fns`, then it will return a function which lets you pass in the
  24318. * arguments as if it were a single function call. If more arguments are
  24319. * provided, `callback` is required while `args` is still optional.
  24320. *
  24321. * @name applyEach
  24322. * @static
  24323. * @memberOf module:ControlFlow
  24324. * @method
  24325. * @category Control Flow
  24326. * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s
  24327. * to all call with the same arguments
  24328. * @param {...*} [args] - any number of separate arguments to pass to the
  24329. * function.
  24330. * @param {Function} [callback] - the final argument should be the callback,
  24331. * called when all functions have completed processing.
  24332. * @returns {Function} - If only the first argument, `fns`, is provided, it will
  24333. * return a function which lets you pass in the arguments as if it were a single
  24334. * function call. The signature is `(..args, callback)`. If invoked with any
  24335. * arguments, `callback` is required.
  24336. * @example
  24337. *
  24338. * async.applyEach([enableSearch, updateSchema], 'bucket', callback);
  24339. *
  24340. * // partial application example:
  24341. * async.each(
  24342. * buckets,
  24343. * async.applyEach([enableSearch, updateSchema]),
  24344. * callback
  24345. * );
  24346. */
  24347. var applyEach = applyEach$1(map);
  24348. function doParallelLimit(fn) {
  24349. return function (obj, limit, iteratee, callback) {
  24350. return fn(_eachOfLimit(limit), obj, wrapAsync(iteratee), callback);
  24351. };
  24352. }
  24353. /**
  24354. * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time.
  24355. *
  24356. * @name mapLimit
  24357. * @static
  24358. * @memberOf module:Collections
  24359. * @method
  24360. * @see [async.map]{@link module:Collections.map}
  24361. * @category Collection
  24362. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  24363. * @param {number} limit - The maximum number of async operations at a time.
  24364. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  24365. * `coll`.
  24366. * The iteratee should complete with the transformed item.
  24367. * Invoked with (item, callback).
  24368. * @param {Function} [callback] - A callback which is called when all `iteratee`
  24369. * functions have finished, or an error occurs. Results is an array of the
  24370. * transformed items from the `coll`. Invoked with (err, results).
  24371. */
  24372. var mapLimit = doParallelLimit(_asyncMap);
  24373. /**
  24374. * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time.
  24375. *
  24376. * @name mapSeries
  24377. * @static
  24378. * @memberOf module:Collections
  24379. * @method
  24380. * @see [async.map]{@link module:Collections.map}
  24381. * @category Collection
  24382. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  24383. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  24384. * `coll`.
  24385. * The iteratee should complete with the transformed item.
  24386. * Invoked with (item, callback).
  24387. * @param {Function} [callback] - A callback which is called when all `iteratee`
  24388. * functions have finished, or an error occurs. Results is an array of the
  24389. * transformed items from the `coll`. Invoked with (err, results).
  24390. */
  24391. var mapSeries = doLimit(mapLimit, 1);
  24392. /**
  24393. * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time.
  24394. *
  24395. * @name applyEachSeries
  24396. * @static
  24397. * @memberOf module:ControlFlow
  24398. * @method
  24399. * @see [async.applyEach]{@link module:ControlFlow.applyEach}
  24400. * @category Control Flow
  24401. * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s to all
  24402. * call with the same arguments
  24403. * @param {...*} [args] - any number of separate arguments to pass to the
  24404. * function.
  24405. * @param {Function} [callback] - the final argument should be the callback,
  24406. * called when all functions have completed processing.
  24407. * @returns {Function} - If only the first argument is provided, it will return
  24408. * a function which lets you pass in the arguments as if it were a single
  24409. * function call.
  24410. */
  24411. var applyEachSeries = applyEach$1(mapSeries);
  24412. /**
  24413. * A specialized version of `_.forEach` for arrays without support for
  24414. * iteratee shorthands.
  24415. *
  24416. * @private
  24417. * @param {Array} [array] The array to iterate over.
  24418. * @param {Function} iteratee The function invoked per iteration.
  24419. * @returns {Array} Returns `array`.
  24420. */
  24421. function arrayEach(array, iteratee) {
  24422. var index = -1,
  24423. length = array == null ? 0 : array.length;
  24424. while (++index < length) {
  24425. if (iteratee(array[index], index, array) === false) {
  24426. break;
  24427. }
  24428. }
  24429. return array;
  24430. }
  24431. /**
  24432. * Creates a base function for methods like `_.forIn` and `_.forOwn`.
  24433. *
  24434. * @private
  24435. * @param {boolean} [fromRight] Specify iterating from right to left.
  24436. * @returns {Function} Returns the new base function.
  24437. */
  24438. function createBaseFor(fromRight) {
  24439. return function(object, iteratee, keysFunc) {
  24440. var index = -1,
  24441. iterable = Object(object),
  24442. props = keysFunc(object),
  24443. length = props.length;
  24444. while (length--) {
  24445. var key = props[fromRight ? length : ++index];
  24446. if (iteratee(iterable[key], key, iterable) === false) {
  24447. break;
  24448. }
  24449. }
  24450. return object;
  24451. };
  24452. }
  24453. /**
  24454. * The base implementation of `baseForOwn` which iterates over `object`
  24455. * properties returned by `keysFunc` and invokes `iteratee` for each property.
  24456. * Iteratee functions may exit iteration early by explicitly returning `false`.
  24457. *
  24458. * @private
  24459. * @param {Object} object The object to iterate over.
  24460. * @param {Function} iteratee The function invoked per iteration.
  24461. * @param {Function} keysFunc The function to get the keys of `object`.
  24462. * @returns {Object} Returns `object`.
  24463. */
  24464. var baseFor = createBaseFor();
  24465. /**
  24466. * The base implementation of `_.forOwn` without support for iteratee shorthands.
  24467. *
  24468. * @private
  24469. * @param {Object} object The object to iterate over.
  24470. * @param {Function} iteratee The function invoked per iteration.
  24471. * @returns {Object} Returns `object`.
  24472. */
  24473. function baseForOwn(object, iteratee) {
  24474. return object && baseFor(object, iteratee, keys);
  24475. }
  24476. /**
  24477. * The base implementation of `_.findIndex` and `_.findLastIndex` without
  24478. * support for iteratee shorthands.
  24479. *
  24480. * @private
  24481. * @param {Array} array The array to inspect.
  24482. * @param {Function} predicate The function invoked per iteration.
  24483. * @param {number} fromIndex The index to search from.
  24484. * @param {boolean} [fromRight] Specify iterating from right to left.
  24485. * @returns {number} Returns the index of the matched value, else `-1`.
  24486. */
  24487. function baseFindIndex(array, predicate, fromIndex, fromRight) {
  24488. var length = array.length,
  24489. index = fromIndex + (fromRight ? 1 : -1);
  24490. while ((fromRight ? index-- : ++index < length)) {
  24491. if (predicate(array[index], index, array)) {
  24492. return index;
  24493. }
  24494. }
  24495. return -1;
  24496. }
  24497. /**
  24498. * The base implementation of `_.isNaN` without support for number objects.
  24499. *
  24500. * @private
  24501. * @param {*} value The value to check.
  24502. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
  24503. */
  24504. function baseIsNaN(value) {
  24505. return value !== value;
  24506. }
  24507. /**
  24508. * A specialized version of `_.indexOf` which performs strict equality
  24509. * comparisons of values, i.e. `===`.
  24510. *
  24511. * @private
  24512. * @param {Array} array The array to inspect.
  24513. * @param {*} value The value to search for.
  24514. * @param {number} fromIndex The index to search from.
  24515. * @returns {number} Returns the index of the matched value, else `-1`.
  24516. */
  24517. function strictIndexOf(array, value, fromIndex) {
  24518. var index = fromIndex - 1,
  24519. length = array.length;
  24520. while (++index < length) {
  24521. if (array[index] === value) {
  24522. return index;
  24523. }
  24524. }
  24525. return -1;
  24526. }
  24527. /**
  24528. * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
  24529. *
  24530. * @private
  24531. * @param {Array} array The array to inspect.
  24532. * @param {*} value The value to search for.
  24533. * @param {number} fromIndex The index to search from.
  24534. * @returns {number} Returns the index of the matched value, else `-1`.
  24535. */
  24536. function baseIndexOf(array, value, fromIndex) {
  24537. return value === value
  24538. ? strictIndexOf(array, value, fromIndex)
  24539. : baseFindIndex(array, baseIsNaN, fromIndex);
  24540. }
  24541. /**
  24542. * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on
  24543. * their requirements. Each function can optionally depend on other functions
  24544. * being completed first, and each function is run as soon as its requirements
  24545. * are satisfied.
  24546. *
  24547. * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence
  24548. * will stop. Further tasks will not execute (so any other functions depending
  24549. * on it will not run), and the main `callback` is immediately called with the
  24550. * error.
  24551. *
  24552. * {@link AsyncFunction}s also receive an object containing the results of functions which
  24553. * have completed so far as the first argument, if they have dependencies. If a
  24554. * task function has no dependencies, it will only be passed a callback.
  24555. *
  24556. * @name auto
  24557. * @static
  24558. * @memberOf module:ControlFlow
  24559. * @method
  24560. * @category Control Flow
  24561. * @param {Object} tasks - An object. Each of its properties is either a
  24562. * function or an array of requirements, with the {@link AsyncFunction} itself the last item
  24563. * in the array. The object's key of a property serves as the name of the task
  24564. * defined by that property, i.e. can be used when specifying requirements for
  24565. * other tasks. The function receives one or two arguments:
  24566. * * a `results` object, containing the results of the previously executed
  24567. * functions, only passed if the task has any dependencies,
  24568. * * a `callback(err, result)` function, which must be called when finished,
  24569. * passing an `error` (which can be `null`) and the result of the function's
  24570. * execution.
  24571. * @param {number} [concurrency=Infinity] - An optional `integer` for
  24572. * determining the maximum number of tasks that can be run in parallel. By
  24573. * default, as many as possible.
  24574. * @param {Function} [callback] - An optional callback which is called when all
  24575. * the tasks have been completed. It receives the `err` argument if any `tasks`
  24576. * pass an error to their callback. Results are always returned; however, if an
  24577. * error occurs, no further `tasks` will be performed, and the results object
  24578. * will only contain partial results. Invoked with (err, results).
  24579. * @returns undefined
  24580. * @example
  24581. *
  24582. * async.auto({
  24583. * // this function will just be passed a callback
  24584. * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'),
  24585. * showData: ['readData', function(results, cb) {
  24586. * // results.readData is the file's contents
  24587. * // ...
  24588. * }]
  24589. * }, callback);
  24590. *
  24591. * async.auto({
  24592. * get_data: function(callback) {
  24593. * console.log('in get_data');
  24594. * // async code to get some data
  24595. * callback(null, 'data', 'converted to array');
  24596. * },
  24597. * make_folder: function(callback) {
  24598. * console.log('in make_folder');
  24599. * // async code to create a directory to store a file in
  24600. * // this is run at the same time as getting the data
  24601. * callback(null, 'folder');
  24602. * },
  24603. * write_file: ['get_data', 'make_folder', function(results, callback) {
  24604. * console.log('in write_file', JSON.stringify(results));
  24605. * // once there is some data and the directory exists,
  24606. * // write the data to a file in the directory
  24607. * callback(null, 'filename');
  24608. * }],
  24609. * email_link: ['write_file', function(results, callback) {
  24610. * console.log('in email_link', JSON.stringify(results));
  24611. * // once the file is written let's email a link to it...
  24612. * // results.write_file contains the filename returned by write_file.
  24613. * callback(null, {'file':results.write_file, 'email':'[email protected]'});
  24614. * }]
  24615. * }, function(err, results) {
  24616. * console.log('err = ', err);
  24617. * console.log('results = ', results);
  24618. * });
  24619. */
  24620. var auto = function (tasks, concurrency, callback) {
  24621. if (typeof concurrency === 'function') {
  24622. // concurrency is optional, shift the args.
  24623. callback = concurrency;
  24624. concurrency = null;
  24625. }
  24626. callback = once(callback || noop);
  24627. var keys$$1 = keys(tasks);
  24628. var numTasks = keys$$1.length;
  24629. if (!numTasks) {
  24630. return callback(null);
  24631. }
  24632. if (!concurrency) {
  24633. concurrency = numTasks;
  24634. }
  24635. var results = {};
  24636. var runningTasks = 0;
  24637. var hasError = false;
  24638. var listeners = Object.create(null);
  24639. var readyTasks = [];
  24640. // for cycle detection:
  24641. var readyToCheck = []; // tasks that have been identified as reachable
  24642. // without the possibility of returning to an ancestor task
  24643. var uncheckedDependencies = {};
  24644. baseForOwn(tasks, function (task, key) {
  24645. if (!isArray(task)) {
  24646. // no dependencies
  24647. enqueueTask(key, [task]);
  24648. readyToCheck.push(key);
  24649. return;
  24650. }
  24651. var dependencies = task.slice(0, task.length - 1);
  24652. var remainingDependencies = dependencies.length;
  24653. if (remainingDependencies === 0) {
  24654. enqueueTask(key, task);
  24655. readyToCheck.push(key);
  24656. return;
  24657. }
  24658. uncheckedDependencies[key] = remainingDependencies;
  24659. arrayEach(dependencies, function (dependencyName) {
  24660. if (!tasks[dependencyName]) {
  24661. throw new Error('async.auto task `' + key +
  24662. '` has a non-existent dependency `' +
  24663. dependencyName + '` in ' +
  24664. dependencies.join(', '));
  24665. }
  24666. addListener(dependencyName, function () {
  24667. remainingDependencies--;
  24668. if (remainingDependencies === 0) {
  24669. enqueueTask(key, task);
  24670. }
  24671. });
  24672. });
  24673. });
  24674. checkForDeadlocks();
  24675. processQueue();
  24676. function enqueueTask(key, task) {
  24677. readyTasks.push(function () {
  24678. runTask(key, task);
  24679. });
  24680. }
  24681. function processQueue() {
  24682. if (readyTasks.length === 0 && runningTasks === 0) {
  24683. return callback(null, results);
  24684. }
  24685. while(readyTasks.length && runningTasks < concurrency) {
  24686. var run = readyTasks.shift();
  24687. run();
  24688. }
  24689. }
  24690. function addListener(taskName, fn) {
  24691. var taskListeners = listeners[taskName];
  24692. if (!taskListeners) {
  24693. taskListeners = listeners[taskName] = [];
  24694. }
  24695. taskListeners.push(fn);
  24696. }
  24697. function taskComplete(taskName) {
  24698. var taskListeners = listeners[taskName] || [];
  24699. arrayEach(taskListeners, function (fn) {
  24700. fn();
  24701. });
  24702. processQueue();
  24703. }
  24704. function runTask(key, task) {
  24705. if (hasError) return;
  24706. var taskCallback = onlyOnce(function(err, result) {
  24707. runningTasks--;
  24708. if (arguments.length > 2) {
  24709. result = slice(arguments, 1);
  24710. }
  24711. if (err) {
  24712. var safeResults = {};
  24713. baseForOwn(results, function(val, rkey) {
  24714. safeResults[rkey] = val;
  24715. });
  24716. safeResults[key] = result;
  24717. hasError = true;
  24718. listeners = Object.create(null);
  24719. callback(err, safeResults);
  24720. } else {
  24721. results[key] = result;
  24722. taskComplete(key);
  24723. }
  24724. });
  24725. runningTasks++;
  24726. var taskFn = wrapAsync(task[task.length - 1]);
  24727. if (task.length > 1) {
  24728. taskFn(results, taskCallback);
  24729. } else {
  24730. taskFn(taskCallback);
  24731. }
  24732. }
  24733. function checkForDeadlocks() {
  24734. // Kahn's algorithm
  24735. // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm
  24736. // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html
  24737. var currentTask;
  24738. var counter = 0;
  24739. while (readyToCheck.length) {
  24740. currentTask = readyToCheck.pop();
  24741. counter++;
  24742. arrayEach(getDependents(currentTask), function (dependent) {
  24743. if (--uncheckedDependencies[dependent] === 0) {
  24744. readyToCheck.push(dependent);
  24745. }
  24746. });
  24747. }
  24748. if (counter !== numTasks) {
  24749. throw new Error(
  24750. 'async.auto cannot execute tasks due to a recursive dependency'
  24751. );
  24752. }
  24753. }
  24754. function getDependents(taskName) {
  24755. var result = [];
  24756. baseForOwn(tasks, function (task, key) {
  24757. if (isArray(task) && baseIndexOf(task, taskName, 0) >= 0) {
  24758. result.push(key);
  24759. }
  24760. });
  24761. return result;
  24762. }
  24763. };
  24764. /**
  24765. * A specialized version of `_.map` for arrays without support for iteratee
  24766. * shorthands.
  24767. *
  24768. * @private
  24769. * @param {Array} [array] The array to iterate over.
  24770. * @param {Function} iteratee The function invoked per iteration.
  24771. * @returns {Array} Returns the new mapped array.
  24772. */
  24773. function arrayMap(array, iteratee) {
  24774. var index = -1,
  24775. length = array == null ? 0 : array.length,
  24776. result = Array(length);
  24777. while (++index < length) {
  24778. result[index] = iteratee(array[index], index, array);
  24779. }
  24780. return result;
  24781. }
  24782. /** `Object#toString` result references. */
  24783. var symbolTag = '[object Symbol]';
  24784. /**
  24785. * Checks if `value` is classified as a `Symbol` primitive or object.
  24786. *
  24787. * @static
  24788. * @memberOf _
  24789. * @since 4.0.0
  24790. * @category Lang
  24791. * @param {*} value The value to check.
  24792. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  24793. * @example
  24794. *
  24795. * _.isSymbol(Symbol.iterator);
  24796. * // => true
  24797. *
  24798. * _.isSymbol('abc');
  24799. * // => false
  24800. */
  24801. function isSymbol(value) {
  24802. return typeof value == 'symbol' ||
  24803. (isObjectLike(value) && baseGetTag(value) == symbolTag);
  24804. }
  24805. /** Used as references for various `Number` constants. */
  24806. var INFINITY = 1 / 0;
  24807. /** Used to convert symbols to primitives and strings. */
  24808. var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined;
  24809. var symbolToString = symbolProto ? symbolProto.toString : undefined;
  24810. /**
  24811. * The base implementation of `_.toString` which doesn't convert nullish
  24812. * values to empty strings.
  24813. *
  24814. * @private
  24815. * @param {*} value The value to process.
  24816. * @returns {string} Returns the string.
  24817. */
  24818. function baseToString(value) {
  24819. // Exit early for strings to avoid a performance hit in some environments.
  24820. if (typeof value == 'string') {
  24821. return value;
  24822. }
  24823. if (isArray(value)) {
  24824. // Recursively convert values (susceptible to call stack limits).
  24825. return arrayMap(value, baseToString) + '';
  24826. }
  24827. if (isSymbol(value)) {
  24828. return symbolToString ? symbolToString.call(value) : '';
  24829. }
  24830. var result = (value + '');
  24831. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  24832. }
  24833. /**
  24834. * The base implementation of `_.slice` without an iteratee call guard.
  24835. *
  24836. * @private
  24837. * @param {Array} array The array to slice.
  24838. * @param {number} [start=0] The start position.
  24839. * @param {number} [end=array.length] The end position.
  24840. * @returns {Array} Returns the slice of `array`.
  24841. */
  24842. function baseSlice(array, start, end) {
  24843. var index = -1,
  24844. length = array.length;
  24845. if (start < 0) {
  24846. start = -start > length ? 0 : (length + start);
  24847. }
  24848. end = end > length ? length : end;
  24849. if (end < 0) {
  24850. end += length;
  24851. }
  24852. length = start > end ? 0 : ((end - start) >>> 0);
  24853. start >>>= 0;
  24854. var result = Array(length);
  24855. while (++index < length) {
  24856. result[index] = array[index + start];
  24857. }
  24858. return result;
  24859. }
  24860. /**
  24861. * Casts `array` to a slice if it's needed.
  24862. *
  24863. * @private
  24864. * @param {Array} array The array to inspect.
  24865. * @param {number} start The start position.
  24866. * @param {number} [end=array.length] The end position.
  24867. * @returns {Array} Returns the cast slice.
  24868. */
  24869. function castSlice(array, start, end) {
  24870. var length = array.length;
  24871. end = end === undefined ? length : end;
  24872. return (!start && end >= length) ? array : baseSlice(array, start, end);
  24873. }
  24874. /**
  24875. * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
  24876. * that is not found in the character symbols.
  24877. *
  24878. * @private
  24879. * @param {Array} strSymbols The string symbols to inspect.
  24880. * @param {Array} chrSymbols The character symbols to find.
  24881. * @returns {number} Returns the index of the last unmatched string symbol.
  24882. */
  24883. function charsEndIndex(strSymbols, chrSymbols) {
  24884. var index = strSymbols.length;
  24885. while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
  24886. return index;
  24887. }
  24888. /**
  24889. * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
  24890. * that is not found in the character symbols.
  24891. *
  24892. * @private
  24893. * @param {Array} strSymbols The string symbols to inspect.
  24894. * @param {Array} chrSymbols The character symbols to find.
  24895. * @returns {number} Returns the index of the first unmatched string symbol.
  24896. */
  24897. function charsStartIndex(strSymbols, chrSymbols) {
  24898. var index = -1,
  24899. length = strSymbols.length;
  24900. while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
  24901. return index;
  24902. }
  24903. /**
  24904. * Converts an ASCII `string` to an array.
  24905. *
  24906. * @private
  24907. * @param {string} string The string to convert.
  24908. * @returns {Array} Returns the converted array.
  24909. */
  24910. function asciiToArray(string) {
  24911. return string.split('');
  24912. }
  24913. /** Used to compose unicode character classes. */
  24914. var rsAstralRange = '\\ud800-\\udfff';
  24915. var rsComboMarksRange = '\\u0300-\\u036f';
  24916. var reComboHalfMarksRange = '\\ufe20-\\ufe2f';
  24917. var rsComboSymbolsRange = '\\u20d0-\\u20ff';
  24918. var rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange;
  24919. var rsVarRange = '\\ufe0e\\ufe0f';
  24920. /** Used to compose unicode capture groups. */
  24921. var rsZWJ = '\\u200d';
  24922. /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
  24923. var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
  24924. /**
  24925. * Checks if `string` contains Unicode symbols.
  24926. *
  24927. * @private
  24928. * @param {string} string The string to inspect.
  24929. * @returns {boolean} Returns `true` if a symbol is found, else `false`.
  24930. */
  24931. function hasUnicode(string) {
  24932. return reHasUnicode.test(string);
  24933. }
  24934. /** Used to compose unicode character classes. */
  24935. var rsAstralRange$1 = '\\ud800-\\udfff';
  24936. var rsComboMarksRange$1 = '\\u0300-\\u036f';
  24937. var reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f';
  24938. var rsComboSymbolsRange$1 = '\\u20d0-\\u20ff';
  24939. var rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1;
  24940. var rsVarRange$1 = '\\ufe0e\\ufe0f';
  24941. /** Used to compose unicode capture groups. */
  24942. var rsAstral = '[' + rsAstralRange$1 + ']';
  24943. var rsCombo = '[' + rsComboRange$1 + ']';
  24944. var rsFitz = '\\ud83c[\\udffb-\\udfff]';
  24945. var rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')';
  24946. var rsNonAstral = '[^' + rsAstralRange$1 + ']';
  24947. var rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}';
  24948. var rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]';
  24949. var rsZWJ$1 = '\\u200d';
  24950. /** Used to compose unicode regexes. */
  24951. var reOptMod = rsModifier + '?';
  24952. var rsOptVar = '[' + rsVarRange$1 + ']?';
  24953. var rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*';
  24954. var rsSeq = rsOptVar + reOptMod + rsOptJoin;
  24955. var rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
  24956. /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
  24957. var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
  24958. /**
  24959. * Converts a Unicode `string` to an array.
  24960. *
  24961. * @private
  24962. * @param {string} string The string to convert.
  24963. * @returns {Array} Returns the converted array.
  24964. */
  24965. function unicodeToArray(string) {
  24966. return string.match(reUnicode) || [];
  24967. }
  24968. /**
  24969. * Converts `string` to an array.
  24970. *
  24971. * @private
  24972. * @param {string} string The string to convert.
  24973. * @returns {Array} Returns the converted array.
  24974. */
  24975. function stringToArray(string) {
  24976. return hasUnicode(string)
  24977. ? unicodeToArray(string)
  24978. : asciiToArray(string);
  24979. }
  24980. /**
  24981. * Converts `value` to a string. An empty string is returned for `null`
  24982. * and `undefined` values. The sign of `-0` is preserved.
  24983. *
  24984. * @static
  24985. * @memberOf _
  24986. * @since 4.0.0
  24987. * @category Lang
  24988. * @param {*} value The value to convert.
  24989. * @returns {string} Returns the converted string.
  24990. * @example
  24991. *
  24992. * _.toString(null);
  24993. * // => ''
  24994. *
  24995. * _.toString(-0);
  24996. * // => '-0'
  24997. *
  24998. * _.toString([1, 2, 3]);
  24999. * // => '1,2,3'
  25000. */
  25001. function toString(value) {
  25002. return value == null ? '' : baseToString(value);
  25003. }
  25004. /** Used to match leading and trailing whitespace. */
  25005. var reTrim = /^\s+|\s+$/g;
  25006. /**
  25007. * Removes leading and trailing whitespace or specified characters from `string`.
  25008. *
  25009. * @static
  25010. * @memberOf _
  25011. * @since 3.0.0
  25012. * @category String
  25013. * @param {string} [string=''] The string to trim.
  25014. * @param {string} [chars=whitespace] The characters to trim.
  25015. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  25016. * @returns {string} Returns the trimmed string.
  25017. * @example
  25018. *
  25019. * _.trim(' abc ');
  25020. * // => 'abc'
  25021. *
  25022. * _.trim('-_-abc-_-', '_-');
  25023. * // => 'abc'
  25024. *
  25025. * _.map([' foo ', ' bar '], _.trim);
  25026. * // => ['foo', 'bar']
  25027. */
  25028. function trim(string, chars, guard) {
  25029. string = toString(string);
  25030. if (string && (guard || chars === undefined)) {
  25031. return string.replace(reTrim, '');
  25032. }
  25033. if (!string || !(chars = baseToString(chars))) {
  25034. return string;
  25035. }
  25036. var strSymbols = stringToArray(string),
  25037. chrSymbols = stringToArray(chars),
  25038. start = charsStartIndex(strSymbols, chrSymbols),
  25039. end = charsEndIndex(strSymbols, chrSymbols) + 1;
  25040. return castSlice(strSymbols, start, end).join('');
  25041. }
  25042. var FN_ARGS = /^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m;
  25043. var FN_ARG_SPLIT = /,/;
  25044. var FN_ARG = /(=.+)?(\s*)$/;
  25045. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  25046. function parseParams(func) {
  25047. func = func.toString().replace(STRIP_COMMENTS, '');
  25048. func = func.match(FN_ARGS)[2].replace(' ', '');
  25049. func = func ? func.split(FN_ARG_SPLIT) : [];
  25050. func = func.map(function (arg){
  25051. return trim(arg.replace(FN_ARG, ''));
  25052. });
  25053. return func;
  25054. }
  25055. /**
  25056. * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent
  25057. * tasks are specified as parameters to the function, after the usual callback
  25058. * parameter, with the parameter names matching the names of the tasks it
  25059. * depends on. This can provide even more readable task graphs which can be
  25060. * easier to maintain.
  25061. *
  25062. * If a final callback is specified, the task results are similarly injected,
  25063. * specified as named parameters after the initial error parameter.
  25064. *
  25065. * The autoInject function is purely syntactic sugar and its semantics are
  25066. * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}.
  25067. *
  25068. * @name autoInject
  25069. * @static
  25070. * @memberOf module:ControlFlow
  25071. * @method
  25072. * @see [async.auto]{@link module:ControlFlow.auto}
  25073. * @category Control Flow
  25074. * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of
  25075. * the form 'func([dependencies...], callback). The object's key of a property
  25076. * serves as the name of the task defined by that property, i.e. can be used
  25077. * when specifying requirements for other tasks.
  25078. * * The `callback` parameter is a `callback(err, result)` which must be called
  25079. * when finished, passing an `error` (which can be `null`) and the result of
  25080. * the function's execution. The remaining parameters name other tasks on
  25081. * which the task is dependent, and the results from those tasks are the
  25082. * arguments of those parameters.
  25083. * @param {Function} [callback] - An optional callback which is called when all
  25084. * the tasks have been completed. It receives the `err` argument if any `tasks`
  25085. * pass an error to their callback, and a `results` object with any completed
  25086. * task results, similar to `auto`.
  25087. * @example
  25088. *
  25089. * // The example from `auto` can be rewritten as follows:
  25090. * async.autoInject({
  25091. * get_data: function(callback) {
  25092. * // async code to get some data
  25093. * callback(null, 'data', 'converted to array');
  25094. * },
  25095. * make_folder: function(callback) {
  25096. * // async code to create a directory to store a file in
  25097. * // this is run at the same time as getting the data
  25098. * callback(null, 'folder');
  25099. * },
  25100. * write_file: function(get_data, make_folder, callback) {
  25101. * // once there is some data and the directory exists,
  25102. * // write the data to a file in the directory
  25103. * callback(null, 'filename');
  25104. * },
  25105. * email_link: function(write_file, callback) {
  25106. * // once the file is written let's email a link to it...
  25107. * // write_file contains the filename returned by write_file.
  25108. * callback(null, {'file':write_file, 'email':'[email protected]'});
  25109. * }
  25110. * }, function(err, results) {
  25111. * console.log('err = ', err);
  25112. * console.log('email_link = ', results.email_link);
  25113. * });
  25114. *
  25115. * // If you are using a JS minifier that mangles parameter names, `autoInject`
  25116. * // will not work with plain functions, since the parameter names will be
  25117. * // collapsed to a single letter identifier. To work around this, you can
  25118. * // explicitly specify the names of the parameters your task function needs
  25119. * // in an array, similar to Angular.js dependency injection.
  25120. *
  25121. * // This still has an advantage over plain `auto`, since the results a task
  25122. * // depends on are still spread into arguments.
  25123. * async.autoInject({
  25124. * //...
  25125. * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) {
  25126. * callback(null, 'filename');
  25127. * }],
  25128. * email_link: ['write_file', function(write_file, callback) {
  25129. * callback(null, {'file':write_file, 'email':'[email protected]'});
  25130. * }]
  25131. * //...
  25132. * }, function(err, results) {
  25133. * console.log('err = ', err);
  25134. * console.log('email_link = ', results.email_link);
  25135. * });
  25136. */
  25137. function autoInject(tasks, callback) {
  25138. var newTasks = {};
  25139. baseForOwn(tasks, function (taskFn, key) {
  25140. var params;
  25141. var fnIsAsync = isAsync(taskFn);
  25142. var hasNoDeps =
  25143. (!fnIsAsync && taskFn.length === 1) ||
  25144. (fnIsAsync && taskFn.length === 0);
  25145. if (isArray(taskFn)) {
  25146. params = taskFn.slice(0, -1);
  25147. taskFn = taskFn[taskFn.length - 1];
  25148. newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn);
  25149. } else if (hasNoDeps) {
  25150. // no dependencies, use the function as-is
  25151. newTasks[key] = taskFn;
  25152. } else {
  25153. params = parseParams(taskFn);
  25154. if (taskFn.length === 0 && !fnIsAsync && params.length === 0) {
  25155. throw new Error("autoInject task functions require explicit parameters.");
  25156. }
  25157. // remove callback param
  25158. if (!fnIsAsync) params.pop();
  25159. newTasks[key] = params.concat(newTask);
  25160. }
  25161. function newTask(results, taskCb) {
  25162. var newArgs = arrayMap(params, function (name) {
  25163. return results[name];
  25164. });
  25165. newArgs.push(taskCb);
  25166. wrapAsync(taskFn).apply(null, newArgs);
  25167. }
  25168. });
  25169. auto(newTasks, callback);
  25170. }
  25171. // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation
  25172. // used for queues. This implementation assumes that the node provided by the user can be modified
  25173. // to adjust the next and last properties. We implement only the minimal functionality
  25174. // for queue support.
  25175. function DLL() {
  25176. this.head = this.tail = null;
  25177. this.length = 0;
  25178. }
  25179. function setInitial(dll, node) {
  25180. dll.length = 1;
  25181. dll.head = dll.tail = node;
  25182. }
  25183. DLL.prototype.removeLink = function(node) {
  25184. if (node.prev) node.prev.next = node.next;
  25185. else this.head = node.next;
  25186. if (node.next) node.next.prev = node.prev;
  25187. else this.tail = node.prev;
  25188. node.prev = node.next = null;
  25189. this.length -= 1;
  25190. return node;
  25191. };
  25192. DLL.prototype.empty = function () {
  25193. while(this.head) this.shift();
  25194. return this;
  25195. };
  25196. DLL.prototype.insertAfter = function(node, newNode) {
  25197. newNode.prev = node;
  25198. newNode.next = node.next;
  25199. if (node.next) node.next.prev = newNode;
  25200. else this.tail = newNode;
  25201. node.next = newNode;
  25202. this.length += 1;
  25203. };
  25204. DLL.prototype.insertBefore = function(node, newNode) {
  25205. newNode.prev = node.prev;
  25206. newNode.next = node;
  25207. if (node.prev) node.prev.next = newNode;
  25208. else this.head = newNode;
  25209. node.prev = newNode;
  25210. this.length += 1;
  25211. };
  25212. DLL.prototype.unshift = function(node) {
  25213. if (this.head) this.insertBefore(this.head, node);
  25214. else setInitial(this, node);
  25215. };
  25216. DLL.prototype.push = function(node) {
  25217. if (this.tail) this.insertAfter(this.tail, node);
  25218. else setInitial(this, node);
  25219. };
  25220. DLL.prototype.shift = function() {
  25221. return this.head && this.removeLink(this.head);
  25222. };
  25223. DLL.prototype.pop = function() {
  25224. return this.tail && this.removeLink(this.tail);
  25225. };
  25226. DLL.prototype.toArray = function () {
  25227. var arr = Array(this.length);
  25228. var curr = this.head;
  25229. for(var idx = 0; idx < this.length; idx++) {
  25230. arr[idx] = curr.data;
  25231. curr = curr.next;
  25232. }
  25233. return arr;
  25234. };
  25235. DLL.prototype.remove = function (testFn) {
  25236. var curr = this.head;
  25237. while(!!curr) {
  25238. var next = curr.next;
  25239. if (testFn(curr)) {
  25240. this.removeLink(curr);
  25241. }
  25242. curr = next;
  25243. }
  25244. return this;
  25245. };
  25246. function queue(worker, concurrency, payload) {
  25247. if (concurrency == null) {
  25248. concurrency = 1;
  25249. }
  25250. else if(concurrency === 0) {
  25251. throw new Error('Concurrency must not be zero');
  25252. }
  25253. var _worker = wrapAsync(worker);
  25254. var numRunning = 0;
  25255. var workersList = [];
  25256. var processingScheduled = false;
  25257. function _insert(data, insertAtFront, callback) {
  25258. if (callback != null && typeof callback !== 'function') {
  25259. throw new Error('task callback must be a function');
  25260. }
  25261. q.started = true;
  25262. if (!isArray(data)) {
  25263. data = [data];
  25264. }
  25265. if (data.length === 0 && q.idle()) {
  25266. // call drain immediately if there are no tasks
  25267. return setImmediate$1(function() {
  25268. q.drain();
  25269. });
  25270. }
  25271. for (var i = 0, l = data.length; i < l; i++) {
  25272. var item = {
  25273. data: data[i],
  25274. callback: callback || noop
  25275. };
  25276. if (insertAtFront) {
  25277. q._tasks.unshift(item);
  25278. } else {
  25279. q._tasks.push(item);
  25280. }
  25281. }
  25282. if (!processingScheduled) {
  25283. processingScheduled = true;
  25284. setImmediate$1(function() {
  25285. processingScheduled = false;
  25286. q.process();
  25287. });
  25288. }
  25289. }
  25290. function _next(tasks) {
  25291. return function(err){
  25292. numRunning -= 1;
  25293. for (var i = 0, l = tasks.length; i < l; i++) {
  25294. var task = tasks[i];
  25295. var index = baseIndexOf(workersList, task, 0);
  25296. if (index === 0) {
  25297. workersList.shift();
  25298. } else if (index > 0) {
  25299. workersList.splice(index, 1);
  25300. }
  25301. task.callback.apply(task, arguments);
  25302. if (err != null) {
  25303. q.error(err, task.data);
  25304. }
  25305. }
  25306. if (numRunning <= (q.concurrency - q.buffer) ) {
  25307. q.unsaturated();
  25308. }
  25309. if (q.idle()) {
  25310. q.drain();
  25311. }
  25312. q.process();
  25313. };
  25314. }
  25315. var isProcessing = false;
  25316. var q = {
  25317. _tasks: new DLL(),
  25318. concurrency: concurrency,
  25319. payload: payload,
  25320. saturated: noop,
  25321. unsaturated:noop,
  25322. buffer: concurrency / 4,
  25323. empty: noop,
  25324. drain: noop,
  25325. error: noop,
  25326. started: false,
  25327. paused: false,
  25328. push: function (data, callback) {
  25329. _insert(data, false, callback);
  25330. },
  25331. kill: function () {
  25332. q.drain = noop;
  25333. q._tasks.empty();
  25334. },
  25335. unshift: function (data, callback) {
  25336. _insert(data, true, callback);
  25337. },
  25338. remove: function (testFn) {
  25339. q._tasks.remove(testFn);
  25340. },
  25341. process: function () {
  25342. // Avoid trying to start too many processing operations. This can occur
  25343. // when callbacks resolve synchronously (#1267).
  25344. if (isProcessing) {
  25345. return;
  25346. }
  25347. isProcessing = true;
  25348. while(!q.paused && numRunning < q.concurrency && q._tasks.length){
  25349. var tasks = [], data = [];
  25350. var l = q._tasks.length;
  25351. if (q.payload) l = Math.min(l, q.payload);
  25352. for (var i = 0; i < l; i++) {
  25353. var node = q._tasks.shift();
  25354. tasks.push(node);
  25355. workersList.push(node);
  25356. data.push(node.data);
  25357. }
  25358. numRunning += 1;
  25359. if (q._tasks.length === 0) {
  25360. q.empty();
  25361. }
  25362. if (numRunning === q.concurrency) {
  25363. q.saturated();
  25364. }
  25365. var cb = onlyOnce(_next(tasks));
  25366. _worker(data, cb);
  25367. }
  25368. isProcessing = false;
  25369. },
  25370. length: function () {
  25371. return q._tasks.length;
  25372. },
  25373. running: function () {
  25374. return numRunning;
  25375. },
  25376. workersList: function () {
  25377. return workersList;
  25378. },
  25379. idle: function() {
  25380. return q._tasks.length + numRunning === 0;
  25381. },
  25382. pause: function () {
  25383. q.paused = true;
  25384. },
  25385. resume: function () {
  25386. if (q.paused === false) { return; }
  25387. q.paused = false;
  25388. setImmediate$1(q.process);
  25389. }
  25390. };
  25391. return q;
  25392. }
  25393. /**
  25394. * A cargo of tasks for the worker function to complete. Cargo inherits all of
  25395. * the same methods and event callbacks as [`queue`]{@link module:ControlFlow.queue}.
  25396. * @typedef {Object} CargoObject
  25397. * @memberOf module:ControlFlow
  25398. * @property {Function} length - A function returning the number of items
  25399. * waiting to be processed. Invoke like `cargo.length()`.
  25400. * @property {number} payload - An `integer` for determining how many tasks
  25401. * should be process per round. This property can be changed after a `cargo` is
  25402. * created to alter the payload on-the-fly.
  25403. * @property {Function} push - Adds `task` to the `queue`. The callback is
  25404. * called once the `worker` has finished processing the task. Instead of a
  25405. * single task, an array of `tasks` can be submitted. The respective callback is
  25406. * used for every task in the list. Invoke like `cargo.push(task, [callback])`.
  25407. * @property {Function} saturated - A callback that is called when the
  25408. * `queue.length()` hits the concurrency and further tasks will be queued.
  25409. * @property {Function} empty - A callback that is called when the last item
  25410. * from the `queue` is given to a `worker`.
  25411. * @property {Function} drain - A callback that is called when the last item
  25412. * from the `queue` has returned from the `worker`.
  25413. * @property {Function} idle - a function returning false if there are items
  25414. * waiting or being processed, or true if not. Invoke like `cargo.idle()`.
  25415. * @property {Function} pause - a function that pauses the processing of tasks
  25416. * until `resume()` is called. Invoke like `cargo.pause()`.
  25417. * @property {Function} resume - a function that resumes the processing of
  25418. * queued tasks when the queue is paused. Invoke like `cargo.resume()`.
  25419. * @property {Function} kill - a function that removes the `drain` callback and
  25420. * empties remaining tasks from the queue forcing it to go idle. Invoke like `cargo.kill()`.
  25421. */
  25422. /**
  25423. * Creates a `cargo` object with the specified payload. Tasks added to the
  25424. * cargo will be processed altogether (up to the `payload` limit). If the
  25425. * `worker` is in progress, the task is queued until it becomes available. Once
  25426. * the `worker` has completed some tasks, each callback of those tasks is
  25427. * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966)
  25428. * for how `cargo` and `queue` work.
  25429. *
  25430. * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers
  25431. * at a time, cargo passes an array of tasks to a single worker, repeating
  25432. * when the worker is finished.
  25433. *
  25434. * @name cargo
  25435. * @static
  25436. * @memberOf module:ControlFlow
  25437. * @method
  25438. * @see [async.queue]{@link module:ControlFlow.queue}
  25439. * @category Control Flow
  25440. * @param {AsyncFunction} worker - An asynchronous function for processing an array
  25441. * of queued tasks. Invoked with `(tasks, callback)`.
  25442. * @param {number} [payload=Infinity] - An optional `integer` for determining
  25443. * how many tasks should be processed per round; if omitted, the default is
  25444. * unlimited.
  25445. * @returns {module:ControlFlow.CargoObject} A cargo object to manage the tasks. Callbacks can
  25446. * attached as certain properties to listen for specific events during the
  25447. * lifecycle of the cargo and inner queue.
  25448. * @example
  25449. *
  25450. * // create a cargo object with payload 2
  25451. * var cargo = async.cargo(function(tasks, callback) {
  25452. * for (var i=0; i<tasks.length; i++) {
  25453. * console.log('hello ' + tasks[i].name);
  25454. * }
  25455. * callback();
  25456. * }, 2);
  25457. *
  25458. * // add some items
  25459. * cargo.push({name: 'foo'}, function(err) {
  25460. * console.log('finished processing foo');
  25461. * });
  25462. * cargo.push({name: 'bar'}, function(err) {
  25463. * console.log('finished processing bar');
  25464. * });
  25465. * cargo.push({name: 'baz'}, function(err) {
  25466. * console.log('finished processing baz');
  25467. * });
  25468. */
  25469. function cargo(worker, payload) {
  25470. return queue(worker, 1, payload);
  25471. }
  25472. /**
  25473. * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.
  25474. *
  25475. * @name eachOfSeries
  25476. * @static
  25477. * @memberOf module:Collections
  25478. * @method
  25479. * @see [async.eachOf]{@link module:Collections.eachOf}
  25480. * @alias forEachOfSeries
  25481. * @category Collection
  25482. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  25483. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  25484. * `coll`.
  25485. * Invoked with (item, key, callback).
  25486. * @param {Function} [callback] - A callback which is called when all `iteratee`
  25487. * functions have finished, or an error occurs. Invoked with (err).
  25488. */
  25489. var eachOfSeries = doLimit(eachOfLimit, 1);
  25490. /**
  25491. * Reduces `coll` into a single value using an async `iteratee` to return each
  25492. * successive step. `memo` is the initial state of the reduction. This function
  25493. * only operates in series.
  25494. *
  25495. * For performance reasons, it may make sense to split a call to this function
  25496. * into a parallel map, and then use the normal `Array.prototype.reduce` on the
  25497. * results. This function is for situations where each step in the reduction
  25498. * needs to be async; if you can get the data before reducing it, then it's
  25499. * probably a good idea to do so.
  25500. *
  25501. * @name reduce
  25502. * @static
  25503. * @memberOf module:Collections
  25504. * @method
  25505. * @alias inject
  25506. * @alias foldl
  25507. * @category Collection
  25508. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  25509. * @param {*} memo - The initial state of the reduction.
  25510. * @param {AsyncFunction} iteratee - A function applied to each item in the
  25511. * array to produce the next step in the reduction.
  25512. * The `iteratee` should complete with the next state of the reduction.
  25513. * If the iteratee complete with an error, the reduction is stopped and the
  25514. * main `callback` is immediately called with the error.
  25515. * Invoked with (memo, item, callback).
  25516. * @param {Function} [callback] - A callback which is called after all the
  25517. * `iteratee` functions have finished. Result is the reduced value. Invoked with
  25518. * (err, result).
  25519. * @example
  25520. *
  25521. * async.reduce([1,2,3], 0, function(memo, item, callback) {
  25522. * // pointless async:
  25523. * process.nextTick(function() {
  25524. * callback(null, memo + item)
  25525. * });
  25526. * }, function(err, result) {
  25527. * // result is now equal to the last value of memo, which is 6
  25528. * });
  25529. */
  25530. function reduce(coll, memo, iteratee, callback) {
  25531. callback = once(callback || noop);
  25532. var _iteratee = wrapAsync(iteratee);
  25533. eachOfSeries(coll, function(x, i, callback) {
  25534. _iteratee(memo, x, function(err, v) {
  25535. memo = v;
  25536. callback(err);
  25537. });
  25538. }, function(err) {
  25539. callback(err, memo);
  25540. });
  25541. }
  25542. /**
  25543. * Version of the compose function that is more natural to read. Each function
  25544. * consumes the return value of the previous function. It is the equivalent of
  25545. * [compose]{@link module:ControlFlow.compose} with the arguments reversed.
  25546. *
  25547. * Each function is executed with the `this` binding of the composed function.
  25548. *
  25549. * @name seq
  25550. * @static
  25551. * @memberOf module:ControlFlow
  25552. * @method
  25553. * @see [async.compose]{@link module:ControlFlow.compose}
  25554. * @category Control Flow
  25555. * @param {...AsyncFunction} functions - the asynchronous functions to compose
  25556. * @returns {Function} a function that composes the `functions` in order
  25557. * @example
  25558. *
  25559. * // Requires lodash (or underscore), express3 and dresende's orm2.
  25560. * // Part of an app, that fetches cats of the logged user.
  25561. * // This example uses `seq` function to avoid overnesting and error
  25562. * // handling clutter.
  25563. * app.get('/cats', function(request, response) {
  25564. * var User = request.models.User;
  25565. * async.seq(
  25566. * _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data))
  25567. * function(user, fn) {
  25568. * user.getCats(fn); // 'getCats' has signature (callback(err, data))
  25569. * }
  25570. * )(req.session.user_id, function (err, cats) {
  25571. * if (err) {
  25572. * console.error(err);
  25573. * response.json({ status: 'error', message: err.message });
  25574. * } else {
  25575. * response.json({ status: 'ok', message: 'Cats found', data: cats });
  25576. * }
  25577. * });
  25578. * });
  25579. */
  25580. function seq(/*...functions*/) {
  25581. var _functions = arrayMap(arguments, wrapAsync);
  25582. return function(/*...args*/) {
  25583. var args = slice(arguments);
  25584. var that = this;
  25585. var cb = args[args.length - 1];
  25586. if (typeof cb == 'function') {
  25587. args.pop();
  25588. } else {
  25589. cb = noop;
  25590. }
  25591. reduce(_functions, args, function(newargs, fn, cb) {
  25592. fn.apply(that, newargs.concat(function(err/*, ...nextargs*/) {
  25593. var nextargs = slice(arguments, 1);
  25594. cb(err, nextargs);
  25595. }));
  25596. },
  25597. function(err, results) {
  25598. cb.apply(that, [err].concat(results));
  25599. });
  25600. };
  25601. }
  25602. /**
  25603. * Creates a function which is a composition of the passed asynchronous
  25604. * functions. Each function consumes the return value of the function that
  25605. * follows. Composing functions `f()`, `g()`, and `h()` would produce the result
  25606. * of `f(g(h()))`, only this version uses callbacks to obtain the return values.
  25607. *
  25608. * Each function is executed with the `this` binding of the composed function.
  25609. *
  25610. * @name compose
  25611. * @static
  25612. * @memberOf module:ControlFlow
  25613. * @method
  25614. * @category Control Flow
  25615. * @param {...AsyncFunction} functions - the asynchronous functions to compose
  25616. * @returns {Function} an asynchronous function that is the composed
  25617. * asynchronous `functions`
  25618. * @example
  25619. *
  25620. * function add1(n, callback) {
  25621. * setTimeout(function () {
  25622. * callback(null, n + 1);
  25623. * }, 10);
  25624. * }
  25625. *
  25626. * function mul3(n, callback) {
  25627. * setTimeout(function () {
  25628. * callback(null, n * 3);
  25629. * }, 10);
  25630. * }
  25631. *
  25632. * var add1mul3 = async.compose(mul3, add1);
  25633. * add1mul3(4, function (err, result) {
  25634. * // result now equals 15
  25635. * });
  25636. */
  25637. var compose = function(/*...args*/) {
  25638. return seq.apply(null, slice(arguments).reverse());
  25639. };
  25640. var _concat = Array.prototype.concat;
  25641. /**
  25642. * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time.
  25643. *
  25644. * @name concatLimit
  25645. * @static
  25646. * @memberOf module:Collections
  25647. * @method
  25648. * @see [async.concat]{@link module:Collections.concat}
  25649. * @category Collection
  25650. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  25651. * @param {number} limit - The maximum number of async operations at a time.
  25652. * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,
  25653. * which should use an array as its result. Invoked with (item, callback).
  25654. * @param {Function} [callback] - A callback which is called after all the
  25655. * `iteratee` functions have finished, or an error occurs. Results is an array
  25656. * containing the concatenated results of the `iteratee` function. Invoked with
  25657. * (err, results).
  25658. */
  25659. var concatLimit = function(coll, limit, iteratee, callback) {
  25660. callback = callback || noop;
  25661. var _iteratee = wrapAsync(iteratee);
  25662. mapLimit(coll, limit, function(val, callback) {
  25663. _iteratee(val, function(err /*, ...args*/) {
  25664. if (err) return callback(err);
  25665. return callback(null, slice(arguments, 1));
  25666. });
  25667. }, function(err, mapResults) {
  25668. var result = [];
  25669. for (var i = 0; i < mapResults.length; i++) {
  25670. if (mapResults[i]) {
  25671. result = _concat.apply(result, mapResults[i]);
  25672. }
  25673. }
  25674. return callback(err, result);
  25675. });
  25676. };
  25677. /**
  25678. * Applies `iteratee` to each item in `coll`, concatenating the results. Returns
  25679. * the concatenated list. The `iteratee`s are called in parallel, and the
  25680. * results are concatenated as they return. There is no guarantee that the
  25681. * results array will be returned in the original order of `coll` passed to the
  25682. * `iteratee` function.
  25683. *
  25684. * @name concat
  25685. * @static
  25686. * @memberOf module:Collections
  25687. * @method
  25688. * @category Collection
  25689. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  25690. * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,
  25691. * which should use an array as its result. Invoked with (item, callback).
  25692. * @param {Function} [callback(err)] - A callback which is called after all the
  25693. * `iteratee` functions have finished, or an error occurs. Results is an array
  25694. * containing the concatenated results of the `iteratee` function. Invoked with
  25695. * (err, results).
  25696. * @example
  25697. *
  25698. * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) {
  25699. * // files is now a list of filenames that exist in the 3 directories
  25700. * });
  25701. */
  25702. var concat = doLimit(concatLimit, Infinity);
  25703. /**
  25704. * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time.
  25705. *
  25706. * @name concatSeries
  25707. * @static
  25708. * @memberOf module:Collections
  25709. * @method
  25710. * @see [async.concat]{@link module:Collections.concat}
  25711. * @category Collection
  25712. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  25713. * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`.
  25714. * The iteratee should complete with an array an array of results.
  25715. * Invoked with (item, callback).
  25716. * @param {Function} [callback(err)] - A callback which is called after all the
  25717. * `iteratee` functions have finished, or an error occurs. Results is an array
  25718. * containing the concatenated results of the `iteratee` function. Invoked with
  25719. * (err, results).
  25720. */
  25721. var concatSeries = doLimit(concatLimit, 1);
  25722. /**
  25723. * Returns a function that when called, calls-back with the values provided.
  25724. * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to
  25725. * [`auto`]{@link module:ControlFlow.auto}.
  25726. *
  25727. * @name constant
  25728. * @static
  25729. * @memberOf module:Utils
  25730. * @method
  25731. * @category Util
  25732. * @param {...*} arguments... - Any number of arguments to automatically invoke
  25733. * callback with.
  25734. * @returns {AsyncFunction} Returns a function that when invoked, automatically
  25735. * invokes the callback with the previous given arguments.
  25736. * @example
  25737. *
  25738. * async.waterfall([
  25739. * async.constant(42),
  25740. * function (value, next) {
  25741. * // value === 42
  25742. * },
  25743. * //...
  25744. * ], callback);
  25745. *
  25746. * async.waterfall([
  25747. * async.constant(filename, "utf8"),
  25748. * fs.readFile,
  25749. * function (fileData, next) {
  25750. * //...
  25751. * }
  25752. * //...
  25753. * ], callback);
  25754. *
  25755. * async.auto({
  25756. * hostname: async.constant("https://server.net/"),
  25757. * port: findFreePort,
  25758. * launchServer: ["hostname", "port", function (options, cb) {
  25759. * startServer(options, cb);
  25760. * }],
  25761. * //...
  25762. * }, callback);
  25763. */
  25764. var constant = function(/*...values*/) {
  25765. var values = slice(arguments);
  25766. var args = [null].concat(values);
  25767. return function (/*...ignoredArgs, callback*/) {
  25768. var callback = arguments[arguments.length - 1];
  25769. return callback.apply(this, args);
  25770. };
  25771. };
  25772. /**
  25773. * This method returns the first argument it receives.
  25774. *
  25775. * @static
  25776. * @since 0.1.0
  25777. * @memberOf _
  25778. * @category Util
  25779. * @param {*} value Any value.
  25780. * @returns {*} Returns `value`.
  25781. * @example
  25782. *
  25783. * var object = { 'a': 1 };
  25784. *
  25785. * console.log(_.identity(object) === object);
  25786. * // => true
  25787. */
  25788. function identity(value) {
  25789. return value;
  25790. }
  25791. function _createTester(check, getResult) {
  25792. return function(eachfn, arr, iteratee, cb) {
  25793. cb = cb || noop;
  25794. var testPassed = false;
  25795. var testResult;
  25796. eachfn(arr, function(value, _, callback) {
  25797. iteratee(value, function(err, result) {
  25798. if (err) {
  25799. callback(err);
  25800. } else if (check(result) && !testResult) {
  25801. testPassed = true;
  25802. testResult = getResult(true, value);
  25803. callback(null, breakLoop);
  25804. } else {
  25805. callback();
  25806. }
  25807. });
  25808. }, function(err) {
  25809. if (err) {
  25810. cb(err);
  25811. } else {
  25812. cb(null, testPassed ? testResult : getResult(false));
  25813. }
  25814. });
  25815. };
  25816. }
  25817. function _findGetResult(v, x) {
  25818. return x;
  25819. }
  25820. /**
  25821. * Returns the first value in `coll` that passes an async truth test. The
  25822. * `iteratee` is applied in parallel, meaning the first iteratee to return
  25823. * `true` will fire the detect `callback` with that result. That means the
  25824. * result might not be the first item in the original `coll` (in terms of order)
  25825. * that passes the test.
  25826. * If order within the original `coll` is important, then look at
  25827. * [`detectSeries`]{@link module:Collections.detectSeries}.
  25828. *
  25829. * @name detect
  25830. * @static
  25831. * @memberOf module:Collections
  25832. * @method
  25833. * @alias find
  25834. * @category Collections
  25835. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  25836. * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
  25837. * The iteratee must complete with a boolean value as its result.
  25838. * Invoked with (item, callback).
  25839. * @param {Function} [callback] - A callback which is called as soon as any
  25840. * iteratee returns `true`, or after all the `iteratee` functions have finished.
  25841. * Result will be the first item in the array that passes the truth test
  25842. * (iteratee) or the value `undefined` if none passed. Invoked with
  25843. * (err, result).
  25844. * @example
  25845. *
  25846. * async.detect(['file1','file2','file3'], function(filePath, callback) {
  25847. * fs.access(filePath, function(err) {
  25848. * callback(null, !err)
  25849. * });
  25850. * }, function(err, result) {
  25851. * // result now equals the first file in the list that exists
  25852. * });
  25853. */
  25854. var detect = doParallel(_createTester(identity, _findGetResult));
  25855. /**
  25856. * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a
  25857. * time.
  25858. *
  25859. * @name detectLimit
  25860. * @static
  25861. * @memberOf module:Collections
  25862. * @method
  25863. * @see [async.detect]{@link module:Collections.detect}
  25864. * @alias findLimit
  25865. * @category Collections
  25866. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  25867. * @param {number} limit - The maximum number of async operations at a time.
  25868. * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
  25869. * The iteratee must complete with a boolean value as its result.
  25870. * Invoked with (item, callback).
  25871. * @param {Function} [callback] - A callback which is called as soon as any
  25872. * iteratee returns `true`, or after all the `iteratee` functions have finished.
  25873. * Result will be the first item in the array that passes the truth test
  25874. * (iteratee) or the value `undefined` if none passed. Invoked with
  25875. * (err, result).
  25876. */
  25877. var detectLimit = doParallelLimit(_createTester(identity, _findGetResult));
  25878. /**
  25879. * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time.
  25880. *
  25881. * @name detectSeries
  25882. * @static
  25883. * @memberOf module:Collections
  25884. * @method
  25885. * @see [async.detect]{@link module:Collections.detect}
  25886. * @alias findSeries
  25887. * @category Collections
  25888. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  25889. * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
  25890. * The iteratee must complete with a boolean value as its result.
  25891. * Invoked with (item, callback).
  25892. * @param {Function} [callback] - A callback which is called as soon as any
  25893. * iteratee returns `true`, or after all the `iteratee` functions have finished.
  25894. * Result will be the first item in the array that passes the truth test
  25895. * (iteratee) or the value `undefined` if none passed. Invoked with
  25896. * (err, result).
  25897. */
  25898. var detectSeries = doLimit(detectLimit, 1);
  25899. function consoleFunc(name) {
  25900. return function (fn/*, ...args*/) {
  25901. var args = slice(arguments, 1);
  25902. args.push(function (err/*, ...args*/) {
  25903. var args = slice(arguments, 1);
  25904. if (typeof console === 'object') {
  25905. if (err) {
  25906. if (console.error) {
  25907. console.error(err);
  25908. }
  25909. } else if (console[name]) {
  25910. arrayEach(args, function (x) {
  25911. console[name](x);
  25912. });
  25913. }
  25914. }
  25915. });
  25916. wrapAsync(fn).apply(null, args);
  25917. };
  25918. }
  25919. /**
  25920. * Logs the result of an [`async` function]{@link AsyncFunction} to the
  25921. * `console` using `console.dir` to display the properties of the resulting object.
  25922. * Only works in Node.js or in browsers that support `console.dir` and
  25923. * `console.error` (such as FF and Chrome).
  25924. * If multiple arguments are returned from the async function,
  25925. * `console.dir` is called on each argument in order.
  25926. *
  25927. * @name dir
  25928. * @static
  25929. * @memberOf module:Utils
  25930. * @method
  25931. * @category Util
  25932. * @param {AsyncFunction} function - The function you want to eventually apply
  25933. * all arguments to.
  25934. * @param {...*} arguments... - Any number of arguments to apply to the function.
  25935. * @example
  25936. *
  25937. * // in a module
  25938. * var hello = function(name, callback) {
  25939. * setTimeout(function() {
  25940. * callback(null, {hello: name});
  25941. * }, 1000);
  25942. * };
  25943. *
  25944. * // in the node repl
  25945. * node> async.dir(hello, 'world');
  25946. * {hello: 'world'}
  25947. */
  25948. var dir = consoleFunc('dir');
  25949. /**
  25950. * The post-check version of [`during`]{@link module:ControlFlow.during}. To reflect the difference in
  25951. * the order of operations, the arguments `test` and `fn` are switched.
  25952. *
  25953. * Also a version of [`doWhilst`]{@link module:ControlFlow.doWhilst} with asynchronous `test` function.
  25954. * @name doDuring
  25955. * @static
  25956. * @memberOf module:ControlFlow
  25957. * @method
  25958. * @see [async.during]{@link module:ControlFlow.during}
  25959. * @category Control Flow
  25960. * @param {AsyncFunction} fn - An async function which is called each time
  25961. * `test` passes. Invoked with (callback).
  25962. * @param {AsyncFunction} test - asynchronous truth test to perform before each
  25963. * execution of `fn`. Invoked with (...args, callback), where `...args` are the
  25964. * non-error args from the previous callback of `fn`.
  25965. * @param {Function} [callback] - A callback which is called after the test
  25966. * function has failed and repeated execution of `fn` has stopped. `callback`
  25967. * will be passed an error if one occurred, otherwise `null`.
  25968. */
  25969. function doDuring(fn, test, callback) {
  25970. callback = onlyOnce(callback || noop);
  25971. var _fn = wrapAsync(fn);
  25972. var _test = wrapAsync(test);
  25973. function next(err/*, ...args*/) {
  25974. if (err) return callback(err);
  25975. var args = slice(arguments, 1);
  25976. args.push(check);
  25977. _test.apply(this, args);
  25978. }
  25979. function check(err, truth) {
  25980. if (err) return callback(err);
  25981. if (!truth) return callback(null);
  25982. _fn(next);
  25983. }
  25984. check(null, true);
  25985. }
  25986. /**
  25987. * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in
  25988. * the order of operations, the arguments `test` and `iteratee` are switched.
  25989. *
  25990. * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.
  25991. *
  25992. * @name doWhilst
  25993. * @static
  25994. * @memberOf module:ControlFlow
  25995. * @method
  25996. * @see [async.whilst]{@link module:ControlFlow.whilst}
  25997. * @category Control Flow
  25998. * @param {AsyncFunction} iteratee - A function which is called each time `test`
  25999. * passes. Invoked with (callback).
  26000. * @param {Function} test - synchronous truth test to perform after each
  26001. * execution of `iteratee`. Invoked with any non-error callback results of
  26002. * `iteratee`.
  26003. * @param {Function} [callback] - A callback which is called after the test
  26004. * function has failed and repeated execution of `iteratee` has stopped.
  26005. * `callback` will be passed an error and any arguments passed to the final
  26006. * `iteratee`'s callback. Invoked with (err, [results]);
  26007. */
  26008. function doWhilst(iteratee, test, callback) {
  26009. callback = onlyOnce(callback || noop);
  26010. var _iteratee = wrapAsync(iteratee);
  26011. var next = function(err/*, ...args*/) {
  26012. if (err) return callback(err);
  26013. var args = slice(arguments, 1);
  26014. if (test.apply(this, args)) return _iteratee(next);
  26015. callback.apply(null, [null].concat(args));
  26016. };
  26017. _iteratee(next);
  26018. }
  26019. /**
  26020. * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the
  26021. * argument ordering differs from `until`.
  26022. *
  26023. * @name doUntil
  26024. * @static
  26025. * @memberOf module:ControlFlow
  26026. * @method
  26027. * @see [async.doWhilst]{@link module:ControlFlow.doWhilst}
  26028. * @category Control Flow
  26029. * @param {AsyncFunction} iteratee - An async function which is called each time
  26030. * `test` fails. Invoked with (callback).
  26031. * @param {Function} test - synchronous truth test to perform after each
  26032. * execution of `iteratee`. Invoked with any non-error callback results of
  26033. * `iteratee`.
  26034. * @param {Function} [callback] - A callback which is called after the test
  26035. * function has passed and repeated execution of `iteratee` has stopped. `callback`
  26036. * will be passed an error and any arguments passed to the final `iteratee`'s
  26037. * callback. Invoked with (err, [results]);
  26038. */
  26039. function doUntil(iteratee, test, callback) {
  26040. doWhilst(iteratee, function() {
  26041. return !test.apply(this, arguments);
  26042. }, callback);
  26043. }
  26044. /**
  26045. * Like [`whilst`]{@link module:ControlFlow.whilst}, except the `test` is an asynchronous function that
  26046. * is passed a callback in the form of `function (err, truth)`. If error is
  26047. * passed to `test` or `fn`, the main callback is immediately called with the
  26048. * value of the error.
  26049. *
  26050. * @name during
  26051. * @static
  26052. * @memberOf module:ControlFlow
  26053. * @method
  26054. * @see [async.whilst]{@link module:ControlFlow.whilst}
  26055. * @category Control Flow
  26056. * @param {AsyncFunction} test - asynchronous truth test to perform before each
  26057. * execution of `fn`. Invoked with (callback).
  26058. * @param {AsyncFunction} fn - An async function which is called each time
  26059. * `test` passes. Invoked with (callback).
  26060. * @param {Function} [callback] - A callback which is called after the test
  26061. * function has failed and repeated execution of `fn` has stopped. `callback`
  26062. * will be passed an error, if one occurred, otherwise `null`.
  26063. * @example
  26064. *
  26065. * var count = 0;
  26066. *
  26067. * async.during(
  26068. * function (callback) {
  26069. * return callback(null, count < 5);
  26070. * },
  26071. * function (callback) {
  26072. * count++;
  26073. * setTimeout(callback, 1000);
  26074. * },
  26075. * function (err) {
  26076. * // 5 seconds have passed
  26077. * }
  26078. * );
  26079. */
  26080. function during(test, fn, callback) {
  26081. callback = onlyOnce(callback || noop);
  26082. var _fn = wrapAsync(fn);
  26083. var _test = wrapAsync(test);
  26084. function next(err) {
  26085. if (err) return callback(err);
  26086. _test(check);
  26087. }
  26088. function check(err, truth) {
  26089. if (err) return callback(err);
  26090. if (!truth) return callback(null);
  26091. _fn(next);
  26092. }
  26093. _test(check);
  26094. }
  26095. function _withoutIndex(iteratee) {
  26096. return function (value, index, callback) {
  26097. return iteratee(value, callback);
  26098. };
  26099. }
  26100. /**
  26101. * Applies the function `iteratee` to each item in `coll`, in parallel.
  26102. * The `iteratee` is called with an item from the list, and a callback for when
  26103. * it has finished. If the `iteratee` passes an error to its `callback`, the
  26104. * main `callback` (for the `each` function) is immediately called with the
  26105. * error.
  26106. *
  26107. * Note, that since this function applies `iteratee` to each item in parallel,
  26108. * there is no guarantee that the iteratee functions will complete in order.
  26109. *
  26110. * @name each
  26111. * @static
  26112. * @memberOf module:Collections
  26113. * @method
  26114. * @alias forEach
  26115. * @category Collection
  26116. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  26117. * @param {AsyncFunction} iteratee - An async function to apply to
  26118. * each item in `coll`. Invoked with (item, callback).
  26119. * The array index is not passed to the iteratee.
  26120. * If you need the index, use `eachOf`.
  26121. * @param {Function} [callback] - A callback which is called when all
  26122. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  26123. * @example
  26124. *
  26125. * // assuming openFiles is an array of file names and saveFile is a function
  26126. * // to save the modified contents of that file:
  26127. *
  26128. * async.each(openFiles, saveFile, function(err){
  26129. * // if any of the saves produced an error, err would equal that error
  26130. * });
  26131. *
  26132. * // assuming openFiles is an array of file names
  26133. * async.each(openFiles, function(file, callback) {
  26134. *
  26135. * // Perform operation on file here.
  26136. * console.log('Processing file ' + file);
  26137. *
  26138. * if( file.length > 32 ) {
  26139. * console.log('This file name is too long');
  26140. * callback('File name too long');
  26141. * } else {
  26142. * // Do work to process file here
  26143. * console.log('File processed');
  26144. * callback();
  26145. * }
  26146. * }, function(err) {
  26147. * // if any of the file processing produced an error, err would equal that error
  26148. * if( err ) {
  26149. * // One of the iterations produced an error.
  26150. * // All processing will now stop.
  26151. * console.log('A file failed to process');
  26152. * } else {
  26153. * console.log('All files have been processed successfully');
  26154. * }
  26155. * });
  26156. */
  26157. function eachLimit(coll, iteratee, callback) {
  26158. eachOf(coll, _withoutIndex(wrapAsync(iteratee)), callback);
  26159. }
  26160. /**
  26161. * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time.
  26162. *
  26163. * @name eachLimit
  26164. * @static
  26165. * @memberOf module:Collections
  26166. * @method
  26167. * @see [async.each]{@link module:Collections.each}
  26168. * @alias forEachLimit
  26169. * @category Collection
  26170. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  26171. * @param {number} limit - The maximum number of async operations at a time.
  26172. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  26173. * `coll`.
  26174. * The array index is not passed to the iteratee.
  26175. * If you need the index, use `eachOfLimit`.
  26176. * Invoked with (item, callback).
  26177. * @param {Function} [callback] - A callback which is called when all
  26178. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  26179. */
  26180. function eachLimit$1(coll, limit, iteratee, callback) {
  26181. _eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback);
  26182. }
  26183. /**
  26184. * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time.
  26185. *
  26186. * @name eachSeries
  26187. * @static
  26188. * @memberOf module:Collections
  26189. * @method
  26190. * @see [async.each]{@link module:Collections.each}
  26191. * @alias forEachSeries
  26192. * @category Collection
  26193. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  26194. * @param {AsyncFunction} iteratee - An async function to apply to each
  26195. * item in `coll`.
  26196. * The array index is not passed to the iteratee.
  26197. * If you need the index, use `eachOfSeries`.
  26198. * Invoked with (item, callback).
  26199. * @param {Function} [callback] - A callback which is called when all
  26200. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  26201. */
  26202. var eachSeries = doLimit(eachLimit$1, 1);
  26203. /**
  26204. * Wrap an async function and ensure it calls its callback on a later tick of
  26205. * the event loop. If the function already calls its callback on a next tick,
  26206. * no extra deferral is added. This is useful for preventing stack overflows
  26207. * (`RangeError: Maximum call stack size exceeded`) and generally keeping
  26208. * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony)
  26209. * contained. ES2017 `async` functions are returned as-is -- they are immune
  26210. * to Zalgo's corrupting influences, as they always resolve on a later tick.
  26211. *
  26212. * @name ensureAsync
  26213. * @static
  26214. * @memberOf module:Utils
  26215. * @method
  26216. * @category Util
  26217. * @param {AsyncFunction} fn - an async function, one that expects a node-style
  26218. * callback as its last argument.
  26219. * @returns {AsyncFunction} Returns a wrapped function with the exact same call
  26220. * signature as the function passed in.
  26221. * @example
  26222. *
  26223. * function sometimesAsync(arg, callback) {
  26224. * if (cache[arg]) {
  26225. * return callback(null, cache[arg]); // this would be synchronous!!
  26226. * } else {
  26227. * doSomeIO(arg, callback); // this IO would be asynchronous
  26228. * }
  26229. * }
  26230. *
  26231. * // this has a risk of stack overflows if many results are cached in a row
  26232. * async.mapSeries(args, sometimesAsync, done);
  26233. *
  26234. * // this will defer sometimesAsync's callback if necessary,
  26235. * // preventing stack overflows
  26236. * async.mapSeries(args, async.ensureAsync(sometimesAsync), done);
  26237. */
  26238. function ensureAsync(fn) {
  26239. if (isAsync(fn)) return fn;
  26240. return initialParams(function (args, callback) {
  26241. var sync = true;
  26242. args.push(function () {
  26243. var innerArgs = arguments;
  26244. if (sync) {
  26245. setImmediate$1(function () {
  26246. callback.apply(null, innerArgs);
  26247. });
  26248. } else {
  26249. callback.apply(null, innerArgs);
  26250. }
  26251. });
  26252. fn.apply(this, args);
  26253. sync = false;
  26254. });
  26255. }
  26256. function notId(v) {
  26257. return !v;
  26258. }
  26259. /**
  26260. * Returns `true` if every element in `coll` satisfies an async test. If any
  26261. * iteratee call returns `false`, the main `callback` is immediately called.
  26262. *
  26263. * @name every
  26264. * @static
  26265. * @memberOf module:Collections
  26266. * @method
  26267. * @alias all
  26268. * @category Collection
  26269. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  26270. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  26271. * in the collection in parallel.
  26272. * The iteratee must complete with a boolean result value.
  26273. * Invoked with (item, callback).
  26274. * @param {Function} [callback] - A callback which is called after all the
  26275. * `iteratee` functions have finished. Result will be either `true` or `false`
  26276. * depending on the values of the async tests. Invoked with (err, result).
  26277. * @example
  26278. *
  26279. * async.every(['file1','file2','file3'], function(filePath, callback) {
  26280. * fs.access(filePath, function(err) {
  26281. * callback(null, !err)
  26282. * });
  26283. * }, function(err, result) {
  26284. * // if result is true then every file exists
  26285. * });
  26286. */
  26287. var every = doParallel(_createTester(notId, notId));
  26288. /**
  26289. * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time.
  26290. *
  26291. * @name everyLimit
  26292. * @static
  26293. * @memberOf module:Collections
  26294. * @method
  26295. * @see [async.every]{@link module:Collections.every}
  26296. * @alias allLimit
  26297. * @category Collection
  26298. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  26299. * @param {number} limit - The maximum number of async operations at a time.
  26300. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  26301. * in the collection in parallel.
  26302. * The iteratee must complete with a boolean result value.
  26303. * Invoked with (item, callback).
  26304. * @param {Function} [callback] - A callback which is called after all the
  26305. * `iteratee` functions have finished. Result will be either `true` or `false`
  26306. * depending on the values of the async tests. Invoked with (err, result).
  26307. */
  26308. var everyLimit = doParallelLimit(_createTester(notId, notId));
  26309. /**
  26310. * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time.
  26311. *
  26312. * @name everySeries
  26313. * @static
  26314. * @memberOf module:Collections
  26315. * @method
  26316. * @see [async.every]{@link module:Collections.every}
  26317. * @alias allSeries
  26318. * @category Collection
  26319. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  26320. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  26321. * in the collection in series.
  26322. * The iteratee must complete with a boolean result value.
  26323. * Invoked with (item, callback).
  26324. * @param {Function} [callback] - A callback which is called after all the
  26325. * `iteratee` functions have finished. Result will be either `true` or `false`
  26326. * depending on the values of the async tests. Invoked with (err, result).
  26327. */
  26328. var everySeries = doLimit(everyLimit, 1);
  26329. /**
  26330. * The base implementation of `_.property` without support for deep paths.
  26331. *
  26332. * @private
  26333. * @param {string} key The key of the property to get.
  26334. * @returns {Function} Returns the new accessor function.
  26335. */
  26336. function baseProperty(key) {
  26337. return function(object) {
  26338. return object == null ? undefined : object[key];
  26339. };
  26340. }
  26341. function filterArray(eachfn, arr, iteratee, callback) {
  26342. var truthValues = new Array(arr.length);
  26343. eachfn(arr, function (x, index, callback) {
  26344. iteratee(x, function (err, v) {
  26345. truthValues[index] = !!v;
  26346. callback(err);
  26347. });
  26348. }, function (err) {
  26349. if (err) return callback(err);
  26350. var results = [];
  26351. for (var i = 0; i < arr.length; i++) {
  26352. if (truthValues[i]) results.push(arr[i]);
  26353. }
  26354. callback(null, results);
  26355. });
  26356. }
  26357. function filterGeneric(eachfn, coll, iteratee, callback) {
  26358. var results = [];
  26359. eachfn(coll, function (x, index, callback) {
  26360. iteratee(x, function (err, v) {
  26361. if (err) {
  26362. callback(err);
  26363. } else {
  26364. if (v) {
  26365. results.push({index: index, value: x});
  26366. }
  26367. callback();
  26368. }
  26369. });
  26370. }, function (err) {
  26371. if (err) {
  26372. callback(err);
  26373. } else {
  26374. callback(null, arrayMap(results.sort(function (a, b) {
  26375. return a.index - b.index;
  26376. }), baseProperty('value')));
  26377. }
  26378. });
  26379. }
  26380. function _filter(eachfn, coll, iteratee, callback) {
  26381. var filter = isArrayLike(coll) ? filterArray : filterGeneric;
  26382. filter(eachfn, coll, wrapAsync(iteratee), callback || noop);
  26383. }
  26384. /**
  26385. * Returns a new array of all the values in `coll` which pass an async truth
  26386. * test. This operation is performed in parallel, but the results array will be
  26387. * in the same order as the original.
  26388. *
  26389. * @name filter
  26390. * @static
  26391. * @memberOf module:Collections
  26392. * @method
  26393. * @alias select
  26394. * @category Collection
  26395. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  26396. * @param {Function} iteratee - A truth test to apply to each item in `coll`.
  26397. * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
  26398. * with a boolean argument once it has completed. Invoked with (item, callback).
  26399. * @param {Function} [callback] - A callback which is called after all the
  26400. * `iteratee` functions have finished. Invoked with (err, results).
  26401. * @example
  26402. *
  26403. * async.filter(['file1','file2','file3'], function(filePath, callback) {
  26404. * fs.access(filePath, function(err) {
  26405. * callback(null, !err)
  26406. * });
  26407. * }, function(err, results) {
  26408. * // results now equals an array of the existing files
  26409. * });
  26410. */
  26411. var filter = doParallel(_filter);
  26412. /**
  26413. * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a
  26414. * time.
  26415. *
  26416. * @name filterLimit
  26417. * @static
  26418. * @memberOf module:Collections
  26419. * @method
  26420. * @see [async.filter]{@link module:Collections.filter}
  26421. * @alias selectLimit
  26422. * @category Collection
  26423. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  26424. * @param {number} limit - The maximum number of async operations at a time.
  26425. * @param {Function} iteratee - A truth test to apply to each item in `coll`.
  26426. * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
  26427. * with a boolean argument once it has completed. Invoked with (item, callback).
  26428. * @param {Function} [callback] - A callback which is called after all the
  26429. * `iteratee` functions have finished. Invoked with (err, results).
  26430. */
  26431. var filterLimit = doParallelLimit(_filter);
  26432. /**
  26433. * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time.
  26434. *
  26435. * @name filterSeries
  26436. * @static
  26437. * @memberOf module:Collections
  26438. * @method
  26439. * @see [async.filter]{@link module:Collections.filter}
  26440. * @alias selectSeries
  26441. * @category Collection
  26442. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  26443. * @param {Function} iteratee - A truth test to apply to each item in `coll`.
  26444. * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
  26445. * with a boolean argument once it has completed. Invoked with (item, callback).
  26446. * @param {Function} [callback] - A callback which is called after all the
  26447. * `iteratee` functions have finished. Invoked with (err, results)
  26448. */
  26449. var filterSeries = doLimit(filterLimit, 1);
  26450. /**
  26451. * Calls the asynchronous function `fn` with a callback parameter that allows it
  26452. * to call itself again, in series, indefinitely.
  26453. * If an error is passed to the callback then `errback` is called with the
  26454. * error, and execution stops, otherwise it will never be called.
  26455. *
  26456. * @name forever
  26457. * @static
  26458. * @memberOf module:ControlFlow
  26459. * @method
  26460. * @category Control Flow
  26461. * @param {AsyncFunction} fn - an async function to call repeatedly.
  26462. * Invoked with (next).
  26463. * @param {Function} [errback] - when `fn` passes an error to it's callback,
  26464. * this function will be called, and execution stops. Invoked with (err).
  26465. * @example
  26466. *
  26467. * async.forever(
  26468. * function(next) {
  26469. * // next is suitable for passing to things that need a callback(err [, whatever]);
  26470. * // it will result in this function being called again.
  26471. * },
  26472. * function(err) {
  26473. * // if next is called with a value in its first parameter, it will appear
  26474. * // in here as 'err', and execution will stop.
  26475. * }
  26476. * );
  26477. */
  26478. function forever(fn, errback) {
  26479. var done = onlyOnce(errback || noop);
  26480. var task = wrapAsync(ensureAsync(fn));
  26481. function next(err) {
  26482. if (err) return done(err);
  26483. task(next);
  26484. }
  26485. next();
  26486. }
  26487. /**
  26488. * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time.
  26489. *
  26490. * @name groupByLimit
  26491. * @static
  26492. * @memberOf module:Collections
  26493. * @method
  26494. * @see [async.groupBy]{@link module:Collections.groupBy}
  26495. * @category Collection
  26496. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  26497. * @param {number} limit - The maximum number of async operations at a time.
  26498. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  26499. * `coll`.
  26500. * The iteratee should complete with a `key` to group the value under.
  26501. * Invoked with (value, callback).
  26502. * @param {Function} [callback] - A callback which is called when all `iteratee`
  26503. * functions have finished, or an error occurs. Result is an `Object` whoses
  26504. * properties are arrays of values which returned the corresponding key.
  26505. */
  26506. var groupByLimit = function(coll, limit, iteratee, callback) {
  26507. callback = callback || noop;
  26508. var _iteratee = wrapAsync(iteratee);
  26509. mapLimit(coll, limit, function(val, callback) {
  26510. _iteratee(val, function(err, key) {
  26511. if (err) return callback(err);
  26512. return callback(null, {key: key, val: val});
  26513. });
  26514. }, function(err, mapResults) {
  26515. var result = {};
  26516. // from MDN, handle object having an `hasOwnProperty` prop
  26517. var hasOwnProperty = Object.prototype.hasOwnProperty;
  26518. for (var i = 0; i < mapResults.length; i++) {
  26519. if (mapResults[i]) {
  26520. var key = mapResults[i].key;
  26521. var val = mapResults[i].val;
  26522. if (hasOwnProperty.call(result, key)) {
  26523. result[key].push(val);
  26524. } else {
  26525. result[key] = [val];
  26526. }
  26527. }
  26528. }
  26529. return callback(err, result);
  26530. });
  26531. };
  26532. /**
  26533. * Returns a new object, where each value corresponds to an array of items, from
  26534. * `coll`, that returned the corresponding key. That is, the keys of the object
  26535. * correspond to the values passed to the `iteratee` callback.
  26536. *
  26537. * Note: Since this function applies the `iteratee` to each item in parallel,
  26538. * there is no guarantee that the `iteratee` functions will complete in order.
  26539. * However, the values for each key in the `result` will be in the same order as
  26540. * the original `coll`. For Objects, the values will roughly be in the order of
  26541. * the original Objects' keys (but this can vary across JavaScript engines).
  26542. *
  26543. * @name groupBy
  26544. * @static
  26545. * @memberOf module:Collections
  26546. * @method
  26547. * @category Collection
  26548. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  26549. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  26550. * `coll`.
  26551. * The iteratee should complete with a `key` to group the value under.
  26552. * Invoked with (value, callback).
  26553. * @param {Function} [callback] - A callback which is called when all `iteratee`
  26554. * functions have finished, or an error occurs. Result is an `Object` whoses
  26555. * properties are arrays of values which returned the corresponding key.
  26556. * @example
  26557. *
  26558. * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) {
  26559. * db.findById(userId, function(err, user) {
  26560. * if (err) return callback(err);
  26561. * return callback(null, user.age);
  26562. * });
  26563. * }, function(err, result) {
  26564. * // result is object containing the userIds grouped by age
  26565. * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']};
  26566. * });
  26567. */
  26568. var groupBy = doLimit(groupByLimit, Infinity);
  26569. /**
  26570. * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time.
  26571. *
  26572. * @name groupBySeries
  26573. * @static
  26574. * @memberOf module:Collections
  26575. * @method
  26576. * @see [async.groupBy]{@link module:Collections.groupBy}
  26577. * @category Collection
  26578. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  26579. * @param {number} limit - The maximum number of async operations at a time.
  26580. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  26581. * `coll`.
  26582. * The iteratee should complete with a `key` to group the value under.
  26583. * Invoked with (value, callback).
  26584. * @param {Function} [callback] - A callback which is called when all `iteratee`
  26585. * functions have finished, or an error occurs. Result is an `Object` whoses
  26586. * properties are arrays of values which returned the corresponding key.
  26587. */
  26588. var groupBySeries = doLimit(groupByLimit, 1);
  26589. /**
  26590. * Logs the result of an `async` function to the `console`. Only works in
  26591. * Node.js or in browsers that support `console.log` and `console.error` (such
  26592. * as FF and Chrome). If multiple arguments are returned from the async
  26593. * function, `console.log` is called on each argument in order.
  26594. *
  26595. * @name log
  26596. * @static
  26597. * @memberOf module:Utils
  26598. * @method
  26599. * @category Util
  26600. * @param {AsyncFunction} function - The function you want to eventually apply
  26601. * all arguments to.
  26602. * @param {...*} arguments... - Any number of arguments to apply to the function.
  26603. * @example
  26604. *
  26605. * // in a module
  26606. * var hello = function(name, callback) {
  26607. * setTimeout(function() {
  26608. * callback(null, 'hello ' + name);
  26609. * }, 1000);
  26610. * };
  26611. *
  26612. * // in the node repl
  26613. * node> async.log(hello, 'world');
  26614. * 'hello world'
  26615. */
  26616. var log = consoleFunc('log');
  26617. /**
  26618. * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a
  26619. * time.
  26620. *
  26621. * @name mapValuesLimit
  26622. * @static
  26623. * @memberOf module:Collections
  26624. * @method
  26625. * @see [async.mapValues]{@link module:Collections.mapValues}
  26626. * @category Collection
  26627. * @param {Object} obj - A collection to iterate over.
  26628. * @param {number} limit - The maximum number of async operations at a time.
  26629. * @param {AsyncFunction} iteratee - A function to apply to each value and key
  26630. * in `coll`.
  26631. * The iteratee should complete with the transformed value as its result.
  26632. * Invoked with (value, key, callback).
  26633. * @param {Function} [callback] - A callback which is called when all `iteratee`
  26634. * functions have finished, or an error occurs. `result` is a new object consisting
  26635. * of each key from `obj`, with each transformed value on the right-hand side.
  26636. * Invoked with (err, result).
  26637. */
  26638. function mapValuesLimit(obj, limit, iteratee, callback) {
  26639. callback = once(callback || noop);
  26640. var newObj = {};
  26641. var _iteratee = wrapAsync(iteratee);
  26642. eachOfLimit(obj, limit, function(val, key, next) {
  26643. _iteratee(val, key, function (err, result) {
  26644. if (err) return next(err);
  26645. newObj[key] = result;
  26646. next();
  26647. });
  26648. }, function (err) {
  26649. callback(err, newObj);
  26650. });
  26651. }
  26652. /**
  26653. * A relative of [`map`]{@link module:Collections.map}, designed for use with objects.
  26654. *
  26655. * Produces a new Object by mapping each value of `obj` through the `iteratee`
  26656. * function. The `iteratee` is called each `value` and `key` from `obj` and a
  26657. * callback for when it has finished processing. Each of these callbacks takes
  26658. * two arguments: an `error`, and the transformed item from `obj`. If `iteratee`
  26659. * passes an error to its callback, the main `callback` (for the `mapValues`
  26660. * function) is immediately called with the error.
  26661. *
  26662. * Note, the order of the keys in the result is not guaranteed. The keys will
  26663. * be roughly in the order they complete, (but this is very engine-specific)
  26664. *
  26665. * @name mapValues
  26666. * @static
  26667. * @memberOf module:Collections
  26668. * @method
  26669. * @category Collection
  26670. * @param {Object} obj - A collection to iterate over.
  26671. * @param {AsyncFunction} iteratee - A function to apply to each value and key
  26672. * in `coll`.
  26673. * The iteratee should complete with the transformed value as its result.
  26674. * Invoked with (value, key, callback).
  26675. * @param {Function} [callback] - A callback which is called when all `iteratee`
  26676. * functions have finished, or an error occurs. `result` is a new object consisting
  26677. * of each key from `obj`, with each transformed value on the right-hand side.
  26678. * Invoked with (err, result).
  26679. * @example
  26680. *
  26681. * async.mapValues({
  26682. * f1: 'file1',
  26683. * f2: 'file2',
  26684. * f3: 'file3'
  26685. * }, function (file, key, callback) {
  26686. * fs.stat(file, callback);
  26687. * }, function(err, result) {
  26688. * // result is now a map of stats for each file, e.g.
  26689. * // {
  26690. * // f1: [stats for file1],
  26691. * // f2: [stats for file2],
  26692. * // f3: [stats for file3]
  26693. * // }
  26694. * });
  26695. */
  26696. var mapValues = doLimit(mapValuesLimit, Infinity);
  26697. /**
  26698. * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time.
  26699. *
  26700. * @name mapValuesSeries
  26701. * @static
  26702. * @memberOf module:Collections
  26703. * @method
  26704. * @see [async.mapValues]{@link module:Collections.mapValues}
  26705. * @category Collection
  26706. * @param {Object} obj - A collection to iterate over.
  26707. * @param {AsyncFunction} iteratee - A function to apply to each value and key
  26708. * in `coll`.
  26709. * The iteratee should complete with the transformed value as its result.
  26710. * Invoked with (value, key, callback).
  26711. * @param {Function} [callback] - A callback which is called when all `iteratee`
  26712. * functions have finished, or an error occurs. `result` is a new object consisting
  26713. * of each key from `obj`, with each transformed value on the right-hand side.
  26714. * Invoked with (err, result).
  26715. */
  26716. var mapValuesSeries = doLimit(mapValuesLimit, 1);
  26717. function has(obj, key) {
  26718. return key in obj;
  26719. }
  26720. /**
  26721. * Caches the results of an async function. When creating a hash to store
  26722. * function results against, the callback is omitted from the hash and an
  26723. * optional hash function can be used.
  26724. *
  26725. * If no hash function is specified, the first argument is used as a hash key,
  26726. * which may work reasonably if it is a string or a data type that converts to a
  26727. * distinct string. Note that objects and arrays will not behave reasonably.
  26728. * Neither will cases where the other arguments are significant. In such cases,
  26729. * specify your own hash function.
  26730. *
  26731. * The cache of results is exposed as the `memo` property of the function
  26732. * returned by `memoize`.
  26733. *
  26734. * @name memoize
  26735. * @static
  26736. * @memberOf module:Utils
  26737. * @method
  26738. * @category Util
  26739. * @param {AsyncFunction} fn - The async function to proxy and cache results from.
  26740. * @param {Function} hasher - An optional function for generating a custom hash
  26741. * for storing results. It has all the arguments applied to it apart from the
  26742. * callback, and must be synchronous.
  26743. * @returns {AsyncFunction} a memoized version of `fn`
  26744. * @example
  26745. *
  26746. * var slow_fn = function(name, callback) {
  26747. * // do something
  26748. * callback(null, result);
  26749. * };
  26750. * var fn = async.memoize(slow_fn);
  26751. *
  26752. * // fn can now be used as if it were slow_fn
  26753. * fn('some name', function() {
  26754. * // callback
  26755. * });
  26756. */
  26757. function memoize(fn, hasher) {
  26758. var memo = Object.create(null);
  26759. var queues = Object.create(null);
  26760. hasher = hasher || identity;
  26761. var _fn = wrapAsync(fn);
  26762. var memoized = initialParams(function memoized(args, callback) {
  26763. var key = hasher.apply(null, args);
  26764. if (has(memo, key)) {
  26765. setImmediate$1(function() {
  26766. callback.apply(null, memo[key]);
  26767. });
  26768. } else if (has(queues, key)) {
  26769. queues[key].push(callback);
  26770. } else {
  26771. queues[key] = [callback];
  26772. _fn.apply(null, args.concat(function(/*args*/) {
  26773. var args = slice(arguments);
  26774. memo[key] = args;
  26775. var q = queues[key];
  26776. delete queues[key];
  26777. for (var i = 0, l = q.length; i < l; i++) {
  26778. q[i].apply(null, args);
  26779. }
  26780. }));
  26781. }
  26782. });
  26783. memoized.memo = memo;
  26784. memoized.unmemoized = fn;
  26785. return memoized;
  26786. }
  26787. /**
  26788. * Calls `callback` on a later loop around the event loop. In Node.js this just
  26789. * calls `process.nextTick`. In the browser it will use `setImmediate` if
  26790. * available, otherwise `setTimeout(callback, 0)`, which means other higher
  26791. * priority events may precede the execution of `callback`.
  26792. *
  26793. * This is used internally for browser-compatibility purposes.
  26794. *
  26795. * @name nextTick
  26796. * @static
  26797. * @memberOf module:Utils
  26798. * @method
  26799. * @see [async.setImmediate]{@link module:Utils.setImmediate}
  26800. * @category Util
  26801. * @param {Function} callback - The function to call on a later loop around
  26802. * the event loop. Invoked with (args...).
  26803. * @param {...*} args... - any number of additional arguments to pass to the
  26804. * callback on the next tick.
  26805. * @example
  26806. *
  26807. * var call_order = [];
  26808. * async.nextTick(function() {
  26809. * call_order.push('two');
  26810. * // call_order now equals ['one','two']
  26811. * });
  26812. * call_order.push('one');
  26813. *
  26814. * async.setImmediate(function (a, b, c) {
  26815. * // a, b, and c equal 1, 2, and 3
  26816. * }, 1, 2, 3);
  26817. */
  26818. var _defer$1;
  26819. if (hasNextTick) {
  26820. _defer$1 = process.nextTick;
  26821. } else if (hasSetImmediate) {
  26822. _defer$1 = setImmediate;
  26823. } else {
  26824. _defer$1 = fallback;
  26825. }
  26826. var nextTick = wrap(_defer$1);
  26827. function _parallel(eachfn, tasks, callback) {
  26828. callback = callback || noop;
  26829. var results = isArrayLike(tasks) ? [] : {};
  26830. eachfn(tasks, function (task, key, callback) {
  26831. wrapAsync(task)(function (err, result) {
  26832. if (arguments.length > 2) {
  26833. result = slice(arguments, 1);
  26834. }
  26835. results[key] = result;
  26836. callback(err);
  26837. });
  26838. }, function (err) {
  26839. callback(err, results);
  26840. });
  26841. }
  26842. /**
  26843. * Run the `tasks` collection of functions in parallel, without waiting until
  26844. * the previous function has completed. If any of the functions pass an error to
  26845. * its callback, the main `callback` is immediately called with the value of the
  26846. * error. Once the `tasks` have completed, the results are passed to the final
  26847. * `callback` as an array.
  26848. *
  26849. * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about
  26850. * parallel execution of code. If your tasks do not use any timers or perform
  26851. * any I/O, they will actually be executed in series. Any synchronous setup
  26852. * sections for each task will happen one after the other. JavaScript remains
  26853. * single-threaded.
  26854. *
  26855. * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the
  26856. * execution of other tasks when a task fails.
  26857. *
  26858. * It is also possible to use an object instead of an array. Each property will
  26859. * be run as a function and the results will be passed to the final `callback`
  26860. * as an object instead of an array. This can be a more readable way of handling
  26861. * results from {@link async.parallel}.
  26862. *
  26863. * @name parallel
  26864. * @static
  26865. * @memberOf module:ControlFlow
  26866. * @method
  26867. * @category Control Flow
  26868. * @param {Array|Iterable|Object} tasks - A collection of
  26869. * [async functions]{@link AsyncFunction} to run.
  26870. * Each async function can complete with any number of optional `result` values.
  26871. * @param {Function} [callback] - An optional callback to run once all the
  26872. * functions have completed successfully. This function gets a results array
  26873. * (or object) containing all the result arguments passed to the task callbacks.
  26874. * Invoked with (err, results).
  26875. *
  26876. * @example
  26877. * async.parallel([
  26878. * function(callback) {
  26879. * setTimeout(function() {
  26880. * callback(null, 'one');
  26881. * }, 200);
  26882. * },
  26883. * function(callback) {
  26884. * setTimeout(function() {
  26885. * callback(null, 'two');
  26886. * }, 100);
  26887. * }
  26888. * ],
  26889. * // optional callback
  26890. * function(err, results) {
  26891. * // the results array will equal ['one','two'] even though
  26892. * // the second function had a shorter timeout.
  26893. * });
  26894. *
  26895. * // an example using an object instead of an array
  26896. * async.parallel({
  26897. * one: function(callback) {
  26898. * setTimeout(function() {
  26899. * callback(null, 1);
  26900. * }, 200);
  26901. * },
  26902. * two: function(callback) {
  26903. * setTimeout(function() {
  26904. * callback(null, 2);
  26905. * }, 100);
  26906. * }
  26907. * }, function(err, results) {
  26908. * // results is now equals to: {one: 1, two: 2}
  26909. * });
  26910. */
  26911. function parallelLimit(tasks, callback) {
  26912. _parallel(eachOf, tasks, callback);
  26913. }
  26914. /**
  26915. * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a
  26916. * time.
  26917. *
  26918. * @name parallelLimit
  26919. * @static
  26920. * @memberOf module:ControlFlow
  26921. * @method
  26922. * @see [async.parallel]{@link module:ControlFlow.parallel}
  26923. * @category Control Flow
  26924. * @param {Array|Iterable|Object} tasks - A collection of
  26925. * [async functions]{@link AsyncFunction} to run.
  26926. * Each async function can complete with any number of optional `result` values.
  26927. * @param {number} limit - The maximum number of async operations at a time.
  26928. * @param {Function} [callback] - An optional callback to run once all the
  26929. * functions have completed successfully. This function gets a results array
  26930. * (or object) containing all the result arguments passed to the task callbacks.
  26931. * Invoked with (err, results).
  26932. */
  26933. function parallelLimit$1(tasks, limit, callback) {
  26934. _parallel(_eachOfLimit(limit), tasks, callback);
  26935. }
  26936. /**
  26937. * A queue of tasks for the worker function to complete.
  26938. * @typedef {Object} QueueObject
  26939. * @memberOf module:ControlFlow
  26940. * @property {Function} length - a function returning the number of items
  26941. * waiting to be processed. Invoke with `queue.length()`.
  26942. * @property {boolean} started - a boolean indicating whether or not any
  26943. * items have been pushed and processed by the queue.
  26944. * @property {Function} running - a function returning the number of items
  26945. * currently being processed. Invoke with `queue.running()`.
  26946. * @property {Function} workersList - a function returning the array of items
  26947. * currently being processed. Invoke with `queue.workersList()`.
  26948. * @property {Function} idle - a function returning false if there are items
  26949. * waiting or being processed, or true if not. Invoke with `queue.idle()`.
  26950. * @property {number} concurrency - an integer for determining how many `worker`
  26951. * functions should be run in parallel. This property can be changed after a
  26952. * `queue` is created to alter the concurrency on-the-fly.
  26953. * @property {Function} push - add a new task to the `queue`. Calls `callback`
  26954. * once the `worker` has finished processing the task. Instead of a single task,
  26955. * a `tasks` array can be submitted. The respective callback is used for every
  26956. * task in the list. Invoke with `queue.push(task, [callback])`,
  26957. * @property {Function} unshift - add a new task to the front of the `queue`.
  26958. * Invoke with `queue.unshift(task, [callback])`.
  26959. * @property {Function} remove - remove items from the queue that match a test
  26960. * function. The test function will be passed an object with a `data` property,
  26961. * and a `priority` property, if this is a
  26962. * [priorityQueue]{@link module:ControlFlow.priorityQueue} object.
  26963. * Invoked with `queue.remove(testFn)`, where `testFn` is of the form
  26964. * `function ({data, priority}) {}` and returns a Boolean.
  26965. * @property {Function} saturated - a callback that is called when the number of
  26966. * running workers hits the `concurrency` limit, and further tasks will be
  26967. * queued.
  26968. * @property {Function} unsaturated - a callback that is called when the number
  26969. * of running workers is less than the `concurrency` & `buffer` limits, and
  26970. * further tasks will not be queued.
  26971. * @property {number} buffer - A minimum threshold buffer in order to say that
  26972. * the `queue` is `unsaturated`.
  26973. * @property {Function} empty - a callback that is called when the last item
  26974. * from the `queue` is given to a `worker`.
  26975. * @property {Function} drain - a callback that is called when the last item
  26976. * from the `queue` has returned from the `worker`.
  26977. * @property {Function} error - a callback that is called when a task errors.
  26978. * Has the signature `function(error, task)`.
  26979. * @property {boolean} paused - a boolean for determining whether the queue is
  26980. * in a paused state.
  26981. * @property {Function} pause - a function that pauses the processing of tasks
  26982. * until `resume()` is called. Invoke with `queue.pause()`.
  26983. * @property {Function} resume - a function that resumes the processing of
  26984. * queued tasks when the queue is paused. Invoke with `queue.resume()`.
  26985. * @property {Function} kill - a function that removes the `drain` callback and
  26986. * empties remaining tasks from the queue forcing it to go idle. No more tasks
  26987. * should be pushed to the queue after calling this function. Invoke with `queue.kill()`.
  26988. */
  26989. /**
  26990. * Creates a `queue` object with the specified `concurrency`. Tasks added to the
  26991. * `queue` are processed in parallel (up to the `concurrency` limit). If all
  26992. * `worker`s are in progress, the task is queued until one becomes available.
  26993. * Once a `worker` completes a `task`, that `task`'s callback is called.
  26994. *
  26995. * @name queue
  26996. * @static
  26997. * @memberOf module:ControlFlow
  26998. * @method
  26999. * @category Control Flow
  27000. * @param {AsyncFunction} worker - An async function for processing a queued task.
  27001. * If you want to handle errors from an individual task, pass a callback to
  27002. * `q.push()`. Invoked with (task, callback).
  27003. * @param {number} [concurrency=1] - An `integer` for determining how many
  27004. * `worker` functions should be run in parallel. If omitted, the concurrency
  27005. * defaults to `1`. If the concurrency is `0`, an error is thrown.
  27006. * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can
  27007. * attached as certain properties to listen for specific events during the
  27008. * lifecycle of the queue.
  27009. * @example
  27010. *
  27011. * // create a queue object with concurrency 2
  27012. * var q = async.queue(function(task, callback) {
  27013. * console.log('hello ' + task.name);
  27014. * callback();
  27015. * }, 2);
  27016. *
  27017. * // assign a callback
  27018. * q.drain = function() {
  27019. * console.log('all items have been processed');
  27020. * };
  27021. *
  27022. * // add some items to the queue
  27023. * q.push({name: 'foo'}, function(err) {
  27024. * console.log('finished processing foo');
  27025. * });
  27026. * q.push({name: 'bar'}, function (err) {
  27027. * console.log('finished processing bar');
  27028. * });
  27029. *
  27030. * // add some items to the queue (batch-wise)
  27031. * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {
  27032. * console.log('finished processing item');
  27033. * });
  27034. *
  27035. * // add some items to the front of the queue
  27036. * q.unshift({name: 'bar'}, function (err) {
  27037. * console.log('finished processing bar');
  27038. * });
  27039. */
  27040. var queue$1 = function (worker, concurrency) {
  27041. var _worker = wrapAsync(worker);
  27042. return queue(function (items, cb) {
  27043. _worker(items[0], cb);
  27044. }, concurrency, 1);
  27045. };
  27046. /**
  27047. * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and
  27048. * completed in ascending priority order.
  27049. *
  27050. * @name priorityQueue
  27051. * @static
  27052. * @memberOf module:ControlFlow
  27053. * @method
  27054. * @see [async.queue]{@link module:ControlFlow.queue}
  27055. * @category Control Flow
  27056. * @param {AsyncFunction} worker - An async function for processing a queued task.
  27057. * If you want to handle errors from an individual task, pass a callback to
  27058. * `q.push()`.
  27059. * Invoked with (task, callback).
  27060. * @param {number} concurrency - An `integer` for determining how many `worker`
  27061. * functions should be run in parallel. If omitted, the concurrency defaults to
  27062. * `1`. If the concurrency is `0`, an error is thrown.
  27063. * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two
  27064. * differences between `queue` and `priorityQueue` objects:
  27065. * * `push(task, priority, [callback])` - `priority` should be a number. If an
  27066. * array of `tasks` is given, all tasks will be assigned the same priority.
  27067. * * The `unshift` method was removed.
  27068. */
  27069. var priorityQueue = function(worker, concurrency) {
  27070. // Start with a normal queue
  27071. var q = queue$1(worker, concurrency);
  27072. // Override push to accept second parameter representing priority
  27073. q.push = function(data, priority, callback) {
  27074. if (callback == null) callback = noop;
  27075. if (typeof callback !== 'function') {
  27076. throw new Error('task callback must be a function');
  27077. }
  27078. q.started = true;
  27079. if (!isArray(data)) {
  27080. data = [data];
  27081. }
  27082. if (data.length === 0) {
  27083. // call drain immediately if there are no tasks
  27084. return setImmediate$1(function() {
  27085. q.drain();
  27086. });
  27087. }
  27088. priority = priority || 0;
  27089. var nextNode = q._tasks.head;
  27090. while (nextNode && priority >= nextNode.priority) {
  27091. nextNode = nextNode.next;
  27092. }
  27093. for (var i = 0, l = data.length; i < l; i++) {
  27094. var item = {
  27095. data: data[i],
  27096. priority: priority,
  27097. callback: callback
  27098. };
  27099. if (nextNode) {
  27100. q._tasks.insertBefore(nextNode, item);
  27101. } else {
  27102. q._tasks.push(item);
  27103. }
  27104. }
  27105. setImmediate$1(q.process);
  27106. };
  27107. // Remove unshift function
  27108. delete q.unshift;
  27109. return q;
  27110. };
  27111. /**
  27112. * Runs the `tasks` array of functions in parallel, without waiting until the
  27113. * previous function has completed. Once any of the `tasks` complete or pass an
  27114. * error to its callback, the main `callback` is immediately called. It's
  27115. * equivalent to `Promise.race()`.
  27116. *
  27117. * @name race
  27118. * @static
  27119. * @memberOf module:ControlFlow
  27120. * @method
  27121. * @category Control Flow
  27122. * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction}
  27123. * to run. Each function can complete with an optional `result` value.
  27124. * @param {Function} callback - A callback to run once any of the functions have
  27125. * completed. This function gets an error or result from the first function that
  27126. * completed. Invoked with (err, result).
  27127. * @returns undefined
  27128. * @example
  27129. *
  27130. * async.race([
  27131. * function(callback) {
  27132. * setTimeout(function() {
  27133. * callback(null, 'one');
  27134. * }, 200);
  27135. * },
  27136. * function(callback) {
  27137. * setTimeout(function() {
  27138. * callback(null, 'two');
  27139. * }, 100);
  27140. * }
  27141. * ],
  27142. * // main callback
  27143. * function(err, result) {
  27144. * // the result will be equal to 'two' as it finishes earlier
  27145. * });
  27146. */
  27147. function race(tasks, callback) {
  27148. callback = once(callback || noop);
  27149. if (!isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions'));
  27150. if (!tasks.length) return callback();
  27151. for (var i = 0, l = tasks.length; i < l; i++) {
  27152. wrapAsync(tasks[i])(callback);
  27153. }
  27154. }
  27155. /**
  27156. * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order.
  27157. *
  27158. * @name reduceRight
  27159. * @static
  27160. * @memberOf module:Collections
  27161. * @method
  27162. * @see [async.reduce]{@link module:Collections.reduce}
  27163. * @alias foldr
  27164. * @category Collection
  27165. * @param {Array} array - A collection to iterate over.
  27166. * @param {*} memo - The initial state of the reduction.
  27167. * @param {AsyncFunction} iteratee - A function applied to each item in the
  27168. * array to produce the next step in the reduction.
  27169. * The `iteratee` should complete with the next state of the reduction.
  27170. * If the iteratee complete with an error, the reduction is stopped and the
  27171. * main `callback` is immediately called with the error.
  27172. * Invoked with (memo, item, callback).
  27173. * @param {Function} [callback] - A callback which is called after all the
  27174. * `iteratee` functions have finished. Result is the reduced value. Invoked with
  27175. * (err, result).
  27176. */
  27177. function reduceRight (array, memo, iteratee, callback) {
  27178. var reversed = slice(array).reverse();
  27179. reduce(reversed, memo, iteratee, callback);
  27180. }
  27181. /**
  27182. * Wraps the async function in another function that always completes with a
  27183. * result object, even when it errors.
  27184. *
  27185. * The result object has either the property `error` or `value`.
  27186. *
  27187. * @name reflect
  27188. * @static
  27189. * @memberOf module:Utils
  27190. * @method
  27191. * @category Util
  27192. * @param {AsyncFunction} fn - The async function you want to wrap
  27193. * @returns {Function} - A function that always passes null to it's callback as
  27194. * the error. The second argument to the callback will be an `object` with
  27195. * either an `error` or a `value` property.
  27196. * @example
  27197. *
  27198. * async.parallel([
  27199. * async.reflect(function(callback) {
  27200. * // do some stuff ...
  27201. * callback(null, 'one');
  27202. * }),
  27203. * async.reflect(function(callback) {
  27204. * // do some more stuff but error ...
  27205. * callback('bad stuff happened');
  27206. * }),
  27207. * async.reflect(function(callback) {
  27208. * // do some more stuff ...
  27209. * callback(null, 'two');
  27210. * })
  27211. * ],
  27212. * // optional callback
  27213. * function(err, results) {
  27214. * // values
  27215. * // results[0].value = 'one'
  27216. * // results[1].error = 'bad stuff happened'
  27217. * // results[2].value = 'two'
  27218. * });
  27219. */
  27220. function reflect(fn) {
  27221. var _fn = wrapAsync(fn);
  27222. return initialParams(function reflectOn(args, reflectCallback) {
  27223. args.push(function callback(error, cbArg) {
  27224. if (error) {
  27225. reflectCallback(null, { error: error });
  27226. } else {
  27227. var value;
  27228. if (arguments.length <= 2) {
  27229. value = cbArg;
  27230. } else {
  27231. value = slice(arguments, 1);
  27232. }
  27233. reflectCallback(null, { value: value });
  27234. }
  27235. });
  27236. return _fn.apply(this, args);
  27237. });
  27238. }
  27239. /**
  27240. * A helper function that wraps an array or an object of functions with `reflect`.
  27241. *
  27242. * @name reflectAll
  27243. * @static
  27244. * @memberOf module:Utils
  27245. * @method
  27246. * @see [async.reflect]{@link module:Utils.reflect}
  27247. * @category Util
  27248. * @param {Array|Object|Iterable} tasks - The collection of
  27249. * [async functions]{@link AsyncFunction} to wrap in `async.reflect`.
  27250. * @returns {Array} Returns an array of async functions, each wrapped in
  27251. * `async.reflect`
  27252. * @example
  27253. *
  27254. * let tasks = [
  27255. * function(callback) {
  27256. * setTimeout(function() {
  27257. * callback(null, 'one');
  27258. * }, 200);
  27259. * },
  27260. * function(callback) {
  27261. * // do some more stuff but error ...
  27262. * callback(new Error('bad stuff happened'));
  27263. * },
  27264. * function(callback) {
  27265. * setTimeout(function() {
  27266. * callback(null, 'two');
  27267. * }, 100);
  27268. * }
  27269. * ];
  27270. *
  27271. * async.parallel(async.reflectAll(tasks),
  27272. * // optional callback
  27273. * function(err, results) {
  27274. * // values
  27275. * // results[0].value = 'one'
  27276. * // results[1].error = Error('bad stuff happened')
  27277. * // results[2].value = 'two'
  27278. * });
  27279. *
  27280. * // an example using an object instead of an array
  27281. * let tasks = {
  27282. * one: function(callback) {
  27283. * setTimeout(function() {
  27284. * callback(null, 'one');
  27285. * }, 200);
  27286. * },
  27287. * two: function(callback) {
  27288. * callback('two');
  27289. * },
  27290. * three: function(callback) {
  27291. * setTimeout(function() {
  27292. * callback(null, 'three');
  27293. * }, 100);
  27294. * }
  27295. * };
  27296. *
  27297. * async.parallel(async.reflectAll(tasks),
  27298. * // optional callback
  27299. * function(err, results) {
  27300. * // values
  27301. * // results.one.value = 'one'
  27302. * // results.two.error = 'two'
  27303. * // results.three.value = 'three'
  27304. * });
  27305. */
  27306. function reflectAll(tasks) {
  27307. var results;
  27308. if (isArray(tasks)) {
  27309. results = arrayMap(tasks, reflect);
  27310. } else {
  27311. results = {};
  27312. baseForOwn(tasks, function(task, key) {
  27313. results[key] = reflect.call(this, task);
  27314. });
  27315. }
  27316. return results;
  27317. }
  27318. function reject$1(eachfn, arr, iteratee, callback) {
  27319. _filter(eachfn, arr, function(value, cb) {
  27320. iteratee(value, function(err, v) {
  27321. cb(err, !v);
  27322. });
  27323. }, callback);
  27324. }
  27325. /**
  27326. * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test.
  27327. *
  27328. * @name reject
  27329. * @static
  27330. * @memberOf module:Collections
  27331. * @method
  27332. * @see [async.filter]{@link module:Collections.filter}
  27333. * @category Collection
  27334. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  27335. * @param {Function} iteratee - An async truth test to apply to each item in
  27336. * `coll`.
  27337. * The should complete with a boolean value as its `result`.
  27338. * Invoked with (item, callback).
  27339. * @param {Function} [callback] - A callback which is called after all the
  27340. * `iteratee` functions have finished. Invoked with (err, results).
  27341. * @example
  27342. *
  27343. * async.reject(['file1','file2','file3'], function(filePath, callback) {
  27344. * fs.access(filePath, function(err) {
  27345. * callback(null, !err)
  27346. * });
  27347. * }, function(err, results) {
  27348. * // results now equals an array of missing files
  27349. * createFiles(results);
  27350. * });
  27351. */
  27352. var reject = doParallel(reject$1);
  27353. /**
  27354. * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a
  27355. * time.
  27356. *
  27357. * @name rejectLimit
  27358. * @static
  27359. * @memberOf module:Collections
  27360. * @method
  27361. * @see [async.reject]{@link module:Collections.reject}
  27362. * @category Collection
  27363. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  27364. * @param {number} limit - The maximum number of async operations at a time.
  27365. * @param {Function} iteratee - An async truth test to apply to each item in
  27366. * `coll`.
  27367. * The should complete with a boolean value as its `result`.
  27368. * Invoked with (item, callback).
  27369. * @param {Function} [callback] - A callback which is called after all the
  27370. * `iteratee` functions have finished. Invoked with (err, results).
  27371. */
  27372. var rejectLimit = doParallelLimit(reject$1);
  27373. /**
  27374. * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time.
  27375. *
  27376. * @name rejectSeries
  27377. * @static
  27378. * @memberOf module:Collections
  27379. * @method
  27380. * @see [async.reject]{@link module:Collections.reject}
  27381. * @category Collection
  27382. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  27383. * @param {Function} iteratee - An async truth test to apply to each item in
  27384. * `coll`.
  27385. * The should complete with a boolean value as its `result`.
  27386. * Invoked with (item, callback).
  27387. * @param {Function} [callback] - A callback which is called after all the
  27388. * `iteratee` functions have finished. Invoked with (err, results).
  27389. */
  27390. var rejectSeries = doLimit(rejectLimit, 1);
  27391. /**
  27392. * Creates a function that returns `value`.
  27393. *
  27394. * @static
  27395. * @memberOf _
  27396. * @since 2.4.0
  27397. * @category Util
  27398. * @param {*} value The value to return from the new function.
  27399. * @returns {Function} Returns the new constant function.
  27400. * @example
  27401. *
  27402. * var objects = _.times(2, _.constant({ 'a': 1 }));
  27403. *
  27404. * console.log(objects);
  27405. * // => [{ 'a': 1 }, { 'a': 1 }]
  27406. *
  27407. * console.log(objects[0] === objects[1]);
  27408. * // => true
  27409. */
  27410. function constant$1(value) {
  27411. return function() {
  27412. return value;
  27413. };
  27414. }
  27415. /**
  27416. * Attempts to get a successful response from `task` no more than `times` times
  27417. * before returning an error. If the task is successful, the `callback` will be
  27418. * passed the result of the successful task. If all attempts fail, the callback
  27419. * will be passed the error and result (if any) of the final attempt.
  27420. *
  27421. * @name retry
  27422. * @static
  27423. * @memberOf module:ControlFlow
  27424. * @method
  27425. * @category Control Flow
  27426. * @see [async.retryable]{@link module:ControlFlow.retryable}
  27427. * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an
  27428. * object with `times` and `interval` or a number.
  27429. * * `times` - The number of attempts to make before giving up. The default
  27430. * is `5`.
  27431. * * `interval` - The time to wait between retries, in milliseconds. The
  27432. * default is `0`. The interval may also be specified as a function of the
  27433. * retry count (see example).
  27434. * * `errorFilter` - An optional synchronous function that is invoked on
  27435. * erroneous result. If it returns `true` the retry attempts will continue;
  27436. * if the function returns `false` the retry flow is aborted with the current
  27437. * attempt's error and result being returned to the final callback.
  27438. * Invoked with (err).
  27439. * * If `opts` is a number, the number specifies the number of times to retry,
  27440. * with the default interval of `0`.
  27441. * @param {AsyncFunction} task - An async function to retry.
  27442. * Invoked with (callback).
  27443. * @param {Function} [callback] - An optional callback which is called when the
  27444. * task has succeeded, or after the final failed attempt. It receives the `err`
  27445. * and `result` arguments of the last attempt at completing the `task`. Invoked
  27446. * with (err, results).
  27447. *
  27448. * @example
  27449. *
  27450. * // The `retry` function can be used as a stand-alone control flow by passing
  27451. * // a callback, as shown below:
  27452. *
  27453. * // try calling apiMethod 3 times
  27454. * async.retry(3, apiMethod, function(err, result) {
  27455. * // do something with the result
  27456. * });
  27457. *
  27458. * // try calling apiMethod 3 times, waiting 200 ms between each retry
  27459. * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {
  27460. * // do something with the result
  27461. * });
  27462. *
  27463. * // try calling apiMethod 10 times with exponential backoff
  27464. * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds)
  27465. * async.retry({
  27466. * times: 10,
  27467. * interval: function(retryCount) {
  27468. * return 50 * Math.pow(2, retryCount);
  27469. * }
  27470. * }, apiMethod, function(err, result) {
  27471. * // do something with the result
  27472. * });
  27473. *
  27474. * // try calling apiMethod the default 5 times no delay between each retry
  27475. * async.retry(apiMethod, function(err, result) {
  27476. * // do something with the result
  27477. * });
  27478. *
  27479. * // try calling apiMethod only when error condition satisfies, all other
  27480. * // errors will abort the retry control flow and return to final callback
  27481. * async.retry({
  27482. * errorFilter: function(err) {
  27483. * return err.message === 'Temporary error'; // only retry on a specific error
  27484. * }
  27485. * }, apiMethod, function(err, result) {
  27486. * // do something with the result
  27487. * });
  27488. *
  27489. * // to retry individual methods that are not as reliable within other
  27490. * // control flow functions, use the `retryable` wrapper:
  27491. * async.auto({
  27492. * users: api.getUsers.bind(api),
  27493. * payments: async.retryable(3, api.getPayments.bind(api))
  27494. * }, function(err, results) {
  27495. * // do something with the results
  27496. * });
  27497. *
  27498. */
  27499. function retry(opts, task, callback) {
  27500. var DEFAULT_TIMES = 5;
  27501. var DEFAULT_INTERVAL = 0;
  27502. var options = {
  27503. times: DEFAULT_TIMES,
  27504. intervalFunc: constant$1(DEFAULT_INTERVAL)
  27505. };
  27506. function parseTimes(acc, t) {
  27507. if (typeof t === 'object') {
  27508. acc.times = +t.times || DEFAULT_TIMES;
  27509. acc.intervalFunc = typeof t.interval === 'function' ?
  27510. t.interval :
  27511. constant$1(+t.interval || DEFAULT_INTERVAL);
  27512. acc.errorFilter = t.errorFilter;
  27513. } else if (typeof t === 'number' || typeof t === 'string') {
  27514. acc.times = +t || DEFAULT_TIMES;
  27515. } else {
  27516. throw new Error("Invalid arguments for async.retry");
  27517. }
  27518. }
  27519. if (arguments.length < 3 && typeof opts === 'function') {
  27520. callback = task || noop;
  27521. task = opts;
  27522. } else {
  27523. parseTimes(options, opts);
  27524. callback = callback || noop;
  27525. }
  27526. if (typeof task !== 'function') {
  27527. throw new Error("Invalid arguments for async.retry");
  27528. }
  27529. var _task = wrapAsync(task);
  27530. var attempt = 1;
  27531. function retryAttempt() {
  27532. _task(function(err) {
  27533. if (err && attempt++ < options.times &&
  27534. (typeof options.errorFilter != 'function' ||
  27535. options.errorFilter(err))) {
  27536. setTimeout(retryAttempt, options.intervalFunc(attempt));
  27537. } else {
  27538. callback.apply(null, arguments);
  27539. }
  27540. });
  27541. }
  27542. retryAttempt();
  27543. }
  27544. /**
  27545. * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method
  27546. * wraps a task and makes it retryable, rather than immediately calling it
  27547. * with retries.
  27548. *
  27549. * @name retryable
  27550. * @static
  27551. * @memberOf module:ControlFlow
  27552. * @method
  27553. * @see [async.retry]{@link module:ControlFlow.retry}
  27554. * @category Control Flow
  27555. * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional
  27556. * options, exactly the same as from `retry`
  27557. * @param {AsyncFunction} task - the asynchronous function to wrap.
  27558. * This function will be passed any arguments passed to the returned wrapper.
  27559. * Invoked with (...args, callback).
  27560. * @returns {AsyncFunction} The wrapped function, which when invoked, will
  27561. * retry on an error, based on the parameters specified in `opts`.
  27562. * This function will accept the same parameters as `task`.
  27563. * @example
  27564. *
  27565. * async.auto({
  27566. * dep1: async.retryable(3, getFromFlakyService),
  27567. * process: ["dep1", async.retryable(3, function (results, cb) {
  27568. * maybeProcessData(results.dep1, cb);
  27569. * })]
  27570. * }, callback);
  27571. */
  27572. var retryable = function (opts, task) {
  27573. if (!task) {
  27574. task = opts;
  27575. opts = null;
  27576. }
  27577. var _task = wrapAsync(task);
  27578. return initialParams(function (args, callback) {
  27579. function taskFn(cb) {
  27580. _task.apply(null, args.concat(cb));
  27581. }
  27582. if (opts) retry(opts, taskFn, callback);
  27583. else retry(taskFn, callback);
  27584. });
  27585. };
  27586. /**
  27587. * Run the functions in the `tasks` collection in series, each one running once
  27588. * the previous function has completed. If any functions in the series pass an
  27589. * error to its callback, no more functions are run, and `callback` is
  27590. * immediately called with the value of the error. Otherwise, `callback`
  27591. * receives an array of results when `tasks` have completed.
  27592. *
  27593. * It is also possible to use an object instead of an array. Each property will
  27594. * be run as a function, and the results will be passed to the final `callback`
  27595. * as an object instead of an array. This can be a more readable way of handling
  27596. * results from {@link async.series}.
  27597. *
  27598. * **Note** that while many implementations preserve the order of object
  27599. * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)
  27600. * explicitly states that
  27601. *
  27602. * > The mechanics and order of enumerating the properties is not specified.
  27603. *
  27604. * So if you rely on the order in which your series of functions are executed,
  27605. * and want this to work on all platforms, consider using an array.
  27606. *
  27607. * @name series
  27608. * @static
  27609. * @memberOf module:ControlFlow
  27610. * @method
  27611. * @category Control Flow
  27612. * @param {Array|Iterable|Object} tasks - A collection containing
  27613. * [async functions]{@link AsyncFunction} to run in series.
  27614. * Each function can complete with any number of optional `result` values.
  27615. * @param {Function} [callback] - An optional callback to run once all the
  27616. * functions have completed. This function gets a results array (or object)
  27617. * containing all the result arguments passed to the `task` callbacks. Invoked
  27618. * with (err, result).
  27619. * @example
  27620. * async.series([
  27621. * function(callback) {
  27622. * // do some stuff ...
  27623. * callback(null, 'one');
  27624. * },
  27625. * function(callback) {
  27626. * // do some more stuff ...
  27627. * callback(null, 'two');
  27628. * }
  27629. * ],
  27630. * // optional callback
  27631. * function(err, results) {
  27632. * // results is now equal to ['one', 'two']
  27633. * });
  27634. *
  27635. * async.series({
  27636. * one: function(callback) {
  27637. * setTimeout(function() {
  27638. * callback(null, 1);
  27639. * }, 200);
  27640. * },
  27641. * two: function(callback){
  27642. * setTimeout(function() {
  27643. * callback(null, 2);
  27644. * }, 100);
  27645. * }
  27646. * }, function(err, results) {
  27647. * // results is now equal to: {one: 1, two: 2}
  27648. * });
  27649. */
  27650. function series(tasks, callback) {
  27651. _parallel(eachOfSeries, tasks, callback);
  27652. }
  27653. /**
  27654. * Returns `true` if at least one element in the `coll` satisfies an async test.
  27655. * If any iteratee call returns `true`, the main `callback` is immediately
  27656. * called.
  27657. *
  27658. * @name some
  27659. * @static
  27660. * @memberOf module:Collections
  27661. * @method
  27662. * @alias any
  27663. * @category Collection
  27664. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  27665. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  27666. * in the collections in parallel.
  27667. * The iteratee should complete with a boolean `result` value.
  27668. * Invoked with (item, callback).
  27669. * @param {Function} [callback] - A callback which is called as soon as any
  27670. * iteratee returns `true`, or after all the iteratee functions have finished.
  27671. * Result will be either `true` or `false` depending on the values of the async
  27672. * tests. Invoked with (err, result).
  27673. * @example
  27674. *
  27675. * async.some(['file1','file2','file3'], function(filePath, callback) {
  27676. * fs.access(filePath, function(err) {
  27677. * callback(null, !err)
  27678. * });
  27679. * }, function(err, result) {
  27680. * // if result is true then at least one of the files exists
  27681. * });
  27682. */
  27683. var some = doParallel(_createTester(Boolean, identity));
  27684. /**
  27685. * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time.
  27686. *
  27687. * @name someLimit
  27688. * @static
  27689. * @memberOf module:Collections
  27690. * @method
  27691. * @see [async.some]{@link module:Collections.some}
  27692. * @alias anyLimit
  27693. * @category Collection
  27694. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  27695. * @param {number} limit - The maximum number of async operations at a time.
  27696. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  27697. * in the collections in parallel.
  27698. * The iteratee should complete with a boolean `result` value.
  27699. * Invoked with (item, callback).
  27700. * @param {Function} [callback] - A callback which is called as soon as any
  27701. * iteratee returns `true`, or after all the iteratee functions have finished.
  27702. * Result will be either `true` or `false` depending on the values of the async
  27703. * tests. Invoked with (err, result).
  27704. */
  27705. var someLimit = doParallelLimit(_createTester(Boolean, identity));
  27706. /**
  27707. * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time.
  27708. *
  27709. * @name someSeries
  27710. * @static
  27711. * @memberOf module:Collections
  27712. * @method
  27713. * @see [async.some]{@link module:Collections.some}
  27714. * @alias anySeries
  27715. * @category Collection
  27716. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  27717. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  27718. * in the collections in series.
  27719. * The iteratee should complete with a boolean `result` value.
  27720. * Invoked with (item, callback).
  27721. * @param {Function} [callback] - A callback which is called as soon as any
  27722. * iteratee returns `true`, or after all the iteratee functions have finished.
  27723. * Result will be either `true` or `false` depending on the values of the async
  27724. * tests. Invoked with (err, result).
  27725. */
  27726. var someSeries = doLimit(someLimit, 1);
  27727. /**
  27728. * Sorts a list by the results of running each `coll` value through an async
  27729. * `iteratee`.
  27730. *
  27731. * @name sortBy
  27732. * @static
  27733. * @memberOf module:Collections
  27734. * @method
  27735. * @category Collection
  27736. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  27737. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  27738. * `coll`.
  27739. * The iteratee should complete with a value to use as the sort criteria as
  27740. * its `result`.
  27741. * Invoked with (item, callback).
  27742. * @param {Function} callback - A callback which is called after all the
  27743. * `iteratee` functions have finished, or an error occurs. Results is the items
  27744. * from the original `coll` sorted by the values returned by the `iteratee`
  27745. * calls. Invoked with (err, results).
  27746. * @example
  27747. *
  27748. * async.sortBy(['file1','file2','file3'], function(file, callback) {
  27749. * fs.stat(file, function(err, stats) {
  27750. * callback(err, stats.mtime);
  27751. * });
  27752. * }, function(err, results) {
  27753. * // results is now the original array of files sorted by
  27754. * // modified date
  27755. * });
  27756. *
  27757. * // By modifying the callback parameter the
  27758. * // sorting order can be influenced:
  27759. *
  27760. * // ascending order
  27761. * async.sortBy([1,9,3,5], function(x, callback) {
  27762. * callback(null, x);
  27763. * }, function(err,result) {
  27764. * // result callback
  27765. * });
  27766. *
  27767. * // descending order
  27768. * async.sortBy([1,9,3,5], function(x, callback) {
  27769. * callback(null, x*-1); //<- x*-1 instead of x, turns the order around
  27770. * }, function(err,result) {
  27771. * // result callback
  27772. * });
  27773. */
  27774. function sortBy (coll, iteratee, callback) {
  27775. var _iteratee = wrapAsync(iteratee);
  27776. map(coll, function (x, callback) {
  27777. _iteratee(x, function (err, criteria) {
  27778. if (err) return callback(err);
  27779. callback(null, {value: x, criteria: criteria});
  27780. });
  27781. }, function (err, results) {
  27782. if (err) return callback(err);
  27783. callback(null, arrayMap(results.sort(comparator), baseProperty('value')));
  27784. });
  27785. function comparator(left, right) {
  27786. var a = left.criteria, b = right.criteria;
  27787. return a < b ? -1 : a > b ? 1 : 0;
  27788. }
  27789. }
  27790. /**
  27791. * Sets a time limit on an asynchronous function. If the function does not call
  27792. * its callback within the specified milliseconds, it will be called with a
  27793. * timeout error. The code property for the error object will be `'ETIMEDOUT'`.
  27794. *
  27795. * @name timeout
  27796. * @static
  27797. * @memberOf module:Utils
  27798. * @method
  27799. * @category Util
  27800. * @param {AsyncFunction} asyncFn - The async function to limit in time.
  27801. * @param {number} milliseconds - The specified time limit.
  27802. * @param {*} [info] - Any variable you want attached (`string`, `object`, etc)
  27803. * to timeout Error for more information..
  27804. * @returns {AsyncFunction} Returns a wrapped function that can be used with any
  27805. * of the control flow functions.
  27806. * Invoke this function with the same parameters as you would `asyncFunc`.
  27807. * @example
  27808. *
  27809. * function myFunction(foo, callback) {
  27810. * doAsyncTask(foo, function(err, data) {
  27811. * // handle errors
  27812. * if (err) return callback(err);
  27813. *
  27814. * // do some stuff ...
  27815. *
  27816. * // return processed data
  27817. * return callback(null, data);
  27818. * });
  27819. * }
  27820. *
  27821. * var wrapped = async.timeout(myFunction, 1000);
  27822. *
  27823. * // call `wrapped` as you would `myFunction`
  27824. * wrapped({ bar: 'bar' }, function(err, data) {
  27825. * // if `myFunction` takes < 1000 ms to execute, `err`
  27826. * // and `data` will have their expected values
  27827. *
  27828. * // else `err` will be an Error with the code 'ETIMEDOUT'
  27829. * });
  27830. */
  27831. function timeout(asyncFn, milliseconds, info) {
  27832. var fn = wrapAsync(asyncFn);
  27833. return initialParams(function (args, callback) {
  27834. var timedOut = false;
  27835. var timer;
  27836. function timeoutCallback() {
  27837. var name = asyncFn.name || 'anonymous';
  27838. var error = new Error('Callback function "' + name + '" timed out.');
  27839. error.code = 'ETIMEDOUT';
  27840. if (info) {
  27841. error.info = info;
  27842. }
  27843. timedOut = true;
  27844. callback(error);
  27845. }
  27846. args.push(function () {
  27847. if (!timedOut) {
  27848. callback.apply(null, arguments);
  27849. clearTimeout(timer);
  27850. }
  27851. });
  27852. // setup timer and call original function
  27853. timer = setTimeout(timeoutCallback, milliseconds);
  27854. fn.apply(null, args);
  27855. });
  27856. }
  27857. /* Built-in method references for those with the same name as other `lodash` methods. */
  27858. var nativeCeil = Math.ceil;
  27859. var nativeMax = Math.max;
  27860. /**
  27861. * The base implementation of `_.range` and `_.rangeRight` which doesn't
  27862. * coerce arguments.
  27863. *
  27864. * @private
  27865. * @param {number} start The start of the range.
  27866. * @param {number} end The end of the range.
  27867. * @param {number} step The value to increment or decrement by.
  27868. * @param {boolean} [fromRight] Specify iterating from right to left.
  27869. * @returns {Array} Returns the range of numbers.
  27870. */
  27871. function baseRange(start, end, step, fromRight) {
  27872. var index = -1,
  27873. length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
  27874. result = Array(length);
  27875. while (length--) {
  27876. result[fromRight ? length : ++index] = start;
  27877. start += step;
  27878. }
  27879. return result;
  27880. }
  27881. /**
  27882. * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a
  27883. * time.
  27884. *
  27885. * @name timesLimit
  27886. * @static
  27887. * @memberOf module:ControlFlow
  27888. * @method
  27889. * @see [async.times]{@link module:ControlFlow.times}
  27890. * @category Control Flow
  27891. * @param {number} count - The number of times to run the function.
  27892. * @param {number} limit - The maximum number of async operations at a time.
  27893. * @param {AsyncFunction} iteratee - The async function to call `n` times.
  27894. * Invoked with the iteration index and a callback: (n, next).
  27895. * @param {Function} callback - see [async.map]{@link module:Collections.map}.
  27896. */
  27897. function timeLimit(count, limit, iteratee, callback) {
  27898. var _iteratee = wrapAsync(iteratee);
  27899. mapLimit(baseRange(0, count, 1), limit, _iteratee, callback);
  27900. }
  27901. /**
  27902. * Calls the `iteratee` function `n` times, and accumulates results in the same
  27903. * manner you would use with [map]{@link module:Collections.map}.
  27904. *
  27905. * @name times
  27906. * @static
  27907. * @memberOf module:ControlFlow
  27908. * @method
  27909. * @see [async.map]{@link module:Collections.map}
  27910. * @category Control Flow
  27911. * @param {number} n - The number of times to run the function.
  27912. * @param {AsyncFunction} iteratee - The async function to call `n` times.
  27913. * Invoked with the iteration index and a callback: (n, next).
  27914. * @param {Function} callback - see {@link module:Collections.map}.
  27915. * @example
  27916. *
  27917. * // Pretend this is some complicated async factory
  27918. * var createUser = function(id, callback) {
  27919. * callback(null, {
  27920. * id: 'user' + id
  27921. * });
  27922. * };
  27923. *
  27924. * // generate 5 users
  27925. * async.times(5, function(n, next) {
  27926. * createUser(n, function(err, user) {
  27927. * next(err, user);
  27928. * });
  27929. * }, function(err, users) {
  27930. * // we should now have 5 users
  27931. * });
  27932. */
  27933. var times = doLimit(timeLimit, Infinity);
  27934. /**
  27935. * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time.
  27936. *
  27937. * @name timesSeries
  27938. * @static
  27939. * @memberOf module:ControlFlow
  27940. * @method
  27941. * @see [async.times]{@link module:ControlFlow.times}
  27942. * @category Control Flow
  27943. * @param {number} n - The number of times to run the function.
  27944. * @param {AsyncFunction} iteratee - The async function to call `n` times.
  27945. * Invoked with the iteration index and a callback: (n, next).
  27946. * @param {Function} callback - see {@link module:Collections.map}.
  27947. */
  27948. var timesSeries = doLimit(timeLimit, 1);
  27949. /**
  27950. * A relative of `reduce`. Takes an Object or Array, and iterates over each
  27951. * element in series, each step potentially mutating an `accumulator` value.
  27952. * The type of the accumulator defaults to the type of collection passed in.
  27953. *
  27954. * @name transform
  27955. * @static
  27956. * @memberOf module:Collections
  27957. * @method
  27958. * @category Collection
  27959. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  27960. * @param {*} [accumulator] - The initial state of the transform. If omitted,
  27961. * it will default to an empty Object or Array, depending on the type of `coll`
  27962. * @param {AsyncFunction} iteratee - A function applied to each item in the
  27963. * collection that potentially modifies the accumulator.
  27964. * Invoked with (accumulator, item, key, callback).
  27965. * @param {Function} [callback] - A callback which is called after all the
  27966. * `iteratee` functions have finished. Result is the transformed accumulator.
  27967. * Invoked with (err, result).
  27968. * @example
  27969. *
  27970. * async.transform([1,2,3], function(acc, item, index, callback) {
  27971. * // pointless async:
  27972. * process.nextTick(function() {
  27973. * acc.push(item * 2)
  27974. * callback(null)
  27975. * });
  27976. * }, function(err, result) {
  27977. * // result is now equal to [2, 4, 6]
  27978. * });
  27979. *
  27980. * @example
  27981. *
  27982. * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) {
  27983. * setImmediate(function () {
  27984. * obj[key] = val * 2;
  27985. * callback();
  27986. * })
  27987. * }, function (err, result) {
  27988. * // result is equal to {a: 2, b: 4, c: 6}
  27989. * })
  27990. */
  27991. function transform (coll, accumulator, iteratee, callback) {
  27992. if (arguments.length <= 3) {
  27993. callback = iteratee;
  27994. iteratee = accumulator;
  27995. accumulator = isArray(coll) ? [] : {};
  27996. }
  27997. callback = once(callback || noop);
  27998. var _iteratee = wrapAsync(iteratee);
  27999. eachOf(coll, function(v, k, cb) {
  28000. _iteratee(accumulator, v, k, cb);
  28001. }, function(err) {
  28002. callback(err, accumulator);
  28003. });
  28004. }
  28005. /**
  28006. * It runs each task in series but stops whenever any of the functions were
  28007. * successful. If one of the tasks were successful, the `callback` will be
  28008. * passed the result of the successful task. If all tasks fail, the callback
  28009. * will be passed the error and result (if any) of the final attempt.
  28010. *
  28011. * @name tryEach
  28012. * @static
  28013. * @memberOf module:ControlFlow
  28014. * @method
  28015. * @category Control Flow
  28016. * @param {Array|Iterable|Object} tasks - A collection containing functions to
  28017. * run, each function is passed a `callback(err, result)` it must call on
  28018. * completion with an error `err` (which can be `null`) and an optional `result`
  28019. * value.
  28020. * @param {Function} [callback] - An optional callback which is called when one
  28021. * of the tasks has succeeded, or all have failed. It receives the `err` and
  28022. * `result` arguments of the last attempt at completing the `task`. Invoked with
  28023. * (err, results).
  28024. * @example
  28025. * async.tryEach([
  28026. * function getDataFromFirstWebsite(callback) {
  28027. * // Try getting the data from the first website
  28028. * callback(err, data);
  28029. * },
  28030. * function getDataFromSecondWebsite(callback) {
  28031. * // First website failed,
  28032. * // Try getting the data from the backup website
  28033. * callback(err, data);
  28034. * }
  28035. * ],
  28036. * // optional callback
  28037. * function(err, results) {
  28038. * Now do something with the data.
  28039. * });
  28040. *
  28041. */
  28042. function tryEach(tasks, callback) {
  28043. var error = null;
  28044. var result;
  28045. callback = callback || noop;
  28046. eachSeries(tasks, function(task, callback) {
  28047. wrapAsync(task)(function (err, res/*, ...args*/) {
  28048. if (arguments.length > 2) {
  28049. result = slice(arguments, 1);
  28050. } else {
  28051. result = res;
  28052. }
  28053. error = err;
  28054. callback(!err);
  28055. });
  28056. }, function () {
  28057. callback(error, result);
  28058. });
  28059. }
  28060. /**
  28061. * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original,
  28062. * unmemoized form. Handy for testing.
  28063. *
  28064. * @name unmemoize
  28065. * @static
  28066. * @memberOf module:Utils
  28067. * @method
  28068. * @see [async.memoize]{@link module:Utils.memoize}
  28069. * @category Util
  28070. * @param {AsyncFunction} fn - the memoized function
  28071. * @returns {AsyncFunction} a function that calls the original unmemoized function
  28072. */
  28073. function unmemoize(fn) {
  28074. return function () {
  28075. return (fn.unmemoized || fn).apply(null, arguments);
  28076. };
  28077. }
  28078. /**
  28079. * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when
  28080. * stopped, or an error occurs.
  28081. *
  28082. * @name whilst
  28083. * @static
  28084. * @memberOf module:ControlFlow
  28085. * @method
  28086. * @category Control Flow
  28087. * @param {Function} test - synchronous truth test to perform before each
  28088. * execution of `iteratee`. Invoked with ().
  28089. * @param {AsyncFunction} iteratee - An async function which is called each time
  28090. * `test` passes. Invoked with (callback).
  28091. * @param {Function} [callback] - A callback which is called after the test
  28092. * function has failed and repeated execution of `iteratee` has stopped. `callback`
  28093. * will be passed an error and any arguments passed to the final `iteratee`'s
  28094. * callback. Invoked with (err, [results]);
  28095. * @returns undefined
  28096. * @example
  28097. *
  28098. * var count = 0;
  28099. * async.whilst(
  28100. * function() { return count < 5; },
  28101. * function(callback) {
  28102. * count++;
  28103. * setTimeout(function() {
  28104. * callback(null, count);
  28105. * }, 1000);
  28106. * },
  28107. * function (err, n) {
  28108. * // 5 seconds have passed, n = 5
  28109. * }
  28110. * );
  28111. */
  28112. function whilst(test, iteratee, callback) {
  28113. callback = onlyOnce(callback || noop);
  28114. var _iteratee = wrapAsync(iteratee);
  28115. if (!test()) return callback(null);
  28116. var next = function(err/*, ...args*/) {
  28117. if (err) return callback(err);
  28118. if (test()) return _iteratee(next);
  28119. var args = slice(arguments, 1);
  28120. callback.apply(null, [null].concat(args));
  28121. };
  28122. _iteratee(next);
  28123. }
  28124. /**
  28125. * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when
  28126. * stopped, or an error occurs. `callback` will be passed an error and any
  28127. * arguments passed to the final `iteratee`'s callback.
  28128. *
  28129. * The inverse of [whilst]{@link module:ControlFlow.whilst}.
  28130. *
  28131. * @name until
  28132. * @static
  28133. * @memberOf module:ControlFlow
  28134. * @method
  28135. * @see [async.whilst]{@link module:ControlFlow.whilst}
  28136. * @category Control Flow
  28137. * @param {Function} test - synchronous truth test to perform before each
  28138. * execution of `iteratee`. Invoked with ().
  28139. * @param {AsyncFunction} iteratee - An async function which is called each time
  28140. * `test` fails. Invoked with (callback).
  28141. * @param {Function} [callback] - A callback which is called after the test
  28142. * function has passed and repeated execution of `iteratee` has stopped. `callback`
  28143. * will be passed an error and any arguments passed to the final `iteratee`'s
  28144. * callback. Invoked with (err, [results]);
  28145. */
  28146. function until(test, iteratee, callback) {
  28147. whilst(function() {
  28148. return !test.apply(this, arguments);
  28149. }, iteratee, callback);
  28150. }
  28151. /**
  28152. * Runs the `tasks` array of functions in series, each passing their results to
  28153. * the next in the array. However, if any of the `tasks` pass an error to their
  28154. * own callback, the next function is not executed, and the main `callback` is
  28155. * immediately called with the error.
  28156. *
  28157. * @name waterfall
  28158. * @static
  28159. * @memberOf module:ControlFlow
  28160. * @method
  28161. * @category Control Flow
  28162. * @param {Array} tasks - An array of [async functions]{@link AsyncFunction}
  28163. * to run.
  28164. * Each function should complete with any number of `result` values.
  28165. * The `result` values will be passed as arguments, in order, to the next task.
  28166. * @param {Function} [callback] - An optional callback to run once all the
  28167. * functions have completed. This will be passed the results of the last task's
  28168. * callback. Invoked with (err, [results]).
  28169. * @returns undefined
  28170. * @example
  28171. *
  28172. * async.waterfall([
  28173. * function(callback) {
  28174. * callback(null, 'one', 'two');
  28175. * },
  28176. * function(arg1, arg2, callback) {
  28177. * // arg1 now equals 'one' and arg2 now equals 'two'
  28178. * callback(null, 'three');
  28179. * },
  28180. * function(arg1, callback) {
  28181. * // arg1 now equals 'three'
  28182. * callback(null, 'done');
  28183. * }
  28184. * ], function (err, result) {
  28185. * // result now equals 'done'
  28186. * });
  28187. *
  28188. * // Or, with named functions:
  28189. * async.waterfall([
  28190. * myFirstFunction,
  28191. * mySecondFunction,
  28192. * myLastFunction,
  28193. * ], function (err, result) {
  28194. * // result now equals 'done'
  28195. * });
  28196. * function myFirstFunction(callback) {
  28197. * callback(null, 'one', 'two');
  28198. * }
  28199. * function mySecondFunction(arg1, arg2, callback) {
  28200. * // arg1 now equals 'one' and arg2 now equals 'two'
  28201. * callback(null, 'three');
  28202. * }
  28203. * function myLastFunction(arg1, callback) {
  28204. * // arg1 now equals 'three'
  28205. * callback(null, 'done');
  28206. * }
  28207. */
  28208. var waterfall = function(tasks, callback) {
  28209. callback = once(callback || noop);
  28210. if (!isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions'));
  28211. if (!tasks.length) return callback();
  28212. var taskIndex = 0;
  28213. function nextTask(args) {
  28214. var task = wrapAsync(tasks[taskIndex++]);
  28215. args.push(onlyOnce(next));
  28216. task.apply(null, args);
  28217. }
  28218. function next(err/*, ...args*/) {
  28219. if (err || taskIndex === tasks.length) {
  28220. return callback.apply(null, arguments);
  28221. }
  28222. nextTask(slice(arguments, 1));
  28223. }
  28224. nextTask([]);
  28225. };
  28226. /**
  28227. * An "async function" in the context of Async is an asynchronous function with
  28228. * a variable number of parameters, with the final parameter being a callback.
  28229. * (`function (arg1, arg2, ..., callback) {}`)
  28230. * The final callback is of the form `callback(err, results...)`, which must be
  28231. * called once the function is completed. The callback should be called with a
  28232. * Error as its first argument to signal that an error occurred.
  28233. * Otherwise, if no error occurred, it should be called with `null` as the first
  28234. * argument, and any additional `result` arguments that may apply, to signal
  28235. * successful completion.
  28236. * The callback must be called exactly once, ideally on a later tick of the
  28237. * JavaScript event loop.
  28238. *
  28239. * This type of function is also referred to as a "Node-style async function",
  28240. * or a "continuation passing-style function" (CPS). Most of the methods of this
  28241. * library are themselves CPS/Node-style async functions, or functions that
  28242. * return CPS/Node-style async functions.
  28243. *
  28244. * Wherever we accept a Node-style async function, we also directly accept an
  28245. * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}.
  28246. * In this case, the `async` function will not be passed a final callback
  28247. * argument, and any thrown error will be used as the `err` argument of the
  28248. * implicit callback, and the return value will be used as the `result` value.
  28249. * (i.e. a `rejected` of the returned Promise becomes the `err` callback
  28250. * argument, and a `resolved` value becomes the `result`.)
  28251. *
  28252. * Note, due to JavaScript limitations, we can only detect native `async`
  28253. * functions and not transpilied implementations.
  28254. * Your environment must have `async`/`await` support for this to work.
  28255. * (e.g. Node > v7.6, or a recent version of a modern browser).
  28256. * If you are using `async` functions through a transpiler (e.g. Babel), you
  28257. * must still wrap the function with [asyncify]{@link module:Utils.asyncify},
  28258. * because the `async function` will be compiled to an ordinary function that
  28259. * returns a promise.
  28260. *
  28261. * @typedef {Function} AsyncFunction
  28262. * @static
  28263. */
  28264. /**
  28265. * Async is a utility module which provides straight-forward, powerful functions
  28266. * for working with asynchronous JavaScript. Although originally designed for
  28267. * use with [Node.js](http://nodejs.org) and installable via
  28268. * `npm install --save async`, it can also be used directly in the browser.
  28269. * @module async
  28270. * @see AsyncFunction
  28271. */
  28272. /**
  28273. * A collection of `async` functions for manipulating collections, such as
  28274. * arrays and objects.
  28275. * @module Collections
  28276. */
  28277. /**
  28278. * A collection of `async` functions for controlling the flow through a script.
  28279. * @module ControlFlow
  28280. */
  28281. /**
  28282. * A collection of `async` utility functions.
  28283. * @module Utils
  28284. */
  28285. var index = {
  28286. apply: apply,
  28287. applyEach: applyEach,
  28288. applyEachSeries: applyEachSeries,
  28289. asyncify: asyncify,
  28290. auto: auto,
  28291. autoInject: autoInject,
  28292. cargo: cargo,
  28293. compose: compose,
  28294. concat: concat,
  28295. concatLimit: concatLimit,
  28296. concatSeries: concatSeries,
  28297. constant: constant,
  28298. detect: detect,
  28299. detectLimit: detectLimit,
  28300. detectSeries: detectSeries,
  28301. dir: dir,
  28302. doDuring: doDuring,
  28303. doUntil: doUntil,
  28304. doWhilst: doWhilst,
  28305. during: during,
  28306. each: eachLimit,
  28307. eachLimit: eachLimit$1,
  28308. eachOf: eachOf,
  28309. eachOfLimit: eachOfLimit,
  28310. eachOfSeries: eachOfSeries,
  28311. eachSeries: eachSeries,
  28312. ensureAsync: ensureAsync,
  28313. every: every,
  28314. everyLimit: everyLimit,
  28315. everySeries: everySeries,
  28316. filter: filter,
  28317. filterLimit: filterLimit,
  28318. filterSeries: filterSeries,
  28319. forever: forever,
  28320. groupBy: groupBy,
  28321. groupByLimit: groupByLimit,
  28322. groupBySeries: groupBySeries,
  28323. log: log,
  28324. map: map,
  28325. mapLimit: mapLimit,
  28326. mapSeries: mapSeries,
  28327. mapValues: mapValues,
  28328. mapValuesLimit: mapValuesLimit,
  28329. mapValuesSeries: mapValuesSeries,
  28330. memoize: memoize,
  28331. nextTick: nextTick,
  28332. parallel: parallelLimit,
  28333. parallelLimit: parallelLimit$1,
  28334. priorityQueue: priorityQueue,
  28335. queue: queue$1,
  28336. race: race,
  28337. reduce: reduce,
  28338. reduceRight: reduceRight,
  28339. reflect: reflect,
  28340. reflectAll: reflectAll,
  28341. reject: reject,
  28342. rejectLimit: rejectLimit,
  28343. rejectSeries: rejectSeries,
  28344. retry: retry,
  28345. retryable: retryable,
  28346. seq: seq,
  28347. series: series,
  28348. setImmediate: setImmediate$1,
  28349. some: some,
  28350. someLimit: someLimit,
  28351. someSeries: someSeries,
  28352. sortBy: sortBy,
  28353. timeout: timeout,
  28354. times: times,
  28355. timesLimit: timeLimit,
  28356. timesSeries: timesSeries,
  28357. transform: transform,
  28358. tryEach: tryEach,
  28359. unmemoize: unmemoize,
  28360. until: until,
  28361. waterfall: waterfall,
  28362. whilst: whilst,
  28363. // aliases
  28364. all: every,
  28365. allLimit: everyLimit,
  28366. allSeries: everySeries,
  28367. any: some,
  28368. anyLimit: someLimit,
  28369. anySeries: someSeries,
  28370. find: detect,
  28371. findLimit: detectLimit,
  28372. findSeries: detectSeries,
  28373. forEach: eachLimit,
  28374. forEachSeries: eachSeries,
  28375. forEachLimit: eachLimit$1,
  28376. forEachOf: eachOf,
  28377. forEachOfSeries: eachOfSeries,
  28378. forEachOfLimit: eachOfLimit,
  28379. inject: reduce,
  28380. foldl: reduce,
  28381. foldr: reduceRight,
  28382. select: filter,
  28383. selectLimit: filterLimit,
  28384. selectSeries: filterSeries,
  28385. wrapSync: asyncify
  28386. };
  28387. exports['default'] = index;
  28388. exports.apply = apply;
  28389. exports.applyEach = applyEach;
  28390. exports.applyEachSeries = applyEachSeries;
  28391. exports.asyncify = asyncify;
  28392. exports.auto = auto;
  28393. exports.autoInject = autoInject;
  28394. exports.cargo = cargo;
  28395. exports.compose = compose;
  28396. exports.concat = concat;
  28397. exports.concatLimit = concatLimit;
  28398. exports.concatSeries = concatSeries;
  28399. exports.constant = constant;
  28400. exports.detect = detect;
  28401. exports.detectLimit = detectLimit;
  28402. exports.detectSeries = detectSeries;
  28403. exports.dir = dir;
  28404. exports.doDuring = doDuring;
  28405. exports.doUntil = doUntil;
  28406. exports.doWhilst = doWhilst;
  28407. exports.during = during;
  28408. exports.each = eachLimit;
  28409. exports.eachLimit = eachLimit$1;
  28410. exports.eachOf = eachOf;
  28411. exports.eachOfLimit = eachOfLimit;
  28412. exports.eachOfSeries = eachOfSeries;
  28413. exports.eachSeries = eachSeries;
  28414. exports.ensureAsync = ensureAsync;
  28415. exports.every = every;
  28416. exports.everyLimit = everyLimit;
  28417. exports.everySeries = everySeries;
  28418. exports.filter = filter;
  28419. exports.filterLimit = filterLimit;
  28420. exports.filterSeries = filterSeries;
  28421. exports.forever = forever;
  28422. exports.groupBy = groupBy;
  28423. exports.groupByLimit = groupByLimit;
  28424. exports.groupBySeries = groupBySeries;
  28425. exports.log = log;
  28426. exports.map = map;
  28427. exports.mapLimit = mapLimit;
  28428. exports.mapSeries = mapSeries;
  28429. exports.mapValues = mapValues;
  28430. exports.mapValuesLimit = mapValuesLimit;
  28431. exports.mapValuesSeries = mapValuesSeries;
  28432. exports.memoize = memoize;
  28433. exports.nextTick = nextTick;
  28434. exports.parallel = parallelLimit;
  28435. exports.parallelLimit = parallelLimit$1;
  28436. exports.priorityQueue = priorityQueue;
  28437. exports.queue = queue$1;
  28438. exports.race = race;
  28439. exports.reduce = reduce;
  28440. exports.reduceRight = reduceRight;
  28441. exports.reflect = reflect;
  28442. exports.reflectAll = reflectAll;
  28443. exports.reject = reject;
  28444. exports.rejectLimit = rejectLimit;
  28445. exports.rejectSeries = rejectSeries;
  28446. exports.retry = retry;
  28447. exports.retryable = retryable;
  28448. exports.seq = seq;
  28449. exports.series = series;
  28450. exports.setImmediate = setImmediate$1;
  28451. exports.some = some;
  28452. exports.someLimit = someLimit;
  28453. exports.someSeries = someSeries;
  28454. exports.sortBy = sortBy;
  28455. exports.timeout = timeout;
  28456. exports.times = times;
  28457. exports.timesLimit = timeLimit;
  28458. exports.timesSeries = timesSeries;
  28459. exports.transform = transform;
  28460. exports.tryEach = tryEach;
  28461. exports.unmemoize = unmemoize;
  28462. exports.until = until;
  28463. exports.waterfall = waterfall;
  28464. exports.whilst = whilst;
  28465. exports.all = every;
  28466. exports.allLimit = everyLimit;
  28467. exports.allSeries = everySeries;
  28468. exports.any = some;
  28469. exports.anyLimit = someLimit;
  28470. exports.anySeries = someSeries;
  28471. exports.find = detect;
  28472. exports.findLimit = detectLimit;
  28473. exports.findSeries = detectSeries;
  28474. exports.forEach = eachLimit;
  28475. exports.forEachSeries = eachSeries;
  28476. exports.forEachLimit = eachLimit$1;
  28477. exports.forEachOf = eachOf;
  28478. exports.forEachOfSeries = eachOfSeries;
  28479. exports.forEachOfLimit = eachOfLimit;
  28480. exports.inject = reduce;
  28481. exports.foldl = reduce;
  28482. exports.foldr = reduceRight;
  28483. exports.select = filter;
  28484. exports.selectLimit = filterLimit;
  28485. exports.selectSeries = filterSeries;
  28486. exports.wrapSync = asyncify;
  28487. Object.defineProperty(exports, '__esModule', { value: true });
  28488. })));
  28489. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
  28490. },{"_process":122,"timers":146}],"es6-promise":[function(require,module,exports){
  28491. (function (process,global){
  28492. /*!
  28493. * @overview es6-promise - a tiny implementation of Promises/A+.
  28494. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  28495. * @license Licensed under MIT license
  28496. * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
  28497. * @version v4.2.8+1e68dce6
  28498. */
  28499. (function (global, factory) {
  28500. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  28501. typeof define === 'function' && define.amd ? define(factory) :
  28502. (global.ES6Promise = factory());
  28503. }(this, (function () { 'use strict';
  28504. function objectOrFunction(x) {
  28505. var type = typeof x;
  28506. return x !== null && (type === 'object' || type === 'function');
  28507. }
  28508. function isFunction(x) {
  28509. return typeof x === 'function';
  28510. }
  28511. var _isArray = void 0;
  28512. if (Array.isArray) {
  28513. _isArray = Array.isArray;
  28514. } else {
  28515. _isArray = function (x) {
  28516. return Object.prototype.toString.call(x) === '[object Array]';
  28517. };
  28518. }
  28519. var isArray = _isArray;
  28520. var len = 0;
  28521. var vertxNext = void 0;
  28522. var customSchedulerFn = void 0;
  28523. var asap = function asap(callback, arg) {
  28524. queue[len] = callback;
  28525. queue[len + 1] = arg;
  28526. len += 2;
  28527. if (len === 2) {
  28528. // If len is 2, that means that we need to schedule an async flush.
  28529. // If additional callbacks are queued before the queue is flushed, they
  28530. // will be processed by this flush that we are scheduling.
  28531. if (customSchedulerFn) {
  28532. customSchedulerFn(flush);
  28533. } else {
  28534. scheduleFlush();
  28535. }
  28536. }
  28537. };
  28538. function setScheduler(scheduleFn) {
  28539. customSchedulerFn = scheduleFn;
  28540. }
  28541. function setAsap(asapFn) {
  28542. asap = asapFn;
  28543. }
  28544. var browserWindow = typeof window !== 'undefined' ? window : undefined;
  28545. var browserGlobal = browserWindow || {};
  28546. var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
  28547. var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  28548. // test for web worker but not in IE10
  28549. var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
  28550. // node
  28551. function useNextTick() {
  28552. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  28553. // see https://github.com/cujojs/when/issues/410 for details
  28554. return function () {
  28555. return process.nextTick(flush);
  28556. };
  28557. }
  28558. // vertx
  28559. function useVertxTimer() {
  28560. if (typeof vertxNext !== 'undefined') {
  28561. return function () {
  28562. vertxNext(flush);
  28563. };
  28564. }
  28565. return useSetTimeout();
  28566. }
  28567. function useMutationObserver() {
  28568. var iterations = 0;
  28569. var observer = new BrowserMutationObserver(flush);
  28570. var node = document.createTextNode('');
  28571. observer.observe(node, { characterData: true });
  28572. return function () {
  28573. node.data = iterations = ++iterations % 2;
  28574. };
  28575. }
  28576. // web worker
  28577. function useMessageChannel() {
  28578. var channel = new MessageChannel();
  28579. channel.port1.onmessage = flush;
  28580. return function () {
  28581. return channel.port2.postMessage(0);
  28582. };
  28583. }
  28584. function useSetTimeout() {
  28585. // Store setTimeout reference so es6-promise will be unaffected by
  28586. // other code modifying setTimeout (like sinon.useFakeTimers())
  28587. var globalSetTimeout = setTimeout;
  28588. return function () {
  28589. return globalSetTimeout(flush, 1);
  28590. };
  28591. }
  28592. var queue = new Array(1000);
  28593. function flush() {
  28594. for (var i = 0; i < len; i += 2) {
  28595. var callback = queue[i];
  28596. var arg = queue[i + 1];
  28597. callback(arg);
  28598. queue[i] = undefined;
  28599. queue[i + 1] = undefined;
  28600. }
  28601. len = 0;
  28602. }
  28603. function attemptVertx() {
  28604. try {
  28605. var vertx = Function('return this')().require('vertx');
  28606. vertxNext = vertx.runOnLoop || vertx.runOnContext;
  28607. return useVertxTimer();
  28608. } catch (e) {
  28609. return useSetTimeout();
  28610. }
  28611. }
  28612. var scheduleFlush = void 0;
  28613. // Decide what async method to use to triggering processing of queued callbacks:
  28614. if (isNode) {
  28615. scheduleFlush = useNextTick();
  28616. } else if (BrowserMutationObserver) {
  28617. scheduleFlush = useMutationObserver();
  28618. } else if (isWorker) {
  28619. scheduleFlush = useMessageChannel();
  28620. } else if (browserWindow === undefined && typeof require === 'function') {
  28621. scheduleFlush = attemptVertx();
  28622. } else {
  28623. scheduleFlush = useSetTimeout();
  28624. }
  28625. function then(onFulfillment, onRejection) {
  28626. var parent = this;
  28627. var child = new this.constructor(noop);
  28628. if (child[PROMISE_ID] === undefined) {
  28629. makePromise(child);
  28630. }
  28631. var _state = parent._state;
  28632. if (_state) {
  28633. var callback = arguments[_state - 1];
  28634. asap(function () {
  28635. return invokeCallback(_state, child, callback, parent._result);
  28636. });
  28637. } else {
  28638. subscribe(parent, child, onFulfillment, onRejection);
  28639. }
  28640. return child;
  28641. }
  28642. /**
  28643. `Promise.resolve` returns a promise that will become resolved with the
  28644. passed `value`. It is shorthand for the following:
  28645. ```javascript
  28646. let promise = new Promise(function(resolve, reject){
  28647. resolve(1);
  28648. });
  28649. promise.then(function(value){
  28650. // value === 1
  28651. });
  28652. ```
  28653. Instead of writing the above, your code now simply becomes the following:
  28654. ```javascript
  28655. let promise = Promise.resolve(1);
  28656. promise.then(function(value){
  28657. // value === 1
  28658. });
  28659. ```
  28660. @method resolve
  28661. @static
  28662. @param {Any} value value that the returned promise will be resolved with
  28663. Useful for tooling.
  28664. @return {Promise} a promise that will become fulfilled with the given
  28665. `value`
  28666. */
  28667. function resolve$1(object) {
  28668. /*jshint validthis:true */
  28669. var Constructor = this;
  28670. if (object && typeof object === 'object' && object.constructor === Constructor) {
  28671. return object;
  28672. }
  28673. var promise = new Constructor(noop);
  28674. resolve(promise, object);
  28675. return promise;
  28676. }
  28677. var PROMISE_ID = Math.random().toString(36).substring(2);
  28678. function noop() {}
  28679. var PENDING = void 0;
  28680. var FULFILLED = 1;
  28681. var REJECTED = 2;
  28682. function selfFulfillment() {
  28683. return new TypeError("You cannot resolve a promise with itself");
  28684. }
  28685. function cannotReturnOwn() {
  28686. return new TypeError('A promises callback cannot return that same promise.');
  28687. }
  28688. function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
  28689. try {
  28690. then$$1.call(value, fulfillmentHandler, rejectionHandler);
  28691. } catch (e) {
  28692. return e;
  28693. }
  28694. }
  28695. function handleForeignThenable(promise, thenable, then$$1) {
  28696. asap(function (promise) {
  28697. var sealed = false;
  28698. var error = tryThen(then$$1, thenable, function (value) {
  28699. if (sealed) {
  28700. return;
  28701. }
  28702. sealed = true;
  28703. if (thenable !== value) {
  28704. resolve(promise, value);
  28705. } else {
  28706. fulfill(promise, value);
  28707. }
  28708. }, function (reason) {
  28709. if (sealed) {
  28710. return;
  28711. }
  28712. sealed = true;
  28713. reject(promise, reason);
  28714. }, 'Settle: ' + (promise._label || ' unknown promise'));
  28715. if (!sealed && error) {
  28716. sealed = true;
  28717. reject(promise, error);
  28718. }
  28719. }, promise);
  28720. }
  28721. function handleOwnThenable(promise, thenable) {
  28722. if (thenable._state === FULFILLED) {
  28723. fulfill(promise, thenable._result);
  28724. } else if (thenable._state === REJECTED) {
  28725. reject(promise, thenable._result);
  28726. } else {
  28727. subscribe(thenable, undefined, function (value) {
  28728. return resolve(promise, value);
  28729. }, function (reason) {
  28730. return reject(promise, reason);
  28731. });
  28732. }
  28733. }
  28734. function handleMaybeThenable(promise, maybeThenable, then$$1) {
  28735. if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
  28736. handleOwnThenable(promise, maybeThenable);
  28737. } else {
  28738. if (then$$1 === undefined) {
  28739. fulfill(promise, maybeThenable);
  28740. } else if (isFunction(then$$1)) {
  28741. handleForeignThenable(promise, maybeThenable, then$$1);
  28742. } else {
  28743. fulfill(promise, maybeThenable);
  28744. }
  28745. }
  28746. }
  28747. function resolve(promise, value) {
  28748. if (promise === value) {
  28749. reject(promise, selfFulfillment());
  28750. } else if (objectOrFunction(value)) {
  28751. var then$$1 = void 0;
  28752. try {
  28753. then$$1 = value.then;
  28754. } catch (error) {
  28755. reject(promise, error);
  28756. return;
  28757. }
  28758. handleMaybeThenable(promise, value, then$$1);
  28759. } else {
  28760. fulfill(promise, value);
  28761. }
  28762. }
  28763. function publishRejection(promise) {
  28764. if (promise._onerror) {
  28765. promise._onerror(promise._result);
  28766. }
  28767. publish(promise);
  28768. }
  28769. function fulfill(promise, value) {
  28770. if (promise._state !== PENDING) {
  28771. return;
  28772. }
  28773. promise._result = value;
  28774. promise._state = FULFILLED;
  28775. if (promise._subscribers.length !== 0) {
  28776. asap(publish, promise);
  28777. }
  28778. }
  28779. function reject(promise, reason) {
  28780. if (promise._state !== PENDING) {
  28781. return;
  28782. }
  28783. promise._state = REJECTED;
  28784. promise._result = reason;
  28785. asap(publishRejection, promise);
  28786. }
  28787. function subscribe(parent, child, onFulfillment, onRejection) {
  28788. var _subscribers = parent._subscribers;
  28789. var length = _subscribers.length;
  28790. parent._onerror = null;
  28791. _subscribers[length] = child;
  28792. _subscribers[length + FULFILLED] = onFulfillment;
  28793. _subscribers[length + REJECTED] = onRejection;
  28794. if (length === 0 && parent._state) {
  28795. asap(publish, parent);
  28796. }
  28797. }
  28798. function publish(promise) {
  28799. var subscribers = promise._subscribers;
  28800. var settled = promise._state;
  28801. if (subscribers.length === 0) {
  28802. return;
  28803. }
  28804. var child = void 0,
  28805. callback = void 0,
  28806. detail = promise._result;
  28807. for (var i = 0; i < subscribers.length; i += 3) {
  28808. child = subscribers[i];
  28809. callback = subscribers[i + settled];
  28810. if (child) {
  28811. invokeCallback(settled, child, callback, detail);
  28812. } else {
  28813. callback(detail);
  28814. }
  28815. }
  28816. promise._subscribers.length = 0;
  28817. }
  28818. function invokeCallback(settled, promise, callback, detail) {
  28819. var hasCallback = isFunction(callback),
  28820. value = void 0,
  28821. error = void 0,
  28822. succeeded = true;
  28823. if (hasCallback) {
  28824. try {
  28825. value = callback(detail);
  28826. } catch (e) {
  28827. succeeded = false;
  28828. error = e;
  28829. }
  28830. if (promise === value) {
  28831. reject(promise, cannotReturnOwn());
  28832. return;
  28833. }
  28834. } else {
  28835. value = detail;
  28836. }
  28837. if (promise._state !== PENDING) {
  28838. // noop
  28839. } else if (hasCallback && succeeded) {
  28840. resolve(promise, value);
  28841. } else if (succeeded === false) {
  28842. reject(promise, error);
  28843. } else if (settled === FULFILLED) {
  28844. fulfill(promise, value);
  28845. } else if (settled === REJECTED) {
  28846. reject(promise, value);
  28847. }
  28848. }
  28849. function initializePromise(promise, resolver) {
  28850. try {
  28851. resolver(function resolvePromise(value) {
  28852. resolve(promise, value);
  28853. }, function rejectPromise(reason) {
  28854. reject(promise, reason);
  28855. });
  28856. } catch (e) {
  28857. reject(promise, e);
  28858. }
  28859. }
  28860. var id = 0;
  28861. function nextId() {
  28862. return id++;
  28863. }
  28864. function makePromise(promise) {
  28865. promise[PROMISE_ID] = id++;
  28866. promise._state = undefined;
  28867. promise._result = undefined;
  28868. promise._subscribers = [];
  28869. }
  28870. function validationError() {
  28871. return new Error('Array Methods must be provided an Array');
  28872. }
  28873. var Enumerator = function () {
  28874. function Enumerator(Constructor, input) {
  28875. this._instanceConstructor = Constructor;
  28876. this.promise = new Constructor(noop);
  28877. if (!this.promise[PROMISE_ID]) {
  28878. makePromise(this.promise);
  28879. }
  28880. if (isArray(input)) {
  28881. this.length = input.length;
  28882. this._remaining = input.length;
  28883. this._result = new Array(this.length);
  28884. if (this.length === 0) {
  28885. fulfill(this.promise, this._result);
  28886. } else {
  28887. this.length = this.length || 0;
  28888. this._enumerate(input);
  28889. if (this._remaining === 0) {
  28890. fulfill(this.promise, this._result);
  28891. }
  28892. }
  28893. } else {
  28894. reject(this.promise, validationError());
  28895. }
  28896. }
  28897. Enumerator.prototype._enumerate = function _enumerate(input) {
  28898. for (var i = 0; this._state === PENDING && i < input.length; i++) {
  28899. this._eachEntry(input[i], i);
  28900. }
  28901. };
  28902. Enumerator.prototype._eachEntry = function _eachEntry(entry, i) {
  28903. var c = this._instanceConstructor;
  28904. var resolve$$1 = c.resolve;
  28905. if (resolve$$1 === resolve$1) {
  28906. var _then = void 0;
  28907. var error = void 0;
  28908. var didError = false;
  28909. try {
  28910. _then = entry.then;
  28911. } catch (e) {
  28912. didError = true;
  28913. error = e;
  28914. }
  28915. if (_then === then && entry._state !== PENDING) {
  28916. this._settledAt(entry._state, i, entry._result);
  28917. } else if (typeof _then !== 'function') {
  28918. this._remaining--;
  28919. this._result[i] = entry;
  28920. } else if (c === Promise$1) {
  28921. var promise = new c(noop);
  28922. if (didError) {
  28923. reject(promise, error);
  28924. } else {
  28925. handleMaybeThenable(promise, entry, _then);
  28926. }
  28927. this._willSettleAt(promise, i);
  28928. } else {
  28929. this._willSettleAt(new c(function (resolve$$1) {
  28930. return resolve$$1(entry);
  28931. }), i);
  28932. }
  28933. } else {
  28934. this._willSettleAt(resolve$$1(entry), i);
  28935. }
  28936. };
  28937. Enumerator.prototype._settledAt = function _settledAt(state, i, value) {
  28938. var promise = this.promise;
  28939. if (promise._state === PENDING) {
  28940. this._remaining--;
  28941. if (state === REJECTED) {
  28942. reject(promise, value);
  28943. } else {
  28944. this._result[i] = value;
  28945. }
  28946. }
  28947. if (this._remaining === 0) {
  28948. fulfill(promise, this._result);
  28949. }
  28950. };
  28951. Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) {
  28952. var enumerator = this;
  28953. subscribe(promise, undefined, function (value) {
  28954. return enumerator._settledAt(FULFILLED, i, value);
  28955. }, function (reason) {
  28956. return enumerator._settledAt(REJECTED, i, reason);
  28957. });
  28958. };
  28959. return Enumerator;
  28960. }();
  28961. /**
  28962. `Promise.all` accepts an array of promises, and returns a new promise which
  28963. is fulfilled with an array of fulfillment values for the passed promises, or
  28964. rejected with the reason of the first passed promise to be rejected. It casts all
  28965. elements of the passed iterable to promises as it runs this algorithm.
  28966. Example:
  28967. ```javascript
  28968. let promise1 = resolve(1);
  28969. let promise2 = resolve(2);
  28970. let promise3 = resolve(3);
  28971. let promises = [ promise1, promise2, promise3 ];
  28972. Promise.all(promises).then(function(array){
  28973. // The array here would be [ 1, 2, 3 ];
  28974. });
  28975. ```
  28976. If any of the `promises` given to `all` are rejected, the first promise
  28977. that is rejected will be given as an argument to the returned promises's
  28978. rejection handler. For example:
  28979. Example:
  28980. ```javascript
  28981. let promise1 = resolve(1);
  28982. let promise2 = reject(new Error("2"));
  28983. let promise3 = reject(new Error("3"));
  28984. let promises = [ promise1, promise2, promise3 ];
  28985. Promise.all(promises).then(function(array){
  28986. // Code here never runs because there are rejected promises!
  28987. }, function(error) {
  28988. // error.message === "2"
  28989. });
  28990. ```
  28991. @method all
  28992. @static
  28993. @param {Array} entries array of promises
  28994. @param {String} label optional string for labeling the promise.
  28995. Useful for tooling.
  28996. @return {Promise} promise that is fulfilled when all `promises` have been
  28997. fulfilled, or rejected if any of them become rejected.
  28998. @static
  28999. */
  29000. function all(entries) {
  29001. return new Enumerator(this, entries).promise;
  29002. }
  29003. /**
  29004. `Promise.race` returns a new promise which is settled in the same way as the
  29005. first passed promise to settle.
  29006. Example:
  29007. ```javascript
  29008. let promise1 = new Promise(function(resolve, reject){
  29009. setTimeout(function(){
  29010. resolve('promise 1');
  29011. }, 200);
  29012. });
  29013. let promise2 = new Promise(function(resolve, reject){
  29014. setTimeout(function(){
  29015. resolve('promise 2');
  29016. }, 100);
  29017. });
  29018. Promise.race([promise1, promise2]).then(function(result){
  29019. // result === 'promise 2' because it was resolved before promise1
  29020. // was resolved.
  29021. });
  29022. ```
  29023. `Promise.race` is deterministic in that only the state of the first
  29024. settled promise matters. For example, even if other promises given to the
  29025. `promises` array argument are resolved, but the first settled promise has
  29026. become rejected before the other promises became fulfilled, the returned
  29027. promise will become rejected:
  29028. ```javascript
  29029. let promise1 = new Promise(function(resolve, reject){
  29030. setTimeout(function(){
  29031. resolve('promise 1');
  29032. }, 200);
  29033. });
  29034. let promise2 = new Promise(function(resolve, reject){
  29035. setTimeout(function(){
  29036. reject(new Error('promise 2'));
  29037. }, 100);
  29038. });
  29039. Promise.race([promise1, promise2]).then(function(result){
  29040. // Code here never runs
  29041. }, function(reason){
  29042. // reason.message === 'promise 2' because promise 2 became rejected before
  29043. // promise 1 became fulfilled
  29044. });
  29045. ```
  29046. An example real-world use case is implementing timeouts:
  29047. ```javascript
  29048. Promise.race([ajax('foo.json'), timeout(5000)])
  29049. ```
  29050. @method race
  29051. @static
  29052. @param {Array} promises array of promises to observe
  29053. Useful for tooling.
  29054. @return {Promise} a promise which settles in the same way as the first passed
  29055. promise to settle.
  29056. */
  29057. function race(entries) {
  29058. /*jshint validthis:true */
  29059. var Constructor = this;
  29060. if (!isArray(entries)) {
  29061. return new Constructor(function (_, reject) {
  29062. return reject(new TypeError('You must pass an array to race.'));
  29063. });
  29064. } else {
  29065. return new Constructor(function (resolve, reject) {
  29066. var length = entries.length;
  29067. for (var i = 0; i < length; i++) {
  29068. Constructor.resolve(entries[i]).then(resolve, reject);
  29069. }
  29070. });
  29071. }
  29072. }
  29073. /**
  29074. `Promise.reject` returns a promise rejected with the passed `reason`.
  29075. It is shorthand for the following:
  29076. ```javascript
  29077. let promise = new Promise(function(resolve, reject){
  29078. reject(new Error('WHOOPS'));
  29079. });
  29080. promise.then(function(value){
  29081. // Code here doesn't run because the promise is rejected!
  29082. }, function(reason){
  29083. // reason.message === 'WHOOPS'
  29084. });
  29085. ```
  29086. Instead of writing the above, your code now simply becomes the following:
  29087. ```javascript
  29088. let promise = Promise.reject(new Error('WHOOPS'));
  29089. promise.then(function(value){
  29090. // Code here doesn't run because the promise is rejected!
  29091. }, function(reason){
  29092. // reason.message === 'WHOOPS'
  29093. });
  29094. ```
  29095. @method reject
  29096. @static
  29097. @param {Any} reason value that the returned promise will be rejected with.
  29098. Useful for tooling.
  29099. @return {Promise} a promise rejected with the given `reason`.
  29100. */
  29101. function reject$1(reason) {
  29102. /*jshint validthis:true */
  29103. var Constructor = this;
  29104. var promise = new Constructor(noop);
  29105. reject(promise, reason);
  29106. return promise;
  29107. }
  29108. function needsResolver() {
  29109. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  29110. }
  29111. function needsNew() {
  29112. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  29113. }
  29114. /**
  29115. Promise objects represent the eventual result of an asynchronous operation. The
  29116. primary way of interacting with a promise is through its `then` method, which
  29117. registers callbacks to receive either a promise's eventual value or the reason
  29118. why the promise cannot be fulfilled.
  29119. Terminology
  29120. -----------
  29121. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  29122. - `thenable` is an object or function that defines a `then` method.
  29123. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  29124. - `exception` is a value that is thrown using the throw statement.
  29125. - `reason` is a value that indicates why a promise was rejected.
  29126. - `settled` the final resting state of a promise, fulfilled or rejected.
  29127. A promise can be in one of three states: pending, fulfilled, or rejected.
  29128. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  29129. state. Promises that are rejected have a rejection reason and are in the
  29130. rejected state. A fulfillment value is never a thenable.
  29131. Promises can also be said to *resolve* a value. If this value is also a
  29132. promise, then the original promise's settled state will match the value's
  29133. settled state. So a promise that *resolves* a promise that rejects will
  29134. itself reject, and a promise that *resolves* a promise that fulfills will
  29135. itself fulfill.
  29136. Basic Usage:
  29137. ------------
  29138. ```js
  29139. let promise = new Promise(function(resolve, reject) {
  29140. // on success
  29141. resolve(value);
  29142. // on failure
  29143. reject(reason);
  29144. });
  29145. promise.then(function(value) {
  29146. // on fulfillment
  29147. }, function(reason) {
  29148. // on rejection
  29149. });
  29150. ```
  29151. Advanced Usage:
  29152. ---------------
  29153. Promises shine when abstracting away asynchronous interactions such as
  29154. `XMLHttpRequest`s.
  29155. ```js
  29156. function getJSON(url) {
  29157. return new Promise(function(resolve, reject){
  29158. let xhr = new XMLHttpRequest();
  29159. xhr.open('GET', url);
  29160. xhr.onreadystatechange = handler;
  29161. xhr.responseType = 'json';
  29162. xhr.setRequestHeader('Accept', 'application/json');
  29163. xhr.send();
  29164. function handler() {
  29165. if (this.readyState === this.DONE) {
  29166. if (this.status === 200) {
  29167. resolve(this.response);
  29168. } else {
  29169. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  29170. }
  29171. }
  29172. };
  29173. });
  29174. }
  29175. getJSON('/posts.json').then(function(json) {
  29176. // on fulfillment
  29177. }, function(reason) {
  29178. // on rejection
  29179. });
  29180. ```
  29181. Unlike callbacks, promises are great composable primitives.
  29182. ```js
  29183. Promise.all([
  29184. getJSON('/posts'),
  29185. getJSON('/comments')
  29186. ]).then(function(values){
  29187. values[0] // => postsJSON
  29188. values[1] // => commentsJSON
  29189. return values;
  29190. });
  29191. ```
  29192. @class Promise
  29193. @param {Function} resolver
  29194. Useful for tooling.
  29195. @constructor
  29196. */
  29197. var Promise$1 = function () {
  29198. function Promise(resolver) {
  29199. this[PROMISE_ID] = nextId();
  29200. this._result = this._state = undefined;
  29201. this._subscribers = [];
  29202. if (noop !== resolver) {
  29203. typeof resolver !== 'function' && needsResolver();
  29204. this instanceof Promise ? initializePromise(this, resolver) : needsNew();
  29205. }
  29206. }
  29207. /**
  29208. The primary way of interacting with a promise is through its `then` method,
  29209. which registers callbacks to receive either a promise's eventual value or the
  29210. reason why the promise cannot be fulfilled.
  29211. ```js
  29212. findUser().then(function(user){
  29213. // user is available
  29214. }, function(reason){
  29215. // user is unavailable, and you are given the reason why
  29216. });
  29217. ```
  29218. Chaining
  29219. --------
  29220. The return value of `then` is itself a promise. This second, 'downstream'
  29221. promise is resolved with the return value of the first promise's fulfillment
  29222. or rejection handler, or rejected if the handler throws an exception.
  29223. ```js
  29224. findUser().then(function (user) {
  29225. return user.name;
  29226. }, function (reason) {
  29227. return 'default name';
  29228. }).then(function (userName) {
  29229. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  29230. // will be `'default name'`
  29231. });
  29232. findUser().then(function (user) {
  29233. throw new Error('Found user, but still unhappy');
  29234. }, function (reason) {
  29235. throw new Error('`findUser` rejected and we're unhappy');
  29236. }).then(function (value) {
  29237. // never reached
  29238. }, function (reason) {
  29239. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  29240. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  29241. });
  29242. ```
  29243. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  29244. ```js
  29245. findUser().then(function (user) {
  29246. throw new PedagogicalException('Upstream error');
  29247. }).then(function (value) {
  29248. // never reached
  29249. }).then(function (value) {
  29250. // never reached
  29251. }, function (reason) {
  29252. // The `PedgagocialException` is propagated all the way down to here
  29253. });
  29254. ```
  29255. Assimilation
  29256. ------------
  29257. Sometimes the value you want to propagate to a downstream promise can only be
  29258. retrieved asynchronously. This can be achieved by returning a promise in the
  29259. fulfillment or rejection handler. The downstream promise will then be pending
  29260. until the returned promise is settled. This is called *assimilation*.
  29261. ```js
  29262. findUser().then(function (user) {
  29263. return findCommentsByAuthor(user);
  29264. }).then(function (comments) {
  29265. // The user's comments are now available
  29266. });
  29267. ```
  29268. If the assimliated promise rejects, then the downstream promise will also reject.
  29269. ```js
  29270. findUser().then(function (user) {
  29271. return findCommentsByAuthor(user);
  29272. }).then(function (comments) {
  29273. // If `findCommentsByAuthor` fulfills, we'll have the value here
  29274. }, function (reason) {
  29275. // If `findCommentsByAuthor` rejects, we'll have the reason here
  29276. });
  29277. ```
  29278. Simple Example
  29279. --------------
  29280. Synchronous Example
  29281. ```javascript
  29282. let result;
  29283. try {
  29284. result = findResult();
  29285. // success
  29286. } catch(reason) {
  29287. // failure
  29288. }
  29289. ```
  29290. Errback Example
  29291. ```js
  29292. findResult(function(result, err){
  29293. if (err) {
  29294. // failure
  29295. } else {
  29296. // success
  29297. }
  29298. });
  29299. ```
  29300. Promise Example;
  29301. ```javascript
  29302. findResult().then(function(result){
  29303. // success
  29304. }, function(reason){
  29305. // failure
  29306. });
  29307. ```
  29308. Advanced Example
  29309. --------------
  29310. Synchronous Example
  29311. ```javascript
  29312. let author, books;
  29313. try {
  29314. author = findAuthor();
  29315. books = findBooksByAuthor(author);
  29316. // success
  29317. } catch(reason) {
  29318. // failure
  29319. }
  29320. ```
  29321. Errback Example
  29322. ```js
  29323. function foundBooks(books) {
  29324. }
  29325. function failure(reason) {
  29326. }
  29327. findAuthor(function(author, err){
  29328. if (err) {
  29329. failure(err);
  29330. // failure
  29331. } else {
  29332. try {
  29333. findBoooksByAuthor(author, function(books, err) {
  29334. if (err) {
  29335. failure(err);
  29336. } else {
  29337. try {
  29338. foundBooks(books);
  29339. } catch(reason) {
  29340. failure(reason);
  29341. }
  29342. }
  29343. });
  29344. } catch(error) {
  29345. failure(err);
  29346. }
  29347. // success
  29348. }
  29349. });
  29350. ```
  29351. Promise Example;
  29352. ```javascript
  29353. findAuthor().
  29354. then(findBooksByAuthor).
  29355. then(function(books){
  29356. // found books
  29357. }).catch(function(reason){
  29358. // something went wrong
  29359. });
  29360. ```
  29361. @method then
  29362. @param {Function} onFulfilled
  29363. @param {Function} onRejected
  29364. Useful for tooling.
  29365. @return {Promise}
  29366. */
  29367. /**
  29368. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  29369. as the catch block of a try/catch statement.
  29370. ```js
  29371. function findAuthor(){
  29372. throw new Error('couldn't find that author');
  29373. }
  29374. // synchronous
  29375. try {
  29376. findAuthor();
  29377. } catch(reason) {
  29378. // something went wrong
  29379. }
  29380. // async with promises
  29381. findAuthor().catch(function(reason){
  29382. // something went wrong
  29383. });
  29384. ```
  29385. @method catch
  29386. @param {Function} onRejection
  29387. Useful for tooling.
  29388. @return {Promise}
  29389. */
  29390. Promise.prototype.catch = function _catch(onRejection) {
  29391. return this.then(null, onRejection);
  29392. };
  29393. /**
  29394. `finally` will be invoked regardless of the promise's fate just as native
  29395. try/catch/finally behaves
  29396. Synchronous example:
  29397. ```js
  29398. findAuthor() {
  29399. if (Math.random() > 0.5) {
  29400. throw new Error();
  29401. }
  29402. return new Author();
  29403. }
  29404. try {
  29405. return findAuthor(); // succeed or fail
  29406. } catch(error) {
  29407. return findOtherAuther();
  29408. } finally {
  29409. // always runs
  29410. // doesn't affect the return value
  29411. }
  29412. ```
  29413. Asynchronous example:
  29414. ```js
  29415. findAuthor().catch(function(reason){
  29416. return findOtherAuther();
  29417. }).finally(function(){
  29418. // author was either found, or not
  29419. });
  29420. ```
  29421. @method finally
  29422. @param {Function} callback
  29423. @return {Promise}
  29424. */
  29425. Promise.prototype.finally = function _finally(callback) {
  29426. var promise = this;
  29427. var constructor = promise.constructor;
  29428. if (isFunction(callback)) {
  29429. return promise.then(function (value) {
  29430. return constructor.resolve(callback()).then(function () {
  29431. return value;
  29432. });
  29433. }, function (reason) {
  29434. return constructor.resolve(callback()).then(function () {
  29435. throw reason;
  29436. });
  29437. });
  29438. }
  29439. return promise.then(callback, callback);
  29440. };
  29441. return Promise;
  29442. }();
  29443. Promise$1.prototype.then = then;
  29444. Promise$1.all = all;
  29445. Promise$1.race = race;
  29446. Promise$1.resolve = resolve$1;
  29447. Promise$1.reject = reject$1;
  29448. Promise$1._setScheduler = setScheduler;
  29449. Promise$1._setAsap = setAsap;
  29450. Promise$1._asap = asap;
  29451. /*global self*/
  29452. function polyfill() {
  29453. var local = void 0;
  29454. if (typeof global !== 'undefined') {
  29455. local = global;
  29456. } else if (typeof self !== 'undefined') {
  29457. local = self;
  29458. } else {
  29459. try {
  29460. local = Function('return this')();
  29461. } catch (e) {
  29462. throw new Error('polyfill failed because global object is unavailable in this environment');
  29463. }
  29464. }
  29465. var P = local.Promise;
  29466. if (P) {
  29467. var promiseToString = null;
  29468. try {
  29469. promiseToString = Object.prototype.toString.call(P.resolve());
  29470. } catch (e) {
  29471. // silently ignored
  29472. }
  29473. if (promiseToString === '[object Promise]' && !P.cast) {
  29474. return;
  29475. }
  29476. }
  29477. local.Promise = Promise$1;
  29478. }
  29479. // Strange compat..
  29480. Promise$1.polyfill = polyfill;
  29481. Promise$1.Promise = Promise$1;
  29482. return Promise$1;
  29483. })));
  29484. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  29485. },{"_process":122}],"inherits":[function(require,module,exports){
  29486. if (typeof Object.create === 'function') {
  29487. // implementation from standard node.js 'util' module
  29488. module.exports = function inherits(ctor, superCtor) {
  29489. if (superCtor) {
  29490. ctor.super_ = superCtor
  29491. ctor.prototype = Object.create(superCtor.prototype, {
  29492. constructor: {
  29493. value: ctor,
  29494. enumerable: false,
  29495. writable: true,
  29496. configurable: true
  29497. }
  29498. })
  29499. }
  29500. };
  29501. } else {
  29502. // old school shim for old browsers
  29503. module.exports = function inherits(ctor, superCtor) {
  29504. if (superCtor) {
  29505. ctor.super_ = superCtor
  29506. var TempCtor = function () {}
  29507. TempCtor.prototype = superCtor.prototype
  29508. ctor.prototype = new TempCtor()
  29509. ctor.prototype.constructor = ctor
  29510. }
  29511. }
  29512. }
  29513. },{}],"kurento-client-core":[function(require,module,exports){
  29514. /* Autogenerated with Kurento Idl */
  29515. /*
  29516. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  29517. *
  29518. * Licensed under the Apache License, Version 2.0 (the "License");
  29519. * you may not use this file except in compliance with the License.
  29520. * You may obtain a copy of the License at
  29521. *
  29522. * http://www.apache.org/licenses/LICENSE-2.0
  29523. *
  29524. * Unless required by applicable law or agreed to in writing, software
  29525. * distributed under the License is distributed on an "AS IS" BASIS,
  29526. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  29527. * See the License for the specific language governing permissions and
  29528. * limitations under the License.
  29529. */
  29530. /**
  29531. * Media API for the Kurento Web SDK
  29532. *
  29533. * @module core
  29534. *
  29535. * @copyright 2013-2015 Kurento (http://kurento.org/)
  29536. * @license ALv2
  29537. */
  29538. Object.defineProperty(exports, 'name', {value: 'core'});
  29539. Object.defineProperty(exports, 'version', {value: '6.14.0'});
  29540. var HubPort = require('./HubPort');
  29541. var MediaPipeline = require('./MediaPipeline');
  29542. var PassThrough = require('./PassThrough');
  29543. exports.HubPort = HubPort;
  29544. exports.MediaPipeline = MediaPipeline;
  29545. exports.PassThrough = PassThrough;
  29546. exports.abstracts = require('./abstracts');
  29547. exports.complexTypes = require('./complexTypes');
  29548. },{"./HubPort":27,"./MediaPipeline":28,"./PassThrough":29,"./abstracts":40,"./complexTypes":83}],"kurento-client-elements":[function(require,module,exports){
  29549. /* Autogenerated with Kurento Idl */
  29550. /*
  29551. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  29552. *
  29553. * Licensed under the Apache License, Version 2.0 (the "License");
  29554. * you may not use this file except in compliance with the License.
  29555. * You may obtain a copy of the License at
  29556. *
  29557. * http://www.apache.org/licenses/LICENSE-2.0
  29558. *
  29559. * Unless required by applicable law or agreed to in writing, software
  29560. * distributed under the License is distributed on an "AS IS" BASIS,
  29561. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  29562. * See the License for the specific language governing permissions and
  29563. * limitations under the License.
  29564. */
  29565. /**
  29566. * Media API for the Kurento Web SDK
  29567. *
  29568. * @module elements
  29569. *
  29570. * @copyright 2013-2015 Kurento (http://kurento.org/)
  29571. * @license ALv2
  29572. */
  29573. Object.defineProperty(exports, 'name', {value: 'elements'});
  29574. Object.defineProperty(exports, 'version', {value: '6.14.0'});
  29575. var AlphaBlending = require('./AlphaBlending');
  29576. var Composite = require('./Composite');
  29577. var Dispatcher = require('./Dispatcher');
  29578. var DispatcherOneToMany = require('./DispatcherOneToMany');
  29579. var HttpPostEndpoint = require('./HttpPostEndpoint');
  29580. var Mixer = require('./Mixer');
  29581. var PlayerEndpoint = require('./PlayerEndpoint');
  29582. var RecorderEndpoint = require('./RecorderEndpoint');
  29583. var RtpEndpoint = require('./RtpEndpoint');
  29584. var WebRtcEndpoint = require('./WebRtcEndpoint');
  29585. exports.AlphaBlending = AlphaBlending;
  29586. exports.Composite = Composite;
  29587. exports.Dispatcher = Dispatcher;
  29588. exports.DispatcherOneToMany = DispatcherOneToMany;
  29589. exports.HttpPostEndpoint = HttpPostEndpoint;
  29590. exports.Mixer = Mixer;
  29591. exports.PlayerEndpoint = PlayerEndpoint;
  29592. exports.RecorderEndpoint = RecorderEndpoint;
  29593. exports.RtpEndpoint = RtpEndpoint;
  29594. exports.WebRtcEndpoint = WebRtcEndpoint;
  29595. exports.abstracts = require('./abstracts');
  29596. exports.complexTypes = require('./complexTypes');
  29597. },{"./AlphaBlending":84,"./Composite":85,"./Dispatcher":86,"./DispatcherOneToMany":87,"./HttpPostEndpoint":88,"./Mixer":89,"./PlayerEndpoint":90,"./RecorderEndpoint":91,"./RtpEndpoint":92,"./WebRtcEndpoint":93,"./abstracts":95,"./complexTypes":105}],"kurento-client-filters":[function(require,module,exports){
  29598. /* Autogenerated with Kurento Idl */
  29599. /*
  29600. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  29601. *
  29602. * Licensed under the Apache License, Version 2.0 (the "License");
  29603. * you may not use this file except in compliance with the License.
  29604. * You may obtain a copy of the License at
  29605. *
  29606. * http://www.apache.org/licenses/LICENSE-2.0
  29607. *
  29608. * Unless required by applicable law or agreed to in writing, software
  29609. * distributed under the License is distributed on an "AS IS" BASIS,
  29610. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  29611. * See the License for the specific language governing permissions and
  29612. * limitations under the License.
  29613. */
  29614. /**
  29615. * Media API for the Kurento Web SDK
  29616. *
  29617. * @module filters
  29618. *
  29619. * @copyright 2013-2015 Kurento (http://kurento.org/)
  29620. * @license ALv2
  29621. */
  29622. Object.defineProperty(exports, 'name', {value: 'filters'});
  29623. Object.defineProperty(exports, 'version', {value: '6.14.0'});
  29624. var FaceOverlayFilter = require('./FaceOverlayFilter');
  29625. var GStreamerFilter = require('./GStreamerFilter');
  29626. var ImageOverlayFilter = require('./ImageOverlayFilter');
  29627. var ZBarFilter = require('./ZBarFilter');
  29628. exports.FaceOverlayFilter = FaceOverlayFilter;
  29629. exports.GStreamerFilter = GStreamerFilter;
  29630. exports.ImageOverlayFilter = ImageOverlayFilter;
  29631. exports.ZBarFilter = ZBarFilter;
  29632. exports.abstracts = require('./abstracts');
  29633. },{"./FaceOverlayFilter":106,"./GStreamerFilter":107,"./ImageOverlayFilter":108,"./ZBarFilter":109,"./abstracts":111}],"kurento-client":[function(require,module,exports){
  29634. /*
  29635. * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
  29636. *
  29637. * Licensed under the Apache License, Version 2.0 (the "License");
  29638. * you may not use this file except in compliance with the License.
  29639. * You may obtain a copy of the License at
  29640. *
  29641. * http://www.apache.org/licenses/LICENSE-2.0
  29642. *
  29643. * Unless required by applicable law or agreed to in writing, software
  29644. * distributed under the License is distributed on an "AS IS" BASIS,
  29645. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  29646. * See the License for the specific language governing permissions and
  29647. * limitations under the License.
  29648. *
  29649. */
  29650. /**
  29651. * Media API for the Kurento Web SDK
  29652. *
  29653. * @module kurentoClient
  29654. *
  29655. * @copyright 2013-2015 Kurento (http://kurento.org/)
  29656. * @license ALv2
  29657. */
  29658. require('error-tojson');
  29659. var checkType = require('./checkType');
  29660. var disguise = require('./disguise')
  29661. var MediaObjectCreator = require('./MediaObjectCreator');
  29662. var register = require('./register');
  29663. var TransactionsManager = require('./TransactionsManager');
  29664. exports.checkType = checkType;
  29665. exports.disguise = disguise;
  29666. exports.MediaObjectCreator = MediaObjectCreator;
  29667. exports.register = register;
  29668. exports.TransactionsManager = TransactionsManager;
  29669. // Export KurentoClient
  29670. var KurentoClient = require('./KurentoClient');
  29671. module.exports = KurentoClient;
  29672. KurentoClient.KurentoClient = KurentoClient;
  29673. // Ugly hack due to circular references
  29674. KurentoClient.checkType = checkType;
  29675. KurentoClient.disguise = disguise;
  29676. KurentoClient.MediaObjectCreator = MediaObjectCreator;
  29677. KurentoClient.register = register;
  29678. KurentoClient.TransactionsManager = TransactionsManager;
  29679. // Register Kurento basic elements
  29680. register('kurento-client-core')
  29681. register('kurento-client-elements')
  29682. register('kurento-client-filters')
  29683. },{"./KurentoClient":1,"./MediaObjectCreator":2,"./TransactionsManager":3,"./checkType":5,"./disguise":7,"./register":8,"error-tojson":20}],"promisecallback":[function(require,module,exports){
  29684. /*
  29685. * (C) Copyright 2014-2015 Kurento (http://kurento.org/)
  29686. *
  29687. * All rights reserved. This program and the accompanying materials are made
  29688. * available under the terms of the GNU Lesser General Public License (LGPL)
  29689. * version 2.1 which accompanies this distribution, and is available at
  29690. * http://www.gnu.org/licenses/lgpl-2.1.html
  29691. *
  29692. * This library is distributed in the hope that it will be useful, but WITHOUT
  29693. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  29694. * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  29695. * details.
  29696. */
  29697. /**
  29698. * Define a callback as the continuation of a promise
  29699. */
  29700. function promiseCallback(promise, callback, thisArg)
  29701. {
  29702. if(callback)
  29703. {
  29704. function callback2(error, result)
  29705. {
  29706. try
  29707. {
  29708. return callback.call(thisArg, error, result);
  29709. }
  29710. catch(exception)
  29711. {
  29712. // Show the exception in the console with its full stack trace
  29713. console.trace(exception);
  29714. throw exception;
  29715. }
  29716. };
  29717. promise = promise.then(callback2.bind(undefined, null), callback2);
  29718. };
  29719. return promise
  29720. };
  29721. module.exports = promiseCallback;
  29722. },{}]},{},[4]);