|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357 |
- (function(e, a) { for(var i in a) e[i] = a[i]; }(exports, /******/ (function(modules) { // webpackBootstrap
- /******/ // The module cache
- /******/ var installedModules = {};
- /******/
- /******/ // The require function
- /******/ function __webpack_require__(moduleId) {
- /******/
- /******/ // Check if module is in cache
- /******/ if(installedModules[moduleId]) {
- /******/ return installedModules[moduleId].exports;
- /******/ }
- /******/ // Create a new module (and put it into the cache)
- /******/ var module = installedModules[moduleId] = {
- /******/ i: moduleId,
- /******/ l: false,
- /******/ exports: {}
- /******/ };
- /******/
- /******/ // Execute the module function
- /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
- /******/
- /******/ // Flag the module as loaded
- /******/ module.l = true;
- /******/
- /******/ // Return the exports of the module
- /******/ return module.exports;
- /******/ }
- /******/
- /******/
- /******/ // expose the modules object (__webpack_modules__)
- /******/ __webpack_require__.m = modules;
- /******/
- /******/ // expose the module cache
- /******/ __webpack_require__.c = installedModules;
- /******/
- /******/ // define getter function for harmony exports
- /******/ __webpack_require__.d = function(exports, name, getter) {
- /******/ if(!__webpack_require__.o(exports, name)) {
- /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
- /******/ }
- /******/ };
- /******/
- /******/ // define __esModule on exports
- /******/ __webpack_require__.r = function(exports) {
- /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
- /******/ }
- /******/ Object.defineProperty(exports, '__esModule', { value: true });
- /******/ };
- /******/
- /******/ // create a fake namespace object
- /******/ // mode & 1: value is a module id, require it
- /******/ // mode & 2: merge all properties of value into the ns
- /******/ // mode & 4: return value when already ns object
- /******/ // mode & 8|1: behave like require
- /******/ __webpack_require__.t = function(value, mode) {
- /******/ if(mode & 1) value = __webpack_require__(value);
- /******/ if(mode & 8) return value;
- /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
- /******/ var ns = Object.create(null);
- /******/ __webpack_require__.r(ns);
- /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
- /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
- /******/ return ns;
- /******/ };
- /******/
- /******/ // getDefaultExport function for compatibility with non-harmony modules
- /******/ __webpack_require__.n = function(module) {
- /******/ var getter = module && module.__esModule ?
- /******/ function getDefault() { return module['default']; } :
- /******/ function getModuleExports() { return module; };
- /******/ __webpack_require__.d(getter, 'a', getter);
- /******/ return getter;
- /******/ };
- /******/
- /******/ // Object.prototype.hasOwnProperty.call
- /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
- /******/
- /******/ // __webpack_public_path__
- /******/ __webpack_require__.p = "";
- /******/
- /******/
- /******/ // Load entry module and return exports
- /******/ return __webpack_require__(__webpack_require__.s = 0);
- /******/ })
- /************************************************************************/
- /******/ ([
- /* 0 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.activate = void 0;
- const coc_nvim_1 = __webpack_require__(1);
- const server_1 = __importDefault(__webpack_require__(2));
- const commands_1 = __webpack_require__(140);
- const organizeImports_1 = __webpack_require__(114);
- const plugins_1 = __webpack_require__(141);
- function activate(context) {
- return __awaiter(this, void 0, void 0, function* () {
- let { subscriptions } = context;
- const config = coc_nvim_1.workspace.getConfiguration().get('tsserver', {});
- if (!config.enable)
- return;
- const pluginManager = new plugins_1.PluginManager();
- const service = new server_1.default(pluginManager);
- subscriptions.push(coc_nvim_1.services.regist(service));
- yield service.start();
- function registCommand(cmd) {
- let { id, execute } = cmd;
- subscriptions.push(coc_nvim_1.commands.registerCommand(id, execute, cmd));
- }
- registCommand(new commands_1.AutoFixCommand(service.clientHost));
- registCommand(new commands_1.ReloadProjectsCommand(service.clientHost));
- registCommand(new commands_1.OpenTsServerLogCommand(service.clientHost));
- registCommand(new commands_1.TypeScriptGoToProjectConfigCommand(service.clientHost));
- registCommand(new organizeImports_1.OrganizeImportsCommand(service.clientHost.serviceClient));
- registCommand(new commands_1.ConfigurePluginCommand(pluginManager));
- registCommand(coc_nvim_1.commands.register({
- id: 'tsserver.restart',
- execute: () => {
- // tslint:disable-next-line:no-floating-promises
- service.stop().then(() => {
- setTimeout(() => {
- service.restart();
- }, 100);
- });
- }
- }));
- return {
- configurePlugin: (pluginId, configuration) => {
- pluginManager.setConfiguration(pluginId, configuration);
- }
- };
- });
- }
- exports.activate = activate;
-
-
- /***/ }),
- /* 1 */
- /***/ (function(module, exports) {
-
- module.exports = require("coc.nvim");
-
- /***/ }),
- /* 2 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- const coc_nvim_1 = __webpack_require__(1);
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- const typescriptServiceClientHost_1 = __importDefault(__webpack_require__(33));
- const languageDescription_1 = __webpack_require__(115);
- class TsserverService {
- constructor(pluginManager) {
- this.pluginManager = pluginManager;
- this.id = 'tsserver';
- this.name = 'tsserver';
- this.state = coc_nvim_1.ServiceStat.Initial;
- this._onDidServiceReady = new vscode_languageserver_protocol_1.Emitter();
- this.onServiceReady = this._onDidServiceReady.event;
- this.disposables = [];
- this.descriptions = [];
- const config = coc_nvim_1.workspace.getConfiguration('tsserver');
- const enableJavascript = !!config.get('enableJavascript');
- this.enable = config.get('enable');
- this.descriptions = languageDescription_1.standardLanguageDescriptions.filter(o => {
- return enableJavascript ? true : o.id != 'javascript';
- });
- this.selector = this.descriptions.reduce((arr, c) => {
- return arr.concat(c.modeIds);
- }, []);
- coc_nvim_1.workspace.onDidOpenTextDocument(doc => {
- this.ensureConfigurationForDocument(doc);
- }, null, this.disposables);
- }
- get config() {
- return coc_nvim_1.workspace.getConfiguration('tsserver');
- }
- ensureConfigurationForDocument(document) {
- let uri = coc_nvim_1.Uri.parse(document.uri);
- let language = this.clientHost.findLanguage(uri);
- if (!language)
- return;
- language.fileConfigurationManager.ensureConfigurationForDocument(document).catch(_e => {
- // noop
- });
- }
- start() {
- if (this.clientHost)
- return;
- this.state = coc_nvim_1.ServiceStat.Starting;
- this.clientHost = new typescriptServiceClientHost_1.default(this.descriptions, this.pluginManager);
- this.disposables.push(this.clientHost);
- let client = this.clientHost.serviceClient;
- return new Promise(resolve => {
- let started = false;
- client.onTsServerStarted(() => {
- Object.defineProperty(this, 'state', {
- get: () => {
- return this.clientHost.serviceClient.state;
- }
- });
- this._onDidServiceReady.fire(void 0);
- this.ensureConfiguration();
- if (!started) {
- started = true;
- resolve();
- }
- });
- });
- }
- ensureConfiguration() {
- if (!this.clientHost)
- return;
- for (let doc of coc_nvim_1.workspace.documents) {
- this.ensureConfigurationForDocument(doc.textDocument);
- }
- }
- dispose() {
- coc_nvim_1.disposeAll(this.disposables);
- }
- restart() {
- return __awaiter(this, void 0, void 0, function* () {
- if (!this.clientHost)
- return;
- let client = this.clientHost.serviceClient;
- yield client.restartTsServer();
- });
- }
- stop() {
- return __awaiter(this, void 0, void 0, function* () {
- if (!this.clientHost)
- return;
- this.clientHost.reset();
- let client = this.clientHost.serviceClient;
- yield client.stop();
- return;
- });
- }
- }
- exports.default = TsserverService;
-
-
- /***/ }),
- /* 3 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- function __export(m) {
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
- }
- Object.defineProperty(exports, "__esModule", { value: true });
- const vscode_jsonrpc_1 = __webpack_require__(4);
- exports.ErrorCodes = vscode_jsonrpc_1.ErrorCodes;
- exports.ResponseError = vscode_jsonrpc_1.ResponseError;
- exports.CancellationToken = vscode_jsonrpc_1.CancellationToken;
- exports.CancellationTokenSource = vscode_jsonrpc_1.CancellationTokenSource;
- exports.Disposable = vscode_jsonrpc_1.Disposable;
- exports.Event = vscode_jsonrpc_1.Event;
- exports.Emitter = vscode_jsonrpc_1.Emitter;
- exports.Trace = vscode_jsonrpc_1.Trace;
- exports.TraceFormat = vscode_jsonrpc_1.TraceFormat;
- exports.SetTraceNotification = vscode_jsonrpc_1.SetTraceNotification;
- exports.LogTraceNotification = vscode_jsonrpc_1.LogTraceNotification;
- exports.RequestType = vscode_jsonrpc_1.RequestType;
- exports.RequestType0 = vscode_jsonrpc_1.RequestType0;
- exports.NotificationType = vscode_jsonrpc_1.NotificationType;
- exports.NotificationType0 = vscode_jsonrpc_1.NotificationType0;
- exports.MessageReader = vscode_jsonrpc_1.MessageReader;
- exports.MessageWriter = vscode_jsonrpc_1.MessageWriter;
- exports.ConnectionStrategy = vscode_jsonrpc_1.ConnectionStrategy;
- exports.StreamMessageReader = vscode_jsonrpc_1.StreamMessageReader;
- exports.StreamMessageWriter = vscode_jsonrpc_1.StreamMessageWriter;
- exports.IPCMessageReader = vscode_jsonrpc_1.IPCMessageReader;
- exports.IPCMessageWriter = vscode_jsonrpc_1.IPCMessageWriter;
- exports.createClientPipeTransport = vscode_jsonrpc_1.createClientPipeTransport;
- exports.createServerPipeTransport = vscode_jsonrpc_1.createServerPipeTransport;
- exports.generateRandomPipeName = vscode_jsonrpc_1.generateRandomPipeName;
- exports.createClientSocketTransport = vscode_jsonrpc_1.createClientSocketTransport;
- exports.createServerSocketTransport = vscode_jsonrpc_1.createServerSocketTransport;
- exports.ProgressType = vscode_jsonrpc_1.ProgressType;
- __export(__webpack_require__(18));
- __export(__webpack_require__(19));
- const callHierarchy = __webpack_require__(31);
- const st = __webpack_require__(32);
- var Proposed;
- (function (Proposed) {
- let CallHierarchyPrepareRequest;
- (function (CallHierarchyPrepareRequest) {
- CallHierarchyPrepareRequest.method = callHierarchy.CallHierarchyPrepareRequest.method;
- CallHierarchyPrepareRequest.type = callHierarchy.CallHierarchyPrepareRequest.type;
- })(CallHierarchyPrepareRequest = Proposed.CallHierarchyPrepareRequest || (Proposed.CallHierarchyPrepareRequest = {}));
- let CallHierarchyIncomingCallsRequest;
- (function (CallHierarchyIncomingCallsRequest) {
- CallHierarchyIncomingCallsRequest.method = callHierarchy.CallHierarchyIncomingCallsRequest.method;
- CallHierarchyIncomingCallsRequest.type = callHierarchy.CallHierarchyIncomingCallsRequest.type;
- })(CallHierarchyIncomingCallsRequest = Proposed.CallHierarchyIncomingCallsRequest || (Proposed.CallHierarchyIncomingCallsRequest = {}));
- let CallHierarchyOutgoingCallsRequest;
- (function (CallHierarchyOutgoingCallsRequest) {
- CallHierarchyOutgoingCallsRequest.method = callHierarchy.CallHierarchyOutgoingCallsRequest.method;
- CallHierarchyOutgoingCallsRequest.type = callHierarchy.CallHierarchyOutgoingCallsRequest.type;
- })(CallHierarchyOutgoingCallsRequest = Proposed.CallHierarchyOutgoingCallsRequest || (Proposed.CallHierarchyOutgoingCallsRequest = {}));
- Proposed.SemanticTokenTypes = st.SemanticTokenTypes;
- Proposed.SemanticTokenModifiers = st.SemanticTokenModifiers;
- Proposed.SemanticTokens = st.SemanticTokens;
- let SemanticTokensRequest;
- (function (SemanticTokensRequest) {
- SemanticTokensRequest.method = st.SemanticTokensRequest.method;
- SemanticTokensRequest.type = st.SemanticTokensRequest.type;
- })(SemanticTokensRequest = Proposed.SemanticTokensRequest || (Proposed.SemanticTokensRequest = {}));
- let SemanticTokensEditsRequest;
- (function (SemanticTokensEditsRequest) {
- SemanticTokensEditsRequest.method = st.SemanticTokensEditsRequest.method;
- SemanticTokensEditsRequest.type = st.SemanticTokensEditsRequest.type;
- })(SemanticTokensEditsRequest = Proposed.SemanticTokensEditsRequest || (Proposed.SemanticTokensEditsRequest = {}));
- let SemanticTokensRangeRequest;
- (function (SemanticTokensRangeRequest) {
- SemanticTokensRangeRequest.method = st.SemanticTokensRangeRequest.method;
- SemanticTokensRangeRequest.type = st.SemanticTokensRangeRequest.type;
- })(SemanticTokensRangeRequest = Proposed.SemanticTokensRangeRequest || (Proposed.SemanticTokensRangeRequest = {}));
- })(Proposed = exports.Proposed || (exports.Proposed = {}));
- function createProtocolConnection(reader, writer, logger, strategy) {
- return vscode_jsonrpc_1.createMessageConnection(reader, writer, logger, strategy);
- }
- exports.createProtocolConnection = createProtocolConnection;
-
-
- /***/ }),
- /* 4 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
- /// <reference path="../typings/thenable.d.ts" />
-
- function __export(m) {
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
- }
- Object.defineProperty(exports, "__esModule", { value: true });
- const Is = __webpack_require__(5);
- const messages_1 = __webpack_require__(6);
- exports.RequestType = messages_1.RequestType;
- exports.RequestType0 = messages_1.RequestType0;
- exports.RequestType1 = messages_1.RequestType1;
- exports.RequestType2 = messages_1.RequestType2;
- exports.RequestType3 = messages_1.RequestType3;
- exports.RequestType4 = messages_1.RequestType4;
- exports.RequestType5 = messages_1.RequestType5;
- exports.RequestType6 = messages_1.RequestType6;
- exports.RequestType7 = messages_1.RequestType7;
- exports.RequestType8 = messages_1.RequestType8;
- exports.RequestType9 = messages_1.RequestType9;
- exports.ResponseError = messages_1.ResponseError;
- exports.ErrorCodes = messages_1.ErrorCodes;
- exports.NotificationType = messages_1.NotificationType;
- exports.NotificationType0 = messages_1.NotificationType0;
- exports.NotificationType1 = messages_1.NotificationType1;
- exports.NotificationType2 = messages_1.NotificationType2;
- exports.NotificationType3 = messages_1.NotificationType3;
- exports.NotificationType4 = messages_1.NotificationType4;
- exports.NotificationType5 = messages_1.NotificationType5;
- exports.NotificationType6 = messages_1.NotificationType6;
- exports.NotificationType7 = messages_1.NotificationType7;
- exports.NotificationType8 = messages_1.NotificationType8;
- exports.NotificationType9 = messages_1.NotificationType9;
- const messageReader_1 = __webpack_require__(7);
- exports.MessageReader = messageReader_1.MessageReader;
- exports.StreamMessageReader = messageReader_1.StreamMessageReader;
- exports.IPCMessageReader = messageReader_1.IPCMessageReader;
- exports.SocketMessageReader = messageReader_1.SocketMessageReader;
- const messageWriter_1 = __webpack_require__(9);
- exports.MessageWriter = messageWriter_1.MessageWriter;
- exports.StreamMessageWriter = messageWriter_1.StreamMessageWriter;
- exports.IPCMessageWriter = messageWriter_1.IPCMessageWriter;
- exports.SocketMessageWriter = messageWriter_1.SocketMessageWriter;
- const events_1 = __webpack_require__(8);
- exports.Disposable = events_1.Disposable;
- exports.Event = events_1.Event;
- exports.Emitter = events_1.Emitter;
- const cancellation_1 = __webpack_require__(10);
- exports.CancellationTokenSource = cancellation_1.CancellationTokenSource;
- exports.CancellationToken = cancellation_1.CancellationToken;
- const linkedMap_1 = __webpack_require__(11);
- __export(__webpack_require__(12));
- __export(__webpack_require__(17));
- var CancelNotification;
- (function (CancelNotification) {
- CancelNotification.type = new messages_1.NotificationType('$/cancelRequest');
- })(CancelNotification || (CancelNotification = {}));
- var ProgressNotification;
- (function (ProgressNotification) {
- ProgressNotification.type = new messages_1.NotificationType('$/progress');
- })(ProgressNotification || (ProgressNotification = {}));
- class ProgressType {
- constructor() {
- }
- }
- exports.ProgressType = ProgressType;
- exports.NullLogger = Object.freeze({
- error: () => { },
- warn: () => { },
- info: () => { },
- log: () => { }
- });
- var Trace;
- (function (Trace) {
- Trace[Trace["Off"] = 0] = "Off";
- Trace[Trace["Messages"] = 1] = "Messages";
- Trace[Trace["Verbose"] = 2] = "Verbose";
- })(Trace = exports.Trace || (exports.Trace = {}));
- (function (Trace) {
- function fromString(value) {
- if (!Is.string(value)) {
- return Trace.Off;
- }
- value = value.toLowerCase();
- switch (value) {
- case 'off':
- return Trace.Off;
- case 'messages':
- return Trace.Messages;
- case 'verbose':
- return Trace.Verbose;
- default:
- return Trace.Off;
- }
- }
- Trace.fromString = fromString;
- function toString(value) {
- switch (value) {
- case Trace.Off:
- return 'off';
- case Trace.Messages:
- return 'messages';
- case Trace.Verbose:
- return 'verbose';
- default:
- return 'off';
- }
- }
- Trace.toString = toString;
- })(Trace = exports.Trace || (exports.Trace = {}));
- var TraceFormat;
- (function (TraceFormat) {
- TraceFormat["Text"] = "text";
- TraceFormat["JSON"] = "json";
- })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
- (function (TraceFormat) {
- function fromString(value) {
- value = value.toLowerCase();
- if (value === 'json') {
- return TraceFormat.JSON;
- }
- else {
- return TraceFormat.Text;
- }
- }
- TraceFormat.fromString = fromString;
- })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
- var SetTraceNotification;
- (function (SetTraceNotification) {
- SetTraceNotification.type = new messages_1.NotificationType('$/setTraceNotification');
- })(SetTraceNotification = exports.SetTraceNotification || (exports.SetTraceNotification = {}));
- var LogTraceNotification;
- (function (LogTraceNotification) {
- LogTraceNotification.type = new messages_1.NotificationType('$/logTraceNotification');
- })(LogTraceNotification = exports.LogTraceNotification || (exports.LogTraceNotification = {}));
- var ConnectionErrors;
- (function (ConnectionErrors) {
- /**
- * The connection is closed.
- */
- ConnectionErrors[ConnectionErrors["Closed"] = 1] = "Closed";
- /**
- * The connection got disposed.
- */
- ConnectionErrors[ConnectionErrors["Disposed"] = 2] = "Disposed";
- /**
- * The connection is already in listening mode.
- */
- ConnectionErrors[ConnectionErrors["AlreadyListening"] = 3] = "AlreadyListening";
- })(ConnectionErrors = exports.ConnectionErrors || (exports.ConnectionErrors = {}));
- class ConnectionError extends Error {
- constructor(code, message) {
- super(message);
- this.code = code;
- Object.setPrototypeOf(this, ConnectionError.prototype);
- }
- }
- exports.ConnectionError = ConnectionError;
- var ConnectionStrategy;
- (function (ConnectionStrategy) {
- function is(value) {
- let candidate = value;
- return candidate && Is.func(candidate.cancelUndispatched);
- }
- ConnectionStrategy.is = is;
- })(ConnectionStrategy = exports.ConnectionStrategy || (exports.ConnectionStrategy = {}));
- var ConnectionState;
- (function (ConnectionState) {
- ConnectionState[ConnectionState["New"] = 1] = "New";
- ConnectionState[ConnectionState["Listening"] = 2] = "Listening";
- ConnectionState[ConnectionState["Closed"] = 3] = "Closed";
- ConnectionState[ConnectionState["Disposed"] = 4] = "Disposed";
- })(ConnectionState || (ConnectionState = {}));
- function _createMessageConnection(messageReader, messageWriter, logger, strategy) {
- let sequenceNumber = 0;
- let notificationSquenceNumber = 0;
- let unknownResponseSquenceNumber = 0;
- const version = '2.0';
- let starRequestHandler = undefined;
- let requestHandlers = Object.create(null);
- let starNotificationHandler = undefined;
- let notificationHandlers = Object.create(null);
- let progressHandlers = new Map();
- let timer;
- let messageQueue = new linkedMap_1.LinkedMap();
- let responsePromises = Object.create(null);
- let requestTokens = Object.create(null);
- let trace = Trace.Off;
- let traceFormat = TraceFormat.Text;
- let tracer;
- let state = ConnectionState.New;
- let errorEmitter = new events_1.Emitter();
- let closeEmitter = new events_1.Emitter();
- let unhandledNotificationEmitter = new events_1.Emitter();
- let unhandledProgressEmitter = new events_1.Emitter();
- let disposeEmitter = new events_1.Emitter();
- function createRequestQueueKey(id) {
- return 'req-' + id.toString();
- }
- function createResponseQueueKey(id) {
- if (id === null) {
- return 'res-unknown-' + (++unknownResponseSquenceNumber).toString();
- }
- else {
- return 'res-' + id.toString();
- }
- }
- function createNotificationQueueKey() {
- return 'not-' + (++notificationSquenceNumber).toString();
- }
- function addMessageToQueue(queue, message) {
- if (messages_1.isRequestMessage(message)) {
- queue.set(createRequestQueueKey(message.id), message);
- }
- else if (messages_1.isResponseMessage(message)) {
- queue.set(createResponseQueueKey(message.id), message);
- }
- else {
- queue.set(createNotificationQueueKey(), message);
- }
- }
- function cancelUndispatched(_message) {
- return undefined;
- }
- function isListening() {
- return state === ConnectionState.Listening;
- }
- function isClosed() {
- return state === ConnectionState.Closed;
- }
- function isDisposed() {
- return state === ConnectionState.Disposed;
- }
- function closeHandler() {
- if (state === ConnectionState.New || state === ConnectionState.Listening) {
- state = ConnectionState.Closed;
- closeEmitter.fire(undefined);
- }
- // If the connection is disposed don't sent close events.
- }
- function readErrorHandler(error) {
- errorEmitter.fire([error, undefined, undefined]);
- }
- function writeErrorHandler(data) {
- errorEmitter.fire(data);
- }
- messageReader.onClose(closeHandler);
- messageReader.onError(readErrorHandler);
- messageWriter.onClose(closeHandler);
- messageWriter.onError(writeErrorHandler);
- function triggerMessageQueue() {
- if (timer || messageQueue.size === 0) {
- return;
- }
- timer = setImmediate(() => {
- timer = undefined;
- processMessageQueue();
- });
- }
- function processMessageQueue() {
- if (messageQueue.size === 0) {
- return;
- }
- let message = messageQueue.shift();
- try {
- if (messages_1.isRequestMessage(message)) {
- handleRequest(message);
- }
- else if (messages_1.isNotificationMessage(message)) {
- handleNotification(message);
- }
- else if (messages_1.isResponseMessage(message)) {
- handleResponse(message);
- }
- else {
- handleInvalidMessage(message);
- }
- }
- finally {
- triggerMessageQueue();
- }
- }
- let callback = (message) => {
- try {
- // We have received a cancellation message. Check if the message is still in the queue
- // and cancel it if allowed to do so.
- if (messages_1.isNotificationMessage(message) && message.method === CancelNotification.type.method) {
- let key = createRequestQueueKey(message.params.id);
- let toCancel = messageQueue.get(key);
- if (messages_1.isRequestMessage(toCancel)) {
- let response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
- if (response && (response.error !== void 0 || response.result !== void 0)) {
- messageQueue.delete(key);
- response.id = toCancel.id;
- traceSendingResponse(response, message.method, Date.now());
- messageWriter.write(response);
- return;
- }
- }
- }
- addMessageToQueue(messageQueue, message);
- }
- finally {
- triggerMessageQueue();
- }
- };
- function handleRequest(requestMessage) {
- if (isDisposed()) {
- // we return here silently since we fired an event when the
- // connection got disposed.
- return;
- }
- function reply(resultOrError, method, startTime) {
- let message = {
- jsonrpc: version,
- id: requestMessage.id
- };
- if (resultOrError instanceof messages_1.ResponseError) {
- message.error = resultOrError.toJson();
- }
- else {
- message.result = resultOrError === void 0 ? null : resultOrError;
- }
- traceSendingResponse(message, method, startTime);
- messageWriter.write(message);
- }
- function replyError(error, method, startTime) {
- let message = {
- jsonrpc: version,
- id: requestMessage.id,
- error: error.toJson()
- };
- traceSendingResponse(message, method, startTime);
- messageWriter.write(message);
- }
- function replySuccess(result, method, startTime) {
- // The JSON RPC defines that a response must either have a result or an error
- // So we can't treat undefined as a valid response result.
- if (result === void 0) {
- result = null;
- }
- let message = {
- jsonrpc: version,
- id: requestMessage.id,
- result: result
- };
- traceSendingResponse(message, method, startTime);
- messageWriter.write(message);
- }
- traceReceivedRequest(requestMessage);
- let element = requestHandlers[requestMessage.method];
- let type;
- let requestHandler;
- if (element) {
- type = element.type;
- requestHandler = element.handler;
- }
- let startTime = Date.now();
- if (requestHandler || starRequestHandler) {
- let cancellationSource = new cancellation_1.CancellationTokenSource();
- let tokenKey = String(requestMessage.id);
- requestTokens[tokenKey] = cancellationSource;
- try {
- let handlerResult;
- if (requestMessage.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
- handlerResult = requestHandler
- ? requestHandler(cancellationSource.token)
- : starRequestHandler(requestMessage.method, cancellationSource.token);
- }
- else if (Is.array(requestMessage.params) && (type === void 0 || type.numberOfParams > 1)) {
- handlerResult = requestHandler
- ? requestHandler(...requestMessage.params, cancellationSource.token)
- : starRequestHandler(requestMessage.method, ...requestMessage.params, cancellationSource.token);
- }
- else {
- handlerResult = requestHandler
- ? requestHandler(requestMessage.params, cancellationSource.token)
- : starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
- }
- let promise = handlerResult;
- if (!handlerResult) {
- delete requestTokens[tokenKey];
- replySuccess(handlerResult, requestMessage.method, startTime);
- }
- else if (promise.then) {
- promise.then((resultOrError) => {
- delete requestTokens[tokenKey];
- reply(resultOrError, requestMessage.method, startTime);
- }, error => {
- delete requestTokens[tokenKey];
- if (error instanceof messages_1.ResponseError) {
- replyError(error, requestMessage.method, startTime);
- }
- else if (error && Is.string(error.message)) {
- replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
- }
- else {
- replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
- }
- });
- }
- else {
- delete requestTokens[tokenKey];
- reply(handlerResult, requestMessage.method, startTime);
- }
- }
- catch (error) {
- delete requestTokens[tokenKey];
- if (error instanceof messages_1.ResponseError) {
- reply(error, requestMessage.method, startTime);
- }
- else if (error && Is.string(error.message)) {
- replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
- }
- else {
- replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
- }
- }
- }
- else {
- replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
- }
- }
- function handleResponse(responseMessage) {
- if (isDisposed()) {
- // See handle request.
- return;
- }
- if (responseMessage.id === null) {
- if (responseMessage.error) {
- logger.error(`Received response message without id: Error is: \n${JSON.stringify(responseMessage.error, undefined, 4)}`);
- }
- else {
- logger.error(`Received response message without id. No further error information provided.`);
- }
- }
- else {
- let key = String(responseMessage.id);
- let responsePromise = responsePromises[key];
- traceReceivedResponse(responseMessage, responsePromise);
- if (responsePromise) {
- delete responsePromises[key];
- try {
- if (responseMessage.error) {
- let error = responseMessage.error;
- responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
- }
- else if (responseMessage.result !== void 0) {
- responsePromise.resolve(responseMessage.result);
- }
- else {
- throw new Error('Should never happen.');
- }
- }
- catch (error) {
- if (error.message) {
- logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
- }
- else {
- logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
- }
- }
- }
- }
- }
- function handleNotification(message) {
- if (isDisposed()) {
- // See handle request.
- return;
- }
- let type = undefined;
- let notificationHandler;
- if (message.method === CancelNotification.type.method) {
- notificationHandler = (params) => {
- let id = params.id;
- let source = requestTokens[String(id)];
- if (source) {
- source.cancel();
- }
- };
- }
- else {
- let element = notificationHandlers[message.method];
- if (element) {
- notificationHandler = element.handler;
- type = element.type;
- }
- }
- if (notificationHandler || starNotificationHandler) {
- try {
- traceReceivedNotification(message);
- if (message.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
- notificationHandler ? notificationHandler() : starNotificationHandler(message.method);
- }
- else if (Is.array(message.params) && (type === void 0 || type.numberOfParams > 1)) {
- notificationHandler ? notificationHandler(...message.params) : starNotificationHandler(message.method, ...message.params);
- }
- else {
- notificationHandler ? notificationHandler(message.params) : starNotificationHandler(message.method, message.params);
- }
- }
- catch (error) {
- if (error.message) {
- logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
- }
- else {
- logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
- }
- }
- }
- else {
- unhandledNotificationEmitter.fire(message);
- }
- }
- function handleInvalidMessage(message) {
- if (!message) {
- logger.error('Received empty message.');
- return;
- }
- logger.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(message, null, 4)}`);
- // Test whether we find an id to reject the promise
- let responseMessage = message;
- if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {
- let key = String(responseMessage.id);
- let responseHandler = responsePromises[key];
- if (responseHandler) {
- responseHandler.reject(new Error('The received response has neither a result nor an error property.'));
- }
- }
- }
- function traceSendingRequest(message) {
- if (trace === Trace.Off || !tracer) {
- return;
- }
- if (traceFormat === TraceFormat.Text) {
- let data = undefined;
- if (trace === Trace.Verbose && message.params) {
- data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
- }
- tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
- }
- else {
- logLSPMessage('send-request', message);
- }
- }
- function traceSendingNotification(message) {
- if (trace === Trace.Off || !tracer) {
- return;
- }
- if (traceFormat === TraceFormat.Text) {
- let data = undefined;
- if (trace === Trace.Verbose) {
- if (message.params) {
- data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
- }
- else {
- data = 'No parameters provided.\n\n';
- }
- }
- tracer.log(`Sending notification '${message.method}'.`, data);
- }
- else {
- logLSPMessage('send-notification', message);
- }
- }
- function traceSendingResponse(message, method, startTime) {
- if (trace === Trace.Off || !tracer) {
- return;
- }
- if (traceFormat === TraceFormat.Text) {
- let data = undefined;
- if (trace === Trace.Verbose) {
- if (message.error && message.error.data) {
- data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
- }
- else {
- if (message.result) {
- data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
- }
- else if (message.error === void 0) {
- data = 'No result returned.\n\n';
- }
- }
- }
- tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
- }
- else {
- logLSPMessage('send-response', message);
- }
- }
- function traceReceivedRequest(message) {
- if (trace === Trace.Off || !tracer) {
- return;
- }
- if (traceFormat === TraceFormat.Text) {
- let data = undefined;
- if (trace === Trace.Verbose && message.params) {
- data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
- }
- tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
- }
- else {
- logLSPMessage('receive-request', message);
- }
- }
- function traceReceivedNotification(message) {
- if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {
- return;
- }
- if (traceFormat === TraceFormat.Text) {
- let data = undefined;
- if (trace === Trace.Verbose) {
- if (message.params) {
- data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
- }
- else {
- data = 'No parameters provided.\n\n';
- }
- }
- tracer.log(`Received notification '${message.method}'.`, data);
- }
- else {
- logLSPMessage('receive-notification', message);
- }
- }
- function traceReceivedResponse(message, responsePromise) {
- if (trace === Trace.Off || !tracer) {
- return;
- }
- if (traceFormat === TraceFormat.Text) {
- let data = undefined;
- if (trace === Trace.Verbose) {
- if (message.error && message.error.data) {
- data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
- }
- else {
- if (message.result) {
- data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
- }
- else if (message.error === void 0) {
- data = 'No result returned.\n\n';
- }
- }
- }
- if (responsePromise) {
- let error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : '';
- tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
- }
- else {
- tracer.log(`Received response ${message.id} without active response promise.`, data);
- }
- }
- else {
- logLSPMessage('receive-response', message);
- }
- }
- function logLSPMessage(type, message) {
- if (!tracer || trace === Trace.Off) {
- return;
- }
- const lspMessage = {
- isLSPMessage: true,
- type,
- message,
- timestamp: Date.now()
- };
- tracer.log(lspMessage);
- }
- function throwIfClosedOrDisposed() {
- if (isClosed()) {
- throw new ConnectionError(ConnectionErrors.Closed, 'Connection is closed.');
- }
- if (isDisposed()) {
- throw new ConnectionError(ConnectionErrors.Disposed, 'Connection is disposed.');
- }
- }
- function throwIfListening() {
- if (isListening()) {
- throw new ConnectionError(ConnectionErrors.AlreadyListening, 'Connection is already listening');
- }
- }
- function throwIfNotListening() {
- if (!isListening()) {
- throw new Error('Call listen() first.');
- }
- }
- function undefinedToNull(param) {
- if (param === void 0) {
- return null;
- }
- else {
- return param;
- }
- }
- function computeMessageParams(type, params) {
- let result;
- let numberOfParams = type.numberOfParams;
- switch (numberOfParams) {
- case 0:
- result = null;
- break;
- case 1:
- result = undefinedToNull(params[0]);
- break;
- default:
- result = [];
- for (let i = 0; i < params.length && i < numberOfParams; i++) {
- result.push(undefinedToNull(params[i]));
- }
- if (params.length < numberOfParams) {
- for (let i = params.length; i < numberOfParams; i++) {
- result.push(null);
- }
- }
- break;
- }
- return result;
- }
- let connection = {
- sendNotification: (type, ...params) => {
- throwIfClosedOrDisposed();
- let method;
- let messageParams;
- if (Is.string(type)) {
- method = type;
- switch (params.length) {
- case 0:
- messageParams = null;
- break;
- case 1:
- messageParams = params[0];
- break;
- default:
- messageParams = params;
- break;
- }
- }
- else {
- method = type.method;
- messageParams = computeMessageParams(type, params);
- }
- let notificationMessage = {
- jsonrpc: version,
- method: method,
- params: messageParams
- };
- traceSendingNotification(notificationMessage);
- messageWriter.write(notificationMessage);
- },
- onNotification: (type, handler) => {
- throwIfClosedOrDisposed();
- if (Is.func(type)) {
- starNotificationHandler = type;
- }
- else if (handler) {
- if (Is.string(type)) {
- notificationHandlers[type] = { type: undefined, handler };
- }
- else {
- notificationHandlers[type.method] = { type, handler };
- }
- }
- },
- onProgress: (_type, token, handler) => {
- if (progressHandlers.has(token)) {
- throw new Error(`Progress handler for token ${token} already registered`);
- }
- progressHandlers.set(token, handler);
- return {
- dispose: () => {
- progressHandlers.delete(token);
- }
- };
- },
- sendProgress: (_type, token, value) => {
- connection.sendNotification(ProgressNotification.type, { token, value });
- },
- onUnhandledProgress: unhandledProgressEmitter.event,
- sendRequest: (type, ...params) => {
- throwIfClosedOrDisposed();
- throwIfNotListening();
- let method;
- let messageParams;
- let token = undefined;
- if (Is.string(type)) {
- method = type;
- switch (params.length) {
- case 0:
- messageParams = null;
- break;
- case 1:
- // The cancellation token is optional so it can also be undefined.
- if (cancellation_1.CancellationToken.is(params[0])) {
- messageParams = null;
- token = params[0];
- }
- else {
- messageParams = undefinedToNull(params[0]);
- }
- break;
- default:
- const last = params.length - 1;
- if (cancellation_1.CancellationToken.is(params[last])) {
- token = params[last];
- if (params.length === 2) {
- messageParams = undefinedToNull(params[0]);
- }
- else {
- messageParams = params.slice(0, last).map(value => undefinedToNull(value));
- }
- }
- else {
- messageParams = params.map(value => undefinedToNull(value));
- }
- break;
- }
- }
- else {
- method = type.method;
- messageParams = computeMessageParams(type, params);
- let numberOfParams = type.numberOfParams;
- token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined;
- }
- let id = sequenceNumber++;
- let result = new Promise((resolve, reject) => {
- let requestMessage = {
- jsonrpc: version,
- id: id,
- method: method,
- params: messageParams
- };
- let responsePromise = { method: method, timerStart: Date.now(), resolve, reject };
- traceSendingRequest(requestMessage);
- try {
- messageWriter.write(requestMessage);
- }
- catch (e) {
- // Writing the message failed. So we need to reject the promise.
- responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : 'Unknown reason'));
- responsePromise = null;
- }
- if (responsePromise) {
- responsePromises[String(id)] = responsePromise;
- }
- });
- if (token) {
- token.onCancellationRequested(() => {
- connection.sendNotification(CancelNotification.type, { id });
- });
- }
- return result;
- },
- onRequest: (type, handler) => {
- throwIfClosedOrDisposed();
- if (Is.func(type)) {
- starRequestHandler = type;
- }
- else if (handler) {
- if (Is.string(type)) {
- requestHandlers[type] = { type: undefined, handler };
- }
- else {
- requestHandlers[type.method] = { type, handler };
- }
- }
- },
- trace: (_value, _tracer, sendNotificationOrTraceOptions) => {
- let _sendNotification = false;
- let _traceFormat = TraceFormat.Text;
- if (sendNotificationOrTraceOptions !== void 0) {
- if (Is.boolean(sendNotificationOrTraceOptions)) {
- _sendNotification = sendNotificationOrTraceOptions;
- }
- else {
- _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
- _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
- }
- }
- trace = _value;
- traceFormat = _traceFormat;
- if (trace === Trace.Off) {
- tracer = undefined;
- }
- else {
- tracer = _tracer;
- }
- if (_sendNotification && !isClosed() && !isDisposed()) {
- connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });
- }
- },
- onError: errorEmitter.event,
- onClose: closeEmitter.event,
- onUnhandledNotification: unhandledNotificationEmitter.event,
- onDispose: disposeEmitter.event,
- dispose: () => {
- if (isDisposed()) {
- return;
- }
- state = ConnectionState.Disposed;
- disposeEmitter.fire(undefined);
- let error = new Error('Connection got disposed.');
- Object.keys(responsePromises).forEach((key) => {
- responsePromises[key].reject(error);
- });
- responsePromises = Object.create(null);
- requestTokens = Object.create(null);
- messageQueue = new linkedMap_1.LinkedMap();
- // Test for backwards compatibility
- if (Is.func(messageWriter.dispose)) {
- messageWriter.dispose();
- }
- if (Is.func(messageReader.dispose)) {
- messageReader.dispose();
- }
- },
- listen: () => {
- throwIfClosedOrDisposed();
- throwIfListening();
- state = ConnectionState.Listening;
- messageReader.listen(callback);
- },
- inspect: () => {
- // eslint-disable-next-line no-console
- console.log('inspect');
- }
- };
- connection.onNotification(LogTraceNotification.type, (params) => {
- if (trace === Trace.Off || !tracer) {
- return;
- }
- tracer.log(params.message, trace === Trace.Verbose ? params.verbose : undefined);
- });
- connection.onNotification(ProgressNotification.type, (params) => {
- const handler = progressHandlers.get(params.token);
- if (handler) {
- handler(params.value);
- }
- else {
- unhandledProgressEmitter.fire(params);
- }
- });
- return connection;
- }
- function isMessageReader(value) {
- return value.listen !== void 0 && value.read === void 0;
- }
- function isMessageWriter(value) {
- return value.write !== void 0 && value.end === void 0;
- }
- function createMessageConnection(input, output, logger, strategy) {
- if (!logger) {
- logger = exports.NullLogger;
- }
- let reader = isMessageReader(input) ? input : new messageReader_1.StreamMessageReader(input);
- let writer = isMessageWriter(output) ? output : new messageWriter_1.StreamMessageWriter(output);
- return _createMessageConnection(reader, writer, logger, strategy);
- }
- exports.createMessageConnection = createMessageConnection;
-
-
- /***/ }),
- /* 5 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- function boolean(value) {
- return value === true || value === false;
- }
- exports.boolean = boolean;
- function string(value) {
- return typeof value === 'string' || value instanceof String;
- }
- exports.string = string;
- function number(value) {
- return typeof value === 'number' || value instanceof Number;
- }
- exports.number = number;
- function error(value) {
- return value instanceof Error;
- }
- exports.error = error;
- function func(value) {
- return typeof value === 'function';
- }
- exports.func = func;
- function array(value) {
- return Array.isArray(value);
- }
- exports.array = array;
- function stringArray(value) {
- return array(value) && value.every(elem => string(elem));
- }
- exports.stringArray = stringArray;
-
-
- /***/ }),
- /* 6 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const is = __webpack_require__(5);
- /**
- * Predefined error codes.
- */
- var ErrorCodes;
- (function (ErrorCodes) {
- // Defined by JSON RPC
- ErrorCodes.ParseError = -32700;
- ErrorCodes.InvalidRequest = -32600;
- ErrorCodes.MethodNotFound = -32601;
- ErrorCodes.InvalidParams = -32602;
- ErrorCodes.InternalError = -32603;
- ErrorCodes.serverErrorStart = -32099;
- ErrorCodes.serverErrorEnd = -32000;
- ErrorCodes.ServerNotInitialized = -32002;
- ErrorCodes.UnknownErrorCode = -32001;
- // Defined by the protocol.
- ErrorCodes.RequestCancelled = -32800;
- ErrorCodes.ContentModified = -32801;
- // Defined by VSCode library.
- ErrorCodes.MessageWriteError = 1;
- ErrorCodes.MessageReadError = 2;
- })(ErrorCodes = exports.ErrorCodes || (exports.ErrorCodes = {}));
- /**
- * An error object return in a response in case a request
- * has failed.
- */
- class ResponseError extends Error {
- constructor(code, message, data) {
- super(message);
- this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;
- this.data = data;
- Object.setPrototypeOf(this, ResponseError.prototype);
- }
- toJson() {
- return {
- code: this.code,
- message: this.message,
- data: this.data,
- };
- }
- }
- exports.ResponseError = ResponseError;
- /**
- * An abstract implementation of a MessageType.
- */
- class AbstractMessageType {
- constructor(_method, _numberOfParams) {
- this._method = _method;
- this._numberOfParams = _numberOfParams;
- }
- get method() {
- return this._method;
- }
- get numberOfParams() {
- return this._numberOfParams;
- }
- }
- exports.AbstractMessageType = AbstractMessageType;
- /**
- * Classes to type request response pairs
- *
- * The type parameter RO will be removed in the next major version
- * of the JSON RPC library since it is a LSP concept and doesn't
- * belong here. For now it is tagged as default never.
- */
- class RequestType0 extends AbstractMessageType {
- constructor(method) {
- super(method, 0);
- }
- }
- exports.RequestType0 = RequestType0;
- class RequestType extends AbstractMessageType {
- constructor(method) {
- super(method, 1);
- }
- }
- exports.RequestType = RequestType;
- class RequestType1 extends AbstractMessageType {
- constructor(method) {
- super(method, 1);
- }
- }
- exports.RequestType1 = RequestType1;
- class RequestType2 extends AbstractMessageType {
- constructor(method) {
- super(method, 2);
- }
- }
- exports.RequestType2 = RequestType2;
- class RequestType3 extends AbstractMessageType {
- constructor(method) {
- super(method, 3);
- }
- }
- exports.RequestType3 = RequestType3;
- class RequestType4 extends AbstractMessageType {
- constructor(method) {
- super(method, 4);
- }
- }
- exports.RequestType4 = RequestType4;
- class RequestType5 extends AbstractMessageType {
- constructor(method) {
- super(method, 5);
- }
- }
- exports.RequestType5 = RequestType5;
- class RequestType6 extends AbstractMessageType {
- constructor(method) {
- super(method, 6);
- }
- }
- exports.RequestType6 = RequestType6;
- class RequestType7 extends AbstractMessageType {
- constructor(method) {
- super(method, 7);
- }
- }
- exports.RequestType7 = RequestType7;
- class RequestType8 extends AbstractMessageType {
- constructor(method) {
- super(method, 8);
- }
- }
- exports.RequestType8 = RequestType8;
- class RequestType9 extends AbstractMessageType {
- constructor(method) {
- super(method, 9);
- }
- }
- exports.RequestType9 = RequestType9;
- /**
- * The type parameter RO will be removed in the next major version
- * of the JSON RPC library since it is a LSP concept and doesn't
- * belong here. For now it is tagged as default never.
- */
- class NotificationType extends AbstractMessageType {
- constructor(method) {
- super(method, 1);
- this._ = undefined;
- }
- }
- exports.NotificationType = NotificationType;
- class NotificationType0 extends AbstractMessageType {
- constructor(method) {
- super(method, 0);
- }
- }
- exports.NotificationType0 = NotificationType0;
- class NotificationType1 extends AbstractMessageType {
- constructor(method) {
- super(method, 1);
- }
- }
- exports.NotificationType1 = NotificationType1;
- class NotificationType2 extends AbstractMessageType {
- constructor(method) {
- super(method, 2);
- }
- }
- exports.NotificationType2 = NotificationType2;
- class NotificationType3 extends AbstractMessageType {
- constructor(method) {
- super(method, 3);
- }
- }
- exports.NotificationType3 = NotificationType3;
- class NotificationType4 extends AbstractMessageType {
- constructor(method) {
- super(method, 4);
- }
- }
- exports.NotificationType4 = NotificationType4;
- class NotificationType5 extends AbstractMessageType {
- constructor(method) {
- super(method, 5);
- }
- }
- exports.NotificationType5 = NotificationType5;
- class NotificationType6 extends AbstractMessageType {
- constructor(method) {
- super(method, 6);
- }
- }
- exports.NotificationType6 = NotificationType6;
- class NotificationType7 extends AbstractMessageType {
- constructor(method) {
- super(method, 7);
- }
- }
- exports.NotificationType7 = NotificationType7;
- class NotificationType8 extends AbstractMessageType {
- constructor(method) {
- super(method, 8);
- }
- }
- exports.NotificationType8 = NotificationType8;
- class NotificationType9 extends AbstractMessageType {
- constructor(method) {
- super(method, 9);
- }
- }
- exports.NotificationType9 = NotificationType9;
- /**
- * Tests if the given message is a request message
- */
- function isRequestMessage(message) {
- let candidate = message;
- return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));
- }
- exports.isRequestMessage = isRequestMessage;
- /**
- * Tests if the given message is a notification message
- */
- function isNotificationMessage(message) {
- let candidate = message;
- return candidate && is.string(candidate.method) && message.id === void 0;
- }
- exports.isNotificationMessage = isNotificationMessage;
- /**
- * Tests if the given message is a response message
- */
- function isResponseMessage(message) {
- let candidate = message;
- return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);
- }
- exports.isResponseMessage = isResponseMessage;
-
-
- /***/ }),
- /* 7 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const events_1 = __webpack_require__(8);
- const Is = __webpack_require__(5);
- let DefaultSize = 8192;
- let CR = Buffer.from('\r', 'ascii')[0];
- let LF = Buffer.from('\n', 'ascii')[0];
- let CRLF = '\r\n';
- class MessageBuffer {
- constructor(encoding = 'utf8') {
- this.encoding = encoding;
- this.index = 0;
- this.buffer = Buffer.allocUnsafe(DefaultSize);
- }
- append(chunk) {
- var toAppend = chunk;
- if (typeof (chunk) === 'string') {
- var str = chunk;
- var bufferLen = Buffer.byteLength(str, this.encoding);
- toAppend = Buffer.allocUnsafe(bufferLen);
- toAppend.write(str, 0, bufferLen, this.encoding);
- }
- if (this.buffer.length - this.index >= toAppend.length) {
- toAppend.copy(this.buffer, this.index, 0, toAppend.length);
- }
- else {
- var newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * DefaultSize;
- if (this.index === 0) {
- this.buffer = Buffer.allocUnsafe(newSize);
- toAppend.copy(this.buffer, 0, 0, toAppend.length);
- }
- else {
- this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
- }
- }
- this.index += toAppend.length;
- }
- tryReadHeaders() {
- let result = undefined;
- let current = 0;
- while (current + 3 < this.index && (this.buffer[current] !== CR || this.buffer[current + 1] !== LF || this.buffer[current + 2] !== CR || this.buffer[current + 3] !== LF)) {
- current++;
- }
- // No header / body separator found (e.g CRLFCRLF)
- if (current + 3 >= this.index) {
- return result;
- }
- result = Object.create(null);
- let headers = this.buffer.toString('ascii', 0, current).split(CRLF);
- headers.forEach((header) => {
- let index = header.indexOf(':');
- if (index === -1) {
- throw new Error('Message header must separate key and value using :');
- }
- let key = header.substr(0, index);
- let value = header.substr(index + 1).trim();
- result[key] = value;
- });
- let nextStart = current + 4;
- this.buffer = this.buffer.slice(nextStart);
- this.index = this.index - nextStart;
- return result;
- }
- tryReadContent(length) {
- if (this.index < length) {
- return null;
- }
- let result = this.buffer.toString(this.encoding, 0, length);
- let nextStart = length;
- this.buffer.copy(this.buffer, 0, nextStart);
- this.index = this.index - nextStart;
- return result;
- }
- get numberOfBytes() {
- return this.index;
- }
- }
- var MessageReader;
- (function (MessageReader) {
- function is(value) {
- let candidate = value;
- return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) &&
- Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);
- }
- MessageReader.is = is;
- })(MessageReader = exports.MessageReader || (exports.MessageReader = {}));
- class AbstractMessageReader {
- constructor() {
- this.errorEmitter = new events_1.Emitter();
- this.closeEmitter = new events_1.Emitter();
- this.partialMessageEmitter = new events_1.Emitter();
- }
- dispose() {
- this.errorEmitter.dispose();
- this.closeEmitter.dispose();
- }
- get onError() {
- return this.errorEmitter.event;
- }
- fireError(error) {
- this.errorEmitter.fire(this.asError(error));
- }
- get onClose() {
- return this.closeEmitter.event;
- }
- fireClose() {
- this.closeEmitter.fire(undefined);
- }
- get onPartialMessage() {
- return this.partialMessageEmitter.event;
- }
- firePartialMessage(info) {
- this.partialMessageEmitter.fire(info);
- }
- asError(error) {
- if (error instanceof Error) {
- return error;
- }
- else {
- return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
- }
- }
- }
- exports.AbstractMessageReader = AbstractMessageReader;
- class StreamMessageReader extends AbstractMessageReader {
- constructor(readable, encoding = 'utf8') {
- super();
- this.readable = readable;
- this.buffer = new MessageBuffer(encoding);
- this._partialMessageTimeout = 10000;
- }
- set partialMessageTimeout(timeout) {
- this._partialMessageTimeout = timeout;
- }
- get partialMessageTimeout() {
- return this._partialMessageTimeout;
- }
- listen(callback) {
- this.nextMessageLength = -1;
- this.messageToken = 0;
- this.partialMessageTimer = undefined;
- this.callback = callback;
- this.readable.on('data', (data) => {
- this.onData(data);
- });
- this.readable.on('error', (error) => this.fireError(error));
- this.readable.on('close', () => this.fireClose());
- }
- onData(data) {
- this.buffer.append(data);
- while (true) {
- if (this.nextMessageLength === -1) {
- let headers = this.buffer.tryReadHeaders();
- if (!headers) {
- return;
- }
- let contentLength = headers['Content-Length'];
- if (!contentLength) {
- throw new Error('Header must provide a Content-Length property.');
- }
- let length = parseInt(contentLength);
- if (isNaN(length)) {
- throw new Error('Content-Length value must be a number.');
- }
- this.nextMessageLength = length;
- // Take the encoding form the header. For compatibility
- // treat both utf-8 and utf8 as node utf8
- }
- var msg = this.buffer.tryReadContent(this.nextMessageLength);
- if (msg === null) {
- /** We haven't received the full message yet. */
- this.setPartialMessageTimer();
- return;
- }
- this.clearPartialMessageTimer();
- this.nextMessageLength = -1;
- this.messageToken++;
- var json = JSON.parse(msg);
- this.callback(json);
- }
- }
- clearPartialMessageTimer() {
- if (this.partialMessageTimer) {
- clearTimeout(this.partialMessageTimer);
- this.partialMessageTimer = undefined;
- }
- }
- setPartialMessageTimer() {
- this.clearPartialMessageTimer();
- if (this._partialMessageTimeout <= 0) {
- return;
- }
- this.partialMessageTimer = setTimeout((token, timeout) => {
- this.partialMessageTimer = undefined;
- if (token === this.messageToken) {
- this.firePartialMessage({ messageToken: token, waitingTime: timeout });
- this.setPartialMessageTimer();
- }
- }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
- }
- }
- exports.StreamMessageReader = StreamMessageReader;
- class IPCMessageReader extends AbstractMessageReader {
- constructor(process) {
- super();
- this.process = process;
- let eventEmitter = this.process;
- eventEmitter.on('error', (error) => this.fireError(error));
- eventEmitter.on('close', () => this.fireClose());
- }
- listen(callback) {
- this.process.on('message', callback);
- }
- }
- exports.IPCMessageReader = IPCMessageReader;
- class SocketMessageReader extends StreamMessageReader {
- constructor(socket, encoding = 'utf-8') {
- super(socket, encoding);
- }
- }
- exports.SocketMessageReader = SocketMessageReader;
-
-
- /***/ }),
- /* 8 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- var Disposable;
- (function (Disposable) {
- function create(func) {
- return {
- dispose: func
- };
- }
- Disposable.create = create;
- })(Disposable = exports.Disposable || (exports.Disposable = {}));
- var Event;
- (function (Event) {
- const _disposable = { dispose() { } };
- Event.None = function () { return _disposable; };
- })(Event = exports.Event || (exports.Event = {}));
- class CallbackList {
- add(callback, context = null, bucket) {
- if (!this._callbacks) {
- this._callbacks = [];
- this._contexts = [];
- }
- this._callbacks.push(callback);
- this._contexts.push(context);
- if (Array.isArray(bucket)) {
- bucket.push({ dispose: () => this.remove(callback, context) });
- }
- }
- remove(callback, context = null) {
- if (!this._callbacks) {
- return;
- }
- var foundCallbackWithDifferentContext = false;
- for (var i = 0, len = this._callbacks.length; i < len; i++) {
- if (this._callbacks[i] === callback) {
- if (this._contexts[i] === context) {
- // callback & context match => remove it
- this._callbacks.splice(i, 1);
- this._contexts.splice(i, 1);
- return;
- }
- else {
- foundCallbackWithDifferentContext = true;
- }
- }
- }
- if (foundCallbackWithDifferentContext) {
- throw new Error('When adding a listener with a context, you should remove it with the same context');
- }
- }
- invoke(...args) {
- if (!this._callbacks) {
- return [];
- }
- var ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
- for (var i = 0, len = callbacks.length; i < len; i++) {
- try {
- ret.push(callbacks[i].apply(contexts[i], args));
- }
- catch (e) {
- // eslint-disable-next-line no-console
- console.error(e);
- }
- }
- return ret;
- }
- isEmpty() {
- return !this._callbacks || this._callbacks.length === 0;
- }
- dispose() {
- this._callbacks = undefined;
- this._contexts = undefined;
- }
- }
- class Emitter {
- constructor(_options) {
- this._options = _options;
- }
- /**
- * For the public to allow to subscribe
- * to events from this Emitter
- */
- get event() {
- if (!this._event) {
- this._event = (listener, thisArgs, disposables) => {
- if (!this._callbacks) {
- this._callbacks = new CallbackList();
- }
- if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
- this._options.onFirstListenerAdd(this);
- }
- this._callbacks.add(listener, thisArgs);
- let result;
- result = {
- dispose: () => {
- this._callbacks.remove(listener, thisArgs);
- result.dispose = Emitter._noop;
- if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
- this._options.onLastListenerRemove(this);
- }
- }
- };
- if (Array.isArray(disposables)) {
- disposables.push(result);
- }
- return result;
- };
- }
- return this._event;
- }
- /**
- * To be kept private to fire an event to
- * subscribers
- */
- fire(event) {
- if (this._callbacks) {
- this._callbacks.invoke.call(this._callbacks, event);
- }
- }
- dispose() {
- if (this._callbacks) {
- this._callbacks.dispose();
- this._callbacks = undefined;
- }
- }
- }
- exports.Emitter = Emitter;
- Emitter._noop = function () { };
-
-
- /***/ }),
- /* 9 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const events_1 = __webpack_require__(8);
- const Is = __webpack_require__(5);
- let ContentLength = 'Content-Length: ';
- let CRLF = '\r\n';
- var MessageWriter;
- (function (MessageWriter) {
- function is(value) {
- let candidate = value;
- return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) &&
- Is.func(candidate.onError) && Is.func(candidate.write);
- }
- MessageWriter.is = is;
- })(MessageWriter = exports.MessageWriter || (exports.MessageWriter = {}));
- class AbstractMessageWriter {
- constructor() {
- this.errorEmitter = new events_1.Emitter();
- this.closeEmitter = new events_1.Emitter();
- }
- dispose() {
- this.errorEmitter.dispose();
- this.closeEmitter.dispose();
- }
- get onError() {
- return this.errorEmitter.event;
- }
- fireError(error, message, count) {
- this.errorEmitter.fire([this.asError(error), message, count]);
- }
- get onClose() {
- return this.closeEmitter.event;
- }
- fireClose() {
- this.closeEmitter.fire(undefined);
- }
- asError(error) {
- if (error instanceof Error) {
- return error;
- }
- else {
- return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
- }
- }
- }
- exports.AbstractMessageWriter = AbstractMessageWriter;
- class StreamMessageWriter extends AbstractMessageWriter {
- constructor(writable, encoding = 'utf8') {
- super();
- this.writable = writable;
- this.encoding = encoding;
- this.errorCount = 0;
- this.writable.on('error', (error) => this.fireError(error));
- this.writable.on('close', () => this.fireClose());
- }
- write(msg) {
- let json = JSON.stringify(msg);
- let contentLength = Buffer.byteLength(json, this.encoding);
- let headers = [
- ContentLength, contentLength.toString(), CRLF,
- CRLF
- ];
- try {
- // Header must be written in ASCII encoding
- this.writable.write(headers.join(''), 'ascii');
- // Now write the content. This can be written in any encoding
- this.writable.write(json, this.encoding);
- this.errorCount = 0;
- }
- catch (error) {
- this.errorCount++;
- this.fireError(error, msg, this.errorCount);
- }
- }
- }
- exports.StreamMessageWriter = StreamMessageWriter;
- class IPCMessageWriter extends AbstractMessageWriter {
- constructor(process) {
- super();
- this.process = process;
- this.errorCount = 0;
- this.queue = [];
- this.sending = false;
- let eventEmitter = this.process;
- eventEmitter.on('error', (error) => this.fireError(error));
- eventEmitter.on('close', () => this.fireClose);
- }
- write(msg) {
- if (!this.sending && this.queue.length === 0) {
- // See https://github.com/nodejs/node/issues/7657
- this.doWriteMessage(msg);
- }
- else {
- this.queue.push(msg);
- }
- }
- doWriteMessage(msg) {
- try {
- if (this.process.send) {
- this.sending = true;
- this.process.send(msg, undefined, undefined, (error) => {
- this.sending = false;
- if (error) {
- this.errorCount++;
- this.fireError(error, msg, this.errorCount);
- }
- else {
- this.errorCount = 0;
- }
- if (this.queue.length > 0) {
- this.doWriteMessage(this.queue.shift());
- }
- });
- }
- }
- catch (error) {
- this.errorCount++;
- this.fireError(error, msg, this.errorCount);
- }
- }
- }
- exports.IPCMessageWriter = IPCMessageWriter;
- class SocketMessageWriter extends AbstractMessageWriter {
- constructor(socket, encoding = 'utf8') {
- super();
- this.socket = socket;
- this.queue = [];
- this.sending = false;
- this.encoding = encoding;
- this.errorCount = 0;
- this.socket.on('error', (error) => this.fireError(error));
- this.socket.on('close', () => this.fireClose());
- }
- dispose() {
- super.dispose();
- this.socket.destroy();
- }
- write(msg) {
- if (!this.sending && this.queue.length === 0) {
- // See https://github.com/nodejs/node/issues/7657
- this.doWriteMessage(msg);
- }
- else {
- this.queue.push(msg);
- }
- }
- doWriteMessage(msg) {
- let json = JSON.stringify(msg);
- let contentLength = Buffer.byteLength(json, this.encoding);
- let headers = [
- ContentLength, contentLength.toString(), CRLF,
- CRLF
- ];
- try {
- // Header must be written in ASCII encoding
- this.sending = true;
- this.socket.write(headers.join(''), 'ascii', (error) => {
- if (error) {
- this.handleError(error, msg);
- }
- try {
- // Now write the content. This can be written in any encoding
- this.socket.write(json, this.encoding, (error) => {
- this.sending = false;
- if (error) {
- this.handleError(error, msg);
- }
- else {
- this.errorCount = 0;
- }
- if (this.queue.length > 0) {
- this.doWriteMessage(this.queue.shift());
- }
- });
- }
- catch (error) {
- this.handleError(error, msg);
- }
- });
- }
- catch (error) {
- this.handleError(error, msg);
- }
- }
- handleError(error, msg) {
- this.errorCount++;
- this.fireError(error, msg, this.errorCount);
- }
- }
- exports.SocketMessageWriter = SocketMessageWriter;
-
-
- /***/ }),
- /* 10 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const events_1 = __webpack_require__(8);
- const Is = __webpack_require__(5);
- var CancellationToken;
- (function (CancellationToken) {
- CancellationToken.None = Object.freeze({
- isCancellationRequested: false,
- onCancellationRequested: events_1.Event.None
- });
- CancellationToken.Cancelled = Object.freeze({
- isCancellationRequested: true,
- onCancellationRequested: events_1.Event.None
- });
- function is(value) {
- let candidate = value;
- return candidate && (candidate === CancellationToken.None
- || candidate === CancellationToken.Cancelled
- || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested));
- }
- CancellationToken.is = is;
- })(CancellationToken = exports.CancellationToken || (exports.CancellationToken = {}));
- const shortcutEvent = Object.freeze(function (callback, context) {
- let handle = setTimeout(callback.bind(context), 0);
- return { dispose() { clearTimeout(handle); } };
- });
- class MutableToken {
- constructor() {
- this._isCancelled = false;
- }
- cancel() {
- if (!this._isCancelled) {
- this._isCancelled = true;
- if (this._emitter) {
- this._emitter.fire(undefined);
- this.dispose();
- }
- }
- }
- get isCancellationRequested() {
- return this._isCancelled;
- }
- get onCancellationRequested() {
- if (this._isCancelled) {
- return shortcutEvent;
- }
- if (!this._emitter) {
- this._emitter = new events_1.Emitter();
- }
- return this._emitter.event;
- }
- dispose() {
- if (this._emitter) {
- this._emitter.dispose();
- this._emitter = undefined;
- }
- }
- }
- class CancellationTokenSource {
- get token() {
- if (!this._token) {
- // be lazy and create the token only when
- // actually needed
- this._token = new MutableToken();
- }
- return this._token;
- }
- cancel() {
- if (!this._token) {
- // save an object by returning the default
- // cancelled token when cancellation happens
- // before someone asks for the token
- this._token = CancellationToken.Cancelled;
- }
- else {
- this._token.cancel();
- }
- }
- dispose() {
- if (!this._token) {
- // ensure to initialize with an empty token if we had none
- this._token = CancellationToken.None;
- }
- else if (this._token instanceof MutableToken) {
- // actually dispose
- this._token.dispose();
- }
- }
- }
- exports.CancellationTokenSource = CancellationTokenSource;
-
-
- /***/ }),
- /* 11 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- Object.defineProperty(exports, "__esModule", { value: true });
- var Touch;
- (function (Touch) {
- Touch.None = 0;
- Touch.First = 1;
- Touch.Last = 2;
- })(Touch = exports.Touch || (exports.Touch = {}));
- class LinkedMap {
- constructor() {
- this._map = new Map();
- this._head = undefined;
- this._tail = undefined;
- this._size = 0;
- }
- clear() {
- this._map.clear();
- this._head = undefined;
- this._tail = undefined;
- this._size = 0;
- }
- isEmpty() {
- return !this._head && !this._tail;
- }
- get size() {
- return this._size;
- }
- has(key) {
- return this._map.has(key);
- }
- get(key) {
- const item = this._map.get(key);
- if (!item) {
- return undefined;
- }
- return item.value;
- }
- set(key, value, touch = Touch.None) {
- let item = this._map.get(key);
- if (item) {
- item.value = value;
- if (touch !== Touch.None) {
- this.touch(item, touch);
- }
- }
- else {
- item = { key, value, next: undefined, previous: undefined };
- switch (touch) {
- case Touch.None:
- this.addItemLast(item);
- break;
- case Touch.First:
- this.addItemFirst(item);
- break;
- case Touch.Last:
- this.addItemLast(item);
- break;
- default:
- this.addItemLast(item);
- break;
- }
- this._map.set(key, item);
- this._size++;
- }
- }
- delete(key) {
- const item = this._map.get(key);
- if (!item) {
- return false;
- }
- this._map.delete(key);
- this.removeItem(item);
- this._size--;
- return true;
- }
- shift() {
- if (!this._head && !this._tail) {
- return undefined;
- }
- if (!this._head || !this._tail) {
- throw new Error('Invalid list');
- }
- const item = this._head;
- this._map.delete(item.key);
- this.removeItem(item);
- this._size--;
- return item.value;
- }
- forEach(callbackfn, thisArg) {
- let current = this._head;
- while (current) {
- if (thisArg) {
- callbackfn.bind(thisArg)(current.value, current.key, this);
- }
- else {
- callbackfn(current.value, current.key, this);
- }
- current = current.next;
- }
- }
- forEachReverse(callbackfn, thisArg) {
- let current = this._tail;
- while (current) {
- if (thisArg) {
- callbackfn.bind(thisArg)(current.value, current.key, this);
- }
- else {
- callbackfn(current.value, current.key, this);
- }
- current = current.previous;
- }
- }
- values() {
- let result = [];
- let current = this._head;
- while (current) {
- result.push(current.value);
- current = current.next;
- }
- return result;
- }
- keys() {
- let result = [];
- let current = this._head;
- while (current) {
- result.push(current.key);
- current = current.next;
- }
- return result;
- }
- /* JSON RPC run on es5 which has no Symbol.iterator
- public keys(): IterableIterator<K> {
- let current = this._head;
- let iterator: IterableIterator<K> = {
- [Symbol.iterator]() {
- return iterator;
- },
- next():IteratorResult<K> {
- if (current) {
- let result = { value: current.key, done: false };
- current = current.next;
- return result;
- } else {
- return { value: undefined, done: true };
- }
- }
- };
- return iterator;
- }
-
- public values(): IterableIterator<V> {
- let current = this._head;
- let iterator: IterableIterator<V> = {
- [Symbol.iterator]() {
- return iterator;
- },
- next():IteratorResult<V> {
- if (current) {
- let result = { value: current.value, done: false };
- current = current.next;
- return result;
- } else {
- return { value: undefined, done: true };
- }
- }
- };
- return iterator;
- }
- */
- addItemFirst(item) {
- // First time Insert
- if (!this._head && !this._tail) {
- this._tail = item;
- }
- else if (!this._head) {
- throw new Error('Invalid list');
- }
- else {
- item.next = this._head;
- this._head.previous = item;
- }
- this._head = item;
- }
- addItemLast(item) {
- // First time Insert
- if (!this._head && !this._tail) {
- this._head = item;
- }
- else if (!this._tail) {
- throw new Error('Invalid list');
- }
- else {
- item.previous = this._tail;
- this._tail.next = item;
- }
- this._tail = item;
- }
- removeItem(item) {
- if (item === this._head && item === this._tail) {
- this._head = undefined;
- this._tail = undefined;
- }
- else if (item === this._head) {
- this._head = item.next;
- }
- else if (item === this._tail) {
- this._tail = item.previous;
- }
- else {
- const next = item.next;
- const previous = item.previous;
- if (!next || !previous) {
- throw new Error('Invalid list');
- }
- next.previous = previous;
- previous.next = next;
- }
- }
- touch(item, touch) {
- if (!this._head || !this._tail) {
- throw new Error('Invalid list');
- }
- if ((touch !== Touch.First && touch !== Touch.Last)) {
- return;
- }
- if (touch === Touch.First) {
- if (item === this._head) {
- return;
- }
- const next = item.next;
- const previous = item.previous;
- // Unlink the item
- if (item === this._tail) {
- // previous must be defined since item was not head but is tail
- // So there are more than on item in the map
- previous.next = undefined;
- this._tail = previous;
- }
- else {
- // Both next and previous are not undefined since item was neither head nor tail.
- next.previous = previous;
- previous.next = next;
- }
- // Insert the node at head
- item.previous = undefined;
- item.next = this._head;
- this._head.previous = item;
- this._head = item;
- }
- else if (touch === Touch.Last) {
- if (item === this._tail) {
- return;
- }
- const next = item.next;
- const previous = item.previous;
- // Unlink the item.
- if (item === this._head) {
- // next must be defined since item was not tail but is head
- // So there are more than on item in the map
- next.previous = undefined;
- this._head = next;
- }
- else {
- // Both next and previous are not undefined since item was neither head nor tail.
- next.previous = previous;
- previous.next = next;
- }
- item.next = undefined;
- item.previous = this._tail;
- this._tail.next = item;
- this._tail = item;
- }
- }
- }
- exports.LinkedMap = LinkedMap;
-
-
- /***/ }),
- /* 12 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const path_1 = __webpack_require__(13);
- const os_1 = __webpack_require__(14);
- const crypto_1 = __webpack_require__(15);
- const net_1 = __webpack_require__(16);
- const messageReader_1 = __webpack_require__(7);
- const messageWriter_1 = __webpack_require__(9);
- function generateRandomPipeName() {
- const randomSuffix = crypto_1.randomBytes(21).toString('hex');
- if (process.platform === 'win32') {
- return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`;
- }
- else {
- // Mac/Unix: use socket file
- return path_1.join(os_1.tmpdir(), `vscode-${randomSuffix}.sock`);
- }
- }
- exports.generateRandomPipeName = generateRandomPipeName;
- function createClientPipeTransport(pipeName, encoding = 'utf-8') {
- let connectResolve;
- let connected = new Promise((resolve, _reject) => {
- connectResolve = resolve;
- });
- return new Promise((resolve, reject) => {
- let server = net_1.createServer((socket) => {
- server.close();
- connectResolve([
- new messageReader_1.SocketMessageReader(socket, encoding),
- new messageWriter_1.SocketMessageWriter(socket, encoding)
- ]);
- });
- server.on('error', reject);
- server.listen(pipeName, () => {
- server.removeListener('error', reject);
- resolve({
- onConnected: () => { return connected; }
- });
- });
- });
- }
- exports.createClientPipeTransport = createClientPipeTransport;
- function createServerPipeTransport(pipeName, encoding = 'utf-8') {
- const socket = net_1.createConnection(pipeName);
- return [
- new messageReader_1.SocketMessageReader(socket, encoding),
- new messageWriter_1.SocketMessageWriter(socket, encoding)
- ];
- }
- exports.createServerPipeTransport = createServerPipeTransport;
-
-
- /***/ }),
- /* 13 */
- /***/ (function(module, exports) {
-
- module.exports = require("path");
-
- /***/ }),
- /* 14 */
- /***/ (function(module, exports) {
-
- module.exports = require("os");
-
- /***/ }),
- /* 15 */
- /***/ (function(module, exports) {
-
- module.exports = require("crypto");
-
- /***/ }),
- /* 16 */
- /***/ (function(module, exports) {
-
- module.exports = require("net");
-
- /***/ }),
- /* 17 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const net_1 = __webpack_require__(16);
- const messageReader_1 = __webpack_require__(7);
- const messageWriter_1 = __webpack_require__(9);
- function createClientSocketTransport(port, encoding = 'utf-8') {
- let connectResolve;
- let connected = new Promise((resolve, _reject) => {
- connectResolve = resolve;
- });
- return new Promise((resolve, reject) => {
- let server = net_1.createServer((socket) => {
- server.close();
- connectResolve([
- new messageReader_1.SocketMessageReader(socket, encoding),
- new messageWriter_1.SocketMessageWriter(socket, encoding)
- ]);
- });
- server.on('error', reject);
- server.listen(port, '127.0.0.1', () => {
- server.removeListener('error', reject);
- resolve({
- onConnected: () => { return connected; }
- });
- });
- });
- }
- exports.createClientSocketTransport = createClientSocketTransport;
- function createServerSocketTransport(port, encoding = 'utf-8') {
- const socket = net_1.createConnection(port, '127.0.0.1');
- return [
- new messageReader_1.SocketMessageReader(socket, encoding),
- new messageWriter_1.SocketMessageWriter(socket, encoding)
- ];
- }
- exports.createServerSocketTransport = createServerSocketTransport;
-
-
- /***/ }),
- /* 18 */
- /***/ (function(module, __webpack_exports__, __webpack_require__) {
-
- "use strict";
- __webpack_require__.r(__webpack_exports__);
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Position", function() { return Position; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return Range; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Location", function() { return Location; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocationLink", function() { return LocationLink; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return Color; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return ColorInformation; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return ColorPresentation; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return FoldingRangeKind; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return FoldingRange; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticRelatedInformation", function() { return DiagnosticRelatedInformation; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticSeverity", function() { return DiagnosticSeverity; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticTag", function() { return DiagnosticTag; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Diagnostic", function() { return Diagnostic; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Command", function() { return Command; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return TextEdit; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentEdit", function() { return TextDocumentEdit; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CreateFile", function() { return CreateFile; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenameFile", function() { return RenameFile; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeleteFile", function() { return DeleteFile; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceEdit", function() { return WorkspaceEdit; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceChange", function() { return WorkspaceChange; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentIdentifier", function() { return TextDocumentIdentifier; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VersionedTextDocumentIdentifier", function() { return VersionedTextDocumentIdentifier; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentItem", function() { return TextDocumentItem; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupKind", function() { return MarkupKind; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupContent", function() { return MarkupContent; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemKind", function() { return CompletionItemKind; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InsertTextFormat", function() { return InsertTextFormat; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemTag", function() { return CompletionItemTag; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItem", function() { return CompletionItem; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionList", function() { return CompletionList; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkedString", function() { return MarkedString; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Hover", function() { return Hover; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParameterInformation", function() { return ParameterInformation; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignatureInformation", function() { return SignatureInformation; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlightKind", function() { return DocumentHighlightKind; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlight", function() { return DocumentHighlight; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolKind", function() { return SymbolKind; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolTag", function() { return SymbolTag; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolInformation", function() { return SymbolInformation; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentSymbol", function() { return DocumentSymbol; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionKind", function() { return CodeActionKind; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionContext", function() { return CodeActionContext; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeAction", function() { return CodeAction; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeLens", function() { return CodeLens; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FormattingOptions", function() { return FormattingOptions; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentLink", function() { return DocumentLink; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SelectionRange", function() { return SelectionRange; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EOL", function() { return EOL; });
- /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return TextDocument; });
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- /**
- * The Position namespace provides helper functions to work with
- * [Position](#Position) literals.
- */
- var Position;
- (function (Position) {
- /**
- * Creates a new Position literal from the given line and character.
- * @param line The position's line.
- * @param character The position's character.
- */
- function create(line, character) {
- return { line: line, character: character };
- }
- Position.create = create;
- /**
- * Checks whether the given liternal conforms to the [Position](#Position) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character);
- }
- Position.is = is;
- })(Position || (Position = {}));
- /**
- * The Range namespace provides helper functions to work with
- * [Range](#Range) literals.
- */
- var Range;
- (function (Range) {
- function create(one, two, three, four) {
- if (Is.number(one) && Is.number(two) && Is.number(three) && Is.number(four)) {
- return { start: Position.create(one, two), end: Position.create(three, four) };
- }
- else if (Position.is(one) && Position.is(two)) {
- return { start: one, end: two };
- }
- else {
- throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
- }
- }
- Range.create = create;
- /**
- * Checks whether the given literal conforms to the [Range](#Range) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
- }
- Range.is = is;
- })(Range || (Range = {}));
- /**
- * The Location namespace provides helper functions to work with
- * [Location](#Location) literals.
- */
- var Location;
- (function (Location) {
- /**
- * Creates a Location literal.
- * @param uri The location's uri.
- * @param range The location's range.
- */
- function create(uri, range) {
- return { uri: uri, range: range };
- }
- Location.create = create;
- /**
- * Checks whether the given literal conforms to the [Location](#Location) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
- }
- Location.is = is;
- })(Location || (Location = {}));
- /**
- * The LocationLink namespace provides helper functions to work with
- * [LocationLink](#LocationLink) literals.
- */
- var LocationLink;
- (function (LocationLink) {
- /**
- * Creates a LocationLink literal.
- * @param targetUri The definition's uri.
- * @param targetRange The full range of the definition.
- * @param targetSelectionRange The span of the symbol definition at the target.
- * @param originSelectionRange The span of the symbol being defined in the originating source file.
- */
- function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
- return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };
- }
- LocationLink.create = create;
- /**
- * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)
- && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange))
- && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
- }
- LocationLink.is = is;
- })(LocationLink || (LocationLink = {}));
- /**
- * The Color namespace provides helper functions to work with
- * [Color](#Color) literals.
- */
- var Color;
- (function (Color) {
- /**
- * Creates a new Color literal.
- */
- function create(red, green, blue, alpha) {
- return {
- red: red,
- green: green,
- blue: blue,
- alpha: alpha,
- };
- }
- Color.create = create;
- /**
- * Checks whether the given literal conforms to the [Color](#Color) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.number(candidate.red)
- && Is.number(candidate.green)
- && Is.number(candidate.blue)
- && Is.number(candidate.alpha);
- }
- Color.is = is;
- })(Color || (Color = {}));
- /**
- * The ColorInformation namespace provides helper functions to work with
- * [ColorInformation](#ColorInformation) literals.
- */
- var ColorInformation;
- (function (ColorInformation) {
- /**
- * Creates a new ColorInformation literal.
- */
- function create(range, color) {
- return {
- range: range,
- color: color,
- };
- }
- ColorInformation.create = create;
- /**
- * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
- */
- function is(value) {
- var candidate = value;
- return Range.is(candidate.range) && Color.is(candidate.color);
- }
- ColorInformation.is = is;
- })(ColorInformation || (ColorInformation = {}));
- /**
- * The Color namespace provides helper functions to work with
- * [ColorPresentation](#ColorPresentation) literals.
- */
- var ColorPresentation;
- (function (ColorPresentation) {
- /**
- * Creates a new ColorInformation literal.
- */
- function create(label, textEdit, additionalTextEdits) {
- return {
- label: label,
- textEdit: textEdit,
- additionalTextEdits: additionalTextEdits,
- };
- }
- ColorPresentation.create = create;
- /**
- * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.string(candidate.label)
- && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))
- && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
- }
- ColorPresentation.is = is;
- })(ColorPresentation || (ColorPresentation = {}));
- /**
- * Enum of known range kinds
- */
- var FoldingRangeKind;
- (function (FoldingRangeKind) {
- /**
- * Folding range for a comment
- */
- FoldingRangeKind["Comment"] = "comment";
- /**
- * Folding range for a imports or includes
- */
- FoldingRangeKind["Imports"] = "imports";
- /**
- * Folding range for a region (e.g. `#region`)
- */
- FoldingRangeKind["Region"] = "region";
- })(FoldingRangeKind || (FoldingRangeKind = {}));
- /**
- * The folding range namespace provides helper functions to work with
- * [FoldingRange](#FoldingRange) literals.
- */
- var FoldingRange;
- (function (FoldingRange) {
- /**
- * Creates a new FoldingRange literal.
- */
- function create(startLine, endLine, startCharacter, endCharacter, kind) {
- var result = {
- startLine: startLine,
- endLine: endLine
- };
- if (Is.defined(startCharacter)) {
- result.startCharacter = startCharacter;
- }
- if (Is.defined(endCharacter)) {
- result.endCharacter = endCharacter;
- }
- if (Is.defined(kind)) {
- result.kind = kind;
- }
- return result;
- }
- FoldingRange.create = create;
- /**
- * Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.number(candidate.startLine) && Is.number(candidate.startLine)
- && (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter))
- && (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter))
- && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
- }
- FoldingRange.is = is;
- })(FoldingRange || (FoldingRange = {}));
- /**
- * The DiagnosticRelatedInformation namespace provides helper functions to work with
- * [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals.
- */
- var DiagnosticRelatedInformation;
- (function (DiagnosticRelatedInformation) {
- /**
- * Creates a new DiagnosticRelatedInformation literal.
- */
- function create(location, message) {
- return {
- location: location,
- message: message
- };
- }
- DiagnosticRelatedInformation.create = create;
- /**
- * Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
- }
- DiagnosticRelatedInformation.is = is;
- })(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
- /**
- * The diagnostic's severity.
- */
- var DiagnosticSeverity;
- (function (DiagnosticSeverity) {
- /**
- * Reports an error.
- */
- DiagnosticSeverity.Error = 1;
- /**
- * Reports a warning.
- */
- DiagnosticSeverity.Warning = 2;
- /**
- * Reports an information.
- */
- DiagnosticSeverity.Information = 3;
- /**
- * Reports a hint.
- */
- DiagnosticSeverity.Hint = 4;
- })(DiagnosticSeverity || (DiagnosticSeverity = {}));
- /**
- * The diagnostic tags.
- *
- * @since 3.15.0
- */
- var DiagnosticTag;
- (function (DiagnosticTag) {
- /**
- * Unused or unnecessary code.
- *
- * Clients are allowed to render diagnostics with this tag faded out instead of having
- * an error squiggle.
- */
- DiagnosticTag.Unnecessary = 1;
- /**
- * Deprecated or obsolete code.
- *
- * Clients are allowed to rendered diagnostics with this tag strike through.
- */
- DiagnosticTag.Deprecated = 2;
- })(DiagnosticTag || (DiagnosticTag = {}));
- /**
- * The Diagnostic namespace provides helper functions to work with
- * [Diagnostic](#Diagnostic) literals.
- */
- var Diagnostic;
- (function (Diagnostic) {
- /**
- * Creates a new Diagnostic literal.
- */
- function create(range, message, severity, code, source, relatedInformation) {
- var result = { range: range, message: message };
- if (Is.defined(severity)) {
- result.severity = severity;
- }
- if (Is.defined(code)) {
- result.code = code;
- }
- if (Is.defined(source)) {
- result.source = source;
- }
- if (Is.defined(relatedInformation)) {
- result.relatedInformation = relatedInformation;
- }
- return result;
- }
- Diagnostic.create = create;
- /**
- * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate)
- && Range.is(candidate.range)
- && Is.string(candidate.message)
- && (Is.number(candidate.severity) || Is.undefined(candidate.severity))
- && (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))
- && (Is.string(candidate.source) || Is.undefined(candidate.source))
- && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
- }
- Diagnostic.is = is;
- })(Diagnostic || (Diagnostic = {}));
- /**
- * The Command namespace provides helper functions to work with
- * [Command](#Command) literals.
- */
- var Command;
- (function (Command) {
- /**
- * Creates a new Command literal.
- */
- function create(title, command) {
- var args = [];
- for (var _i = 2; _i < arguments.length; _i++) {
- args[_i - 2] = arguments[_i];
- }
- var result = { title: title, command: command };
- if (Is.defined(args) && args.length > 0) {
- result.arguments = args;
- }
- return result;
- }
- Command.create = create;
- /**
- * Checks whether the given literal conforms to the [Command](#Command) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
- }
- Command.is = is;
- })(Command || (Command = {}));
- /**
- * The TextEdit namespace provides helper function to create replace,
- * insert and delete edits more easily.
- */
- var TextEdit;
- (function (TextEdit) {
- /**
- * Creates a replace text edit.
- * @param range The range of text to be replaced.
- * @param newText The new text.
- */
- function replace(range, newText) {
- return { range: range, newText: newText };
- }
- TextEdit.replace = replace;
- /**
- * Creates a insert text edit.
- * @param position The position to insert the text at.
- * @param newText The text to be inserted.
- */
- function insert(position, newText) {
- return { range: { start: position, end: position }, newText: newText };
- }
- TextEdit.insert = insert;
- /**
- * Creates a delete text edit.
- * @param range The range of text to be deleted.
- */
- function del(range) {
- return { range: range, newText: '' };
- }
- TextEdit.del = del;
- function is(value) {
- var candidate = value;
- return Is.objectLiteral(candidate)
- && Is.string(candidate.newText)
- && Range.is(candidate.range);
- }
- TextEdit.is = is;
- })(TextEdit || (TextEdit = {}));
- /**
- * The TextDocumentEdit namespace provides helper function to create
- * an edit that manipulates a text document.
- */
- var TextDocumentEdit;
- (function (TextDocumentEdit) {
- /**
- * Creates a new `TextDocumentEdit`
- */
- function create(textDocument, edits) {
- return { textDocument: textDocument, edits: edits };
- }
- TextDocumentEdit.create = create;
- function is(value) {
- var candidate = value;
- return Is.defined(candidate)
- && VersionedTextDocumentIdentifier.is(candidate.textDocument)
- && Array.isArray(candidate.edits);
- }
- TextDocumentEdit.is = is;
- })(TextDocumentEdit || (TextDocumentEdit = {}));
- var CreateFile;
- (function (CreateFile) {
- function create(uri, options) {
- var result = {
- kind: 'create',
- uri: uri
- };
- if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
- result.options = options;
- }
- return result;
- }
- CreateFile.create = create;
- function is(value) {
- var candidate = value;
- return candidate && candidate.kind === 'create' && Is.string(candidate.uri) &&
- (candidate.options === void 0 ||
- ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
- }
- CreateFile.is = is;
- })(CreateFile || (CreateFile = {}));
- var RenameFile;
- (function (RenameFile) {
- function create(oldUri, newUri, options) {
- var result = {
- kind: 'rename',
- oldUri: oldUri,
- newUri: newUri
- };
- if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
- result.options = options;
- }
- return result;
- }
- RenameFile.create = create;
- function is(value) {
- var candidate = value;
- return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) &&
- (candidate.options === void 0 ||
- ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
- }
- RenameFile.is = is;
- })(RenameFile || (RenameFile = {}));
- var DeleteFile;
- (function (DeleteFile) {
- function create(uri, options) {
- var result = {
- kind: 'delete',
- uri: uri
- };
- if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
- result.options = options;
- }
- return result;
- }
- DeleteFile.create = create;
- function is(value) {
- var candidate = value;
- return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) &&
- (candidate.options === void 0 ||
- ((candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))));
- }
- DeleteFile.is = is;
- })(DeleteFile || (DeleteFile = {}));
- var WorkspaceEdit;
- (function (WorkspaceEdit) {
- function is(value) {
- var candidate = value;
- return candidate &&
- (candidate.changes !== void 0 || candidate.documentChanges !== void 0) &&
- (candidate.documentChanges === void 0 || candidate.documentChanges.every(function (change) {
- if (Is.string(change.kind)) {
- return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
- }
- else {
- return TextDocumentEdit.is(change);
- }
- }));
- }
- WorkspaceEdit.is = is;
- })(WorkspaceEdit || (WorkspaceEdit = {}));
- var TextEditChangeImpl = /** @class */ (function () {
- function TextEditChangeImpl(edits) {
- this.edits = edits;
- }
- TextEditChangeImpl.prototype.insert = function (position, newText) {
- this.edits.push(TextEdit.insert(position, newText));
- };
- TextEditChangeImpl.prototype.replace = function (range, newText) {
- this.edits.push(TextEdit.replace(range, newText));
- };
- TextEditChangeImpl.prototype.delete = function (range) {
- this.edits.push(TextEdit.del(range));
- };
- TextEditChangeImpl.prototype.add = function (edit) {
- this.edits.push(edit);
- };
- TextEditChangeImpl.prototype.all = function () {
- return this.edits;
- };
- TextEditChangeImpl.prototype.clear = function () {
- this.edits.splice(0, this.edits.length);
- };
- return TextEditChangeImpl;
- }());
- /**
- * A workspace change helps constructing changes to a workspace.
- */
- var WorkspaceChange = /** @class */ (function () {
- function WorkspaceChange(workspaceEdit) {
- var _this = this;
- this._textEditChanges = Object.create(null);
- if (workspaceEdit) {
- this._workspaceEdit = workspaceEdit;
- if (workspaceEdit.documentChanges) {
- workspaceEdit.documentChanges.forEach(function (change) {
- if (TextDocumentEdit.is(change)) {
- var textEditChange = new TextEditChangeImpl(change.edits);
- _this._textEditChanges[change.textDocument.uri] = textEditChange;
- }
- });
- }
- else if (workspaceEdit.changes) {
- Object.keys(workspaceEdit.changes).forEach(function (key) {
- var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
- _this._textEditChanges[key] = textEditChange;
- });
- }
- }
- }
- Object.defineProperty(WorkspaceChange.prototype, "edit", {
- /**
- * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal
- * use to be returned from a workspace edit operation like rename.
- */
- get: function () {
- return this._workspaceEdit;
- },
- enumerable: true,
- configurable: true
- });
- WorkspaceChange.prototype.getTextEditChange = function (key) {
- if (VersionedTextDocumentIdentifier.is(key)) {
- if (!this._workspaceEdit) {
- this._workspaceEdit = {
- documentChanges: []
- };
- }
- if (!this._workspaceEdit.documentChanges) {
- throw new Error('Workspace edit is not configured for document changes.');
- }
- var textDocument = key;
- var result = this._textEditChanges[textDocument.uri];
- if (!result) {
- var edits = [];
- var textDocumentEdit = {
- textDocument: textDocument,
- edits: edits
- };
- this._workspaceEdit.documentChanges.push(textDocumentEdit);
- result = new TextEditChangeImpl(edits);
- this._textEditChanges[textDocument.uri] = result;
- }
- return result;
- }
- else {
- if (!this._workspaceEdit) {
- this._workspaceEdit = {
- changes: Object.create(null)
- };
- }
- if (!this._workspaceEdit.changes) {
- throw new Error('Workspace edit is not configured for normal text edit changes.');
- }
- var result = this._textEditChanges[key];
- if (!result) {
- var edits = [];
- this._workspaceEdit.changes[key] = edits;
- result = new TextEditChangeImpl(edits);
- this._textEditChanges[key] = result;
- }
- return result;
- }
- };
- WorkspaceChange.prototype.createFile = function (uri, options) {
- this.checkDocumentChanges();
- this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));
- };
- WorkspaceChange.prototype.renameFile = function (oldUri, newUri, options) {
- this.checkDocumentChanges();
- this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));
- };
- WorkspaceChange.prototype.deleteFile = function (uri, options) {
- this.checkDocumentChanges();
- this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));
- };
- WorkspaceChange.prototype.checkDocumentChanges = function () {
- if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {
- throw new Error('Workspace edit is not configured for document changes.');
- }
- };
- return WorkspaceChange;
- }());
-
- /**
- * The TextDocumentIdentifier namespace provides helper functions to work with
- * [TextDocumentIdentifier](#TextDocumentIdentifier) literals.
- */
- var TextDocumentIdentifier;
- (function (TextDocumentIdentifier) {
- /**
- * Creates a new TextDocumentIdentifier literal.
- * @param uri The document's uri.
- */
- function create(uri) {
- return { uri: uri };
- }
- TextDocumentIdentifier.create = create;
- /**
- * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Is.string(candidate.uri);
- }
- TextDocumentIdentifier.is = is;
- })(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
- /**
- * The VersionedTextDocumentIdentifier namespace provides helper functions to work with
- * [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals.
- */
- var VersionedTextDocumentIdentifier;
- (function (VersionedTextDocumentIdentifier) {
- /**
- * Creates a new VersionedTextDocumentIdentifier literal.
- * @param uri The document's uri.
- * @param uri The document's text.
- */
- function create(uri, version) {
- return { uri: uri, version: version };
- }
- VersionedTextDocumentIdentifier.create = create;
- /**
- * Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.number(candidate.version));
- }
- VersionedTextDocumentIdentifier.is = is;
- })(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
- /**
- * The TextDocumentItem namespace provides helper functions to work with
- * [TextDocumentItem](#TextDocumentItem) literals.
- */
- var TextDocumentItem;
- (function (TextDocumentItem) {
- /**
- * Creates a new TextDocumentItem literal.
- * @param uri The document's uri.
- * @param languageId The document's language identifier.
- * @param version The document's version number.
- * @param text The document's text.
- */
- function create(uri, languageId, version, text) {
- return { uri: uri, languageId: languageId, version: version, text: text };
- }
- TextDocumentItem.create = create;
- /**
- * Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.number(candidate.version) && Is.string(candidate.text);
- }
- TextDocumentItem.is = is;
- })(TextDocumentItem || (TextDocumentItem = {}));
- /**
- * Describes the content type that a client supports in various
- * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
- *
- * Please note that `MarkupKinds` must not start with a `$`. This kinds
- * are reserved for internal usage.
- */
- var MarkupKind;
- (function (MarkupKind) {
- /**
- * Plain text is supported as a content format
- */
- MarkupKind.PlainText = 'plaintext';
- /**
- * Markdown is supported as a content format
- */
- MarkupKind.Markdown = 'markdown';
- })(MarkupKind || (MarkupKind = {}));
- (function (MarkupKind) {
- /**
- * Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type.
- */
- function is(value) {
- var candidate = value;
- return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;
- }
- MarkupKind.is = is;
- })(MarkupKind || (MarkupKind = {}));
- var MarkupContent;
- (function (MarkupContent) {
- /**
- * Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
- }
- MarkupContent.is = is;
- })(MarkupContent || (MarkupContent = {}));
- /**
- * The kind of a completion entry.
- */
- var CompletionItemKind;
- (function (CompletionItemKind) {
- CompletionItemKind.Text = 1;
- CompletionItemKind.Method = 2;
- CompletionItemKind.Function = 3;
- CompletionItemKind.Constructor = 4;
- CompletionItemKind.Field = 5;
- CompletionItemKind.Variable = 6;
- CompletionItemKind.Class = 7;
- CompletionItemKind.Interface = 8;
- CompletionItemKind.Module = 9;
- CompletionItemKind.Property = 10;
- CompletionItemKind.Unit = 11;
- CompletionItemKind.Value = 12;
- CompletionItemKind.Enum = 13;
- CompletionItemKind.Keyword = 14;
- CompletionItemKind.Snippet = 15;
- CompletionItemKind.Color = 16;
- CompletionItemKind.File = 17;
- CompletionItemKind.Reference = 18;
- CompletionItemKind.Folder = 19;
- CompletionItemKind.EnumMember = 20;
- CompletionItemKind.Constant = 21;
- CompletionItemKind.Struct = 22;
- CompletionItemKind.Event = 23;
- CompletionItemKind.Operator = 24;
- CompletionItemKind.TypeParameter = 25;
- })(CompletionItemKind || (CompletionItemKind = {}));
- /**
- * Defines whether the insert text in a completion item should be interpreted as
- * plain text or a snippet.
- */
- var InsertTextFormat;
- (function (InsertTextFormat) {
- /**
- * The primary text to be inserted is treated as a plain string.
- */
- InsertTextFormat.PlainText = 1;
- /**
- * The primary text to be inserted is treated as a snippet.
- *
- * A snippet can define tab stops and placeholders with `$1`, `$2`
- * and `${3:foo}`. `$0` defines the final tab stop, it defaults to
- * the end of the snippet. Placeholders with equal identifiers are linked,
- * that is typing in one will update others too.
- *
- * See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md
- */
- InsertTextFormat.Snippet = 2;
- })(InsertTextFormat || (InsertTextFormat = {}));
- /**
- * Completion item tags are extra annotations that tweak the rendering of a completion
- * item.
- *
- * @since 3.15.0
- */
- var CompletionItemTag;
- (function (CompletionItemTag) {
- /**
- * Render a completion as obsolete, usually using a strike-out.
- */
- CompletionItemTag.Deprecated = 1;
- })(CompletionItemTag || (CompletionItemTag = {}));
- /**
- * The CompletionItem namespace provides functions to deal with
- * completion items.
- */
- var CompletionItem;
- (function (CompletionItem) {
- /**
- * Create a completion item and seed it with a label.
- * @param label The completion item's label
- */
- function create(label) {
- return { label: label };
- }
- CompletionItem.create = create;
- })(CompletionItem || (CompletionItem = {}));
- /**
- * The CompletionList namespace provides functions to deal with
- * completion lists.
- */
- var CompletionList;
- (function (CompletionList) {
- /**
- * Creates a new completion list.
- *
- * @param items The completion items.
- * @param isIncomplete The list is not complete.
- */
- function create(items, isIncomplete) {
- return { items: items ? items : [], isIncomplete: !!isIncomplete };
- }
- CompletionList.create = create;
- })(CompletionList || (CompletionList = {}));
- var MarkedString;
- (function (MarkedString) {
- /**
- * Creates a marked string from plain text.
- *
- * @param plainText The plain text.
- */
- function fromPlainText(plainText) {
- return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
- }
- MarkedString.fromPlainText = fromPlainText;
- /**
- * Checks whether the given value conforms to the [MarkedString](#MarkedString) type.
- */
- function is(value) {
- var candidate = value;
- return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));
- }
- MarkedString.is = is;
- })(MarkedString || (MarkedString = {}));
- var Hover;
- (function (Hover) {
- /**
- * Checks whether the given value conforms to the [Hover](#Hover) interface.
- */
- function is(value) {
- var candidate = value;
- return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||
- MarkedString.is(candidate.contents) ||
- Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));
- }
- Hover.is = is;
- })(Hover || (Hover = {}));
- /**
- * The ParameterInformation namespace provides helper functions to work with
- * [ParameterInformation](#ParameterInformation) literals.
- */
- var ParameterInformation;
- (function (ParameterInformation) {
- /**
- * Creates a new parameter information literal.
- *
- * @param label A label string.
- * @param documentation A doc string.
- */
- function create(label, documentation) {
- return documentation ? { label: label, documentation: documentation } : { label: label };
- }
- ParameterInformation.create = create;
- })(ParameterInformation || (ParameterInformation = {}));
- /**
- * The SignatureInformation namespace provides helper functions to work with
- * [SignatureInformation](#SignatureInformation) literals.
- */
- var SignatureInformation;
- (function (SignatureInformation) {
- function create(label, documentation) {
- var parameters = [];
- for (var _i = 2; _i < arguments.length; _i++) {
- parameters[_i - 2] = arguments[_i];
- }
- var result = { label: label };
- if (Is.defined(documentation)) {
- result.documentation = documentation;
- }
- if (Is.defined(parameters)) {
- result.parameters = parameters;
- }
- else {
- result.parameters = [];
- }
- return result;
- }
- SignatureInformation.create = create;
- })(SignatureInformation || (SignatureInformation = {}));
- /**
- * A document highlight kind.
- */
- var DocumentHighlightKind;
- (function (DocumentHighlightKind) {
- /**
- * A textual occurrence.
- */
- DocumentHighlightKind.Text = 1;
- /**
- * Read-access of a symbol, like reading a variable.
- */
- DocumentHighlightKind.Read = 2;
- /**
- * Write-access of a symbol, like writing to a variable.
- */
- DocumentHighlightKind.Write = 3;
- })(DocumentHighlightKind || (DocumentHighlightKind = {}));
- /**
- * DocumentHighlight namespace to provide helper functions to work with
- * [DocumentHighlight](#DocumentHighlight) literals.
- */
- var DocumentHighlight;
- (function (DocumentHighlight) {
- /**
- * Create a DocumentHighlight object.
- * @param range The range the highlight applies to.
- */
- function create(range, kind) {
- var result = { range: range };
- if (Is.number(kind)) {
- result.kind = kind;
- }
- return result;
- }
- DocumentHighlight.create = create;
- })(DocumentHighlight || (DocumentHighlight = {}));
- /**
- * A symbol kind.
- */
- var SymbolKind;
- (function (SymbolKind) {
- SymbolKind.File = 1;
- SymbolKind.Module = 2;
- SymbolKind.Namespace = 3;
- SymbolKind.Package = 4;
- SymbolKind.Class = 5;
- SymbolKind.Method = 6;
- SymbolKind.Property = 7;
- SymbolKind.Field = 8;
- SymbolKind.Constructor = 9;
- SymbolKind.Enum = 10;
- SymbolKind.Interface = 11;
- SymbolKind.Function = 12;
- SymbolKind.Variable = 13;
- SymbolKind.Constant = 14;
- SymbolKind.String = 15;
- SymbolKind.Number = 16;
- SymbolKind.Boolean = 17;
- SymbolKind.Array = 18;
- SymbolKind.Object = 19;
- SymbolKind.Key = 20;
- SymbolKind.Null = 21;
- SymbolKind.EnumMember = 22;
- SymbolKind.Struct = 23;
- SymbolKind.Event = 24;
- SymbolKind.Operator = 25;
- SymbolKind.TypeParameter = 26;
- })(SymbolKind || (SymbolKind = {}));
- /**
- * Symbol tags are extra annotations that tweak the rendering of a symbol.
- * @since 3.15
- */
- var SymbolTag;
- (function (SymbolTag) {
- /**
- * Render a symbol as obsolete, usually using a strike-out.
- */
- SymbolTag.Deprecated = 1;
- })(SymbolTag || (SymbolTag = {}));
- var SymbolInformation;
- (function (SymbolInformation) {
- /**
- * Creates a new symbol information literal.
- *
- * @param name The name of the symbol.
- * @param kind The kind of the symbol.
- * @param range The range of the location of the symbol.
- * @param uri The resource of the location of symbol, defaults to the current document.
- * @param containerName The name of the symbol containing the symbol.
- */
- function create(name, kind, range, uri, containerName) {
- var result = {
- name: name,
- kind: kind,
- location: { uri: uri, range: range }
- };
- if (containerName) {
- result.containerName = containerName;
- }
- return result;
- }
- SymbolInformation.create = create;
- })(SymbolInformation || (SymbolInformation = {}));
- var DocumentSymbol;
- (function (DocumentSymbol) {
- /**
- * Creates a new symbol information literal.
- *
- * @param name The name of the symbol.
- * @param detail The detail of the symbol.
- * @param kind The kind of the symbol.
- * @param range The range of the symbol.
- * @param selectionRange The selectionRange of the symbol.
- * @param children Children of the symbol.
- */
- function create(name, detail, kind, range, selectionRange, children) {
- var result = {
- name: name,
- detail: detail,
- kind: kind,
- range: range,
- selectionRange: selectionRange
- };
- if (children !== void 0) {
- result.children = children;
- }
- return result;
- }
- DocumentSymbol.create = create;
- /**
- * Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface.
- */
- function is(value) {
- var candidate = value;
- return candidate &&
- Is.string(candidate.name) && Is.number(candidate.kind) &&
- Range.is(candidate.range) && Range.is(candidate.selectionRange) &&
- (candidate.detail === void 0 || Is.string(candidate.detail)) &&
- (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) &&
- (candidate.children === void 0 || Array.isArray(candidate.children));
- }
- DocumentSymbol.is = is;
- })(DocumentSymbol || (DocumentSymbol = {}));
- /**
- * A set of predefined code action kinds
- */
- var CodeActionKind;
- (function (CodeActionKind) {
- /**
- * Empty kind.
- */
- CodeActionKind.Empty = '';
- /**
- * Base kind for quickfix actions: 'quickfix'
- */
- CodeActionKind.QuickFix = 'quickfix';
- /**
- * Base kind for refactoring actions: 'refactor'
- */
- CodeActionKind.Refactor = 'refactor';
- /**
- * Base kind for refactoring extraction actions: 'refactor.extract'
- *
- * Example extract actions:
- *
- * - Extract method
- * - Extract function
- * - Extract variable
- * - Extract interface from class
- * - ...
- */
- CodeActionKind.RefactorExtract = 'refactor.extract';
- /**
- * Base kind for refactoring inline actions: 'refactor.inline'
- *
- * Example inline actions:
- *
- * - Inline function
- * - Inline variable
- * - Inline constant
- * - ...
- */
- CodeActionKind.RefactorInline = 'refactor.inline';
- /**
- * Base kind for refactoring rewrite actions: 'refactor.rewrite'
- *
- * Example rewrite actions:
- *
- * - Convert JavaScript function to class
- * - Add or remove parameter
- * - Encapsulate field
- * - Make method static
- * - Move method to base class
- * - ...
- */
- CodeActionKind.RefactorRewrite = 'refactor.rewrite';
- /**
- * Base kind for source actions: `source`
- *
- * Source code actions apply to the entire file.
- */
- CodeActionKind.Source = 'source';
- /**
- * Base kind for an organize imports source action: `source.organizeImports`
- */
- CodeActionKind.SourceOrganizeImports = 'source.organizeImports';
- /**
- * Base kind for auto-fix source actions: `source.fixAll`.
- *
- * Fix all actions automatically fix errors that have a clear fix that do not require user input.
- * They should not suppress errors or perform unsafe fixes such as generating new types or classes.
- *
- * @since 3.15.0
- */
- CodeActionKind.SourceFixAll = 'source.fixAll';
- })(CodeActionKind || (CodeActionKind = {}));
- /**
- * The CodeActionContext namespace provides helper functions to work with
- * [CodeActionContext](#CodeActionContext) literals.
- */
- var CodeActionContext;
- (function (CodeActionContext) {
- /**
- * Creates a new CodeActionContext literal.
- */
- function create(diagnostics, only) {
- var result = { diagnostics: diagnostics };
- if (only !== void 0 && only !== null) {
- result.only = only;
- }
- return result;
- }
- CodeActionContext.create = create;
- /**
- * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string));
- }
- CodeActionContext.is = is;
- })(CodeActionContext || (CodeActionContext = {}));
- var CodeAction;
- (function (CodeAction) {
- function create(title, commandOrEdit, kind) {
- var result = { title: title };
- if (Command.is(commandOrEdit)) {
- result.command = commandOrEdit;
- }
- else {
- result.edit = commandOrEdit;
- }
- if (kind !== void 0) {
- result.kind = kind;
- }
- return result;
- }
- CodeAction.create = create;
- function is(value) {
- var candidate = value;
- return candidate && Is.string(candidate.title) &&
- (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&
- (candidate.kind === void 0 || Is.string(candidate.kind)) &&
- (candidate.edit !== void 0 || candidate.command !== void 0) &&
- (candidate.command === void 0 || Command.is(candidate.command)) &&
- (candidate.isPreferred === void 0 || Is.boolean(candidate.isPreferred)) &&
- (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));
- }
- CodeAction.is = is;
- })(CodeAction || (CodeAction = {}));
- /**
- * The CodeLens namespace provides helper functions to work with
- * [CodeLens](#CodeLens) literals.
- */
- var CodeLens;
- (function (CodeLens) {
- /**
- * Creates a new CodeLens literal.
- */
- function create(range, data) {
- var result = { range: range };
- if (Is.defined(data)) {
- result.data = data;
- }
- return result;
- }
- CodeLens.create = create;
- /**
- * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
- }
- CodeLens.is = is;
- })(CodeLens || (CodeLens = {}));
- /**
- * The FormattingOptions namespace provides helper functions to work with
- * [FormattingOptions](#FormattingOptions) literals.
- */
- var FormattingOptions;
- (function (FormattingOptions) {
- /**
- * Creates a new FormattingOptions literal.
- */
- function create(tabSize, insertSpaces) {
- return { tabSize: tabSize, insertSpaces: insertSpaces };
- }
- FormattingOptions.create = create;
- /**
- * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Is.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
- }
- FormattingOptions.is = is;
- })(FormattingOptions || (FormattingOptions = {}));
- /**
- * The DocumentLink namespace provides helper functions to work with
- * [DocumentLink](#DocumentLink) literals.
- */
- var DocumentLink;
- (function (DocumentLink) {
- /**
- * Creates a new DocumentLink literal.
- */
- function create(range, target, data) {
- return { range: range, target: target, data: data };
- }
- DocumentLink.create = create;
- /**
- * Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
- }
- DocumentLink.is = is;
- })(DocumentLink || (DocumentLink = {}));
- /**
- * The SelectionRange namespace provides helper function to work with
- * SelectionRange literals.
- */
- var SelectionRange;
- (function (SelectionRange) {
- /**
- * Creates a new SelectionRange
- * @param range the range.
- * @param parent an optional parent.
- */
- function create(range, parent) {
- return { range: range, parent: parent };
- }
- SelectionRange.create = create;
- function is(value) {
- var candidate = value;
- return candidate !== undefined && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));
- }
- SelectionRange.is = is;
- })(SelectionRange || (SelectionRange = {}));
- var EOL = ['\n', '\r\n', '\r'];
- /**
- * @deprecated Use the text document from the new vscode-languageserver-textdocument package.
- */
- var TextDocument;
- (function (TextDocument) {
- /**
- * Creates a new ITextDocument literal from the given uri and content.
- * @param uri The document's uri.
- * @param languageId The document's language Id.
- * @param content The document's content.
- */
- function create(uri, languageId, version, content) {
- return new FullTextDocument(uri, languageId, version, content);
- }
- TextDocument.create = create;
- /**
- * Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface.
- */
- function is(value) {
- var candidate = value;
- return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.number(candidate.lineCount)
- && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
- }
- TextDocument.is = is;
- function applyEdits(document, edits) {
- var text = document.getText();
- var sortedEdits = mergeSort(edits, function (a, b) {
- var diff = a.range.start.line - b.range.start.line;
- if (diff === 0) {
- return a.range.start.character - b.range.start.character;
- }
- return diff;
- });
- var lastModifiedOffset = text.length;
- for (var i = sortedEdits.length - 1; i >= 0; i--) {
- var e = sortedEdits[i];
- var startOffset = document.offsetAt(e.range.start);
- var endOffset = document.offsetAt(e.range.end);
- if (endOffset <= lastModifiedOffset) {
- text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
- }
- else {
- throw new Error('Overlapping edit');
- }
- lastModifiedOffset = startOffset;
- }
- return text;
- }
- TextDocument.applyEdits = applyEdits;
- function mergeSort(data, compare) {
- if (data.length <= 1) {
- // sorted
- return data;
- }
- var p = (data.length / 2) | 0;
- var left = data.slice(0, p);
- var right = data.slice(p);
- mergeSort(left, compare);
- mergeSort(right, compare);
- var leftIdx = 0;
- var rightIdx = 0;
- var i = 0;
- while (leftIdx < left.length && rightIdx < right.length) {
- var ret = compare(left[leftIdx], right[rightIdx]);
- if (ret <= 0) {
- // smaller_equal -> take left to preserve order
- data[i++] = left[leftIdx++];
- }
- else {
- // greater -> take right
- data[i++] = right[rightIdx++];
- }
- }
- while (leftIdx < left.length) {
- data[i++] = left[leftIdx++];
- }
- while (rightIdx < right.length) {
- data[i++] = right[rightIdx++];
- }
- return data;
- }
- })(TextDocument || (TextDocument = {}));
- var FullTextDocument = /** @class */ (function () {
- function FullTextDocument(uri, languageId, version, content) {
- this._uri = uri;
- this._languageId = languageId;
- this._version = version;
- this._content = content;
- this._lineOffsets = undefined;
- }
- Object.defineProperty(FullTextDocument.prototype, "uri", {
- get: function () {
- return this._uri;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(FullTextDocument.prototype, "languageId", {
- get: function () {
- return this._languageId;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(FullTextDocument.prototype, "version", {
- get: function () {
- return this._version;
- },
- enumerable: true,
- configurable: true
- });
- FullTextDocument.prototype.getText = function (range) {
- if (range) {
- var start = this.offsetAt(range.start);
- var end = this.offsetAt(range.end);
- return this._content.substring(start, end);
- }
- return this._content;
- };
- FullTextDocument.prototype.update = function (event, version) {
- this._content = event.text;
- this._version = version;
- this._lineOffsets = undefined;
- };
- FullTextDocument.prototype.getLineOffsets = function () {
- if (this._lineOffsets === undefined) {
- var lineOffsets = [];
- var text = this._content;
- var isLineStart = true;
- for (var i = 0; i < text.length; i++) {
- if (isLineStart) {
- lineOffsets.push(i);
- isLineStart = false;
- }
- var ch = text.charAt(i);
- isLineStart = (ch === '\r' || ch === '\n');
- if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {
- i++;
- }
- }
- if (isLineStart && text.length > 0) {
- lineOffsets.push(text.length);
- }
- this._lineOffsets = lineOffsets;
- }
- return this._lineOffsets;
- };
- FullTextDocument.prototype.positionAt = function (offset) {
- offset = Math.max(Math.min(offset, this._content.length), 0);
- var lineOffsets = this.getLineOffsets();
- var low = 0, high = lineOffsets.length;
- if (high === 0) {
- return Position.create(0, offset);
- }
- while (low < high) {
- var mid = Math.floor((low + high) / 2);
- if (lineOffsets[mid] > offset) {
- high = mid;
- }
- else {
- low = mid + 1;
- }
- }
- // low is the least x for which the line offset is larger than the current offset
- // or array.length if no line offset is larger than the current offset
- var line = low - 1;
- return Position.create(line, offset - lineOffsets[line]);
- };
- FullTextDocument.prototype.offsetAt = function (position) {
- var lineOffsets = this.getLineOffsets();
- if (position.line >= lineOffsets.length) {
- return this._content.length;
- }
- else if (position.line < 0) {
- return 0;
- }
- var lineOffset = lineOffsets[position.line];
- var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
- return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
- };
- Object.defineProperty(FullTextDocument.prototype, "lineCount", {
- get: function () {
- return this.getLineOffsets().length;
- },
- enumerable: true,
- configurable: true
- });
- return FullTextDocument;
- }());
- var Is;
- (function (Is) {
- var toString = Object.prototype.toString;
- function defined(value) {
- return typeof value !== 'undefined';
- }
- Is.defined = defined;
- function undefined(value) {
- return typeof value === 'undefined';
- }
- Is.undefined = undefined;
- function boolean(value) {
- return value === true || value === false;
- }
- Is.boolean = boolean;
- function string(value) {
- return toString.call(value) === '[object String]';
- }
- Is.string = string;
- function number(value) {
- return toString.call(value) === '[object Number]';
- }
- Is.number = number;
- function func(value) {
- return toString.call(value) === '[object Function]';
- }
- Is.func = func;
- function objectLiteral(value) {
- // Strictly speaking class instances pass this check as well. Since the LSP
- // doesn't use classes we ignore this for now. If we do we need to add something
- // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
- return value !== null && typeof value === 'object';
- }
- Is.objectLiteral = objectLiteral;
- function typedArray(value, check) {
- return Array.isArray(value) && value.every(check);
- }
- Is.typedArray = typedArray;
- })(Is || (Is = {}));
-
-
- /***/ }),
- /* 19 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const Is = __webpack_require__(20);
- const vscode_jsonrpc_1 = __webpack_require__(4);
- const messages_1 = __webpack_require__(21);
- const protocol_implementation_1 = __webpack_require__(22);
- exports.ImplementationRequest = protocol_implementation_1.ImplementationRequest;
- const protocol_typeDefinition_1 = __webpack_require__(23);
- exports.TypeDefinitionRequest = protocol_typeDefinition_1.TypeDefinitionRequest;
- const protocol_workspaceFolders_1 = __webpack_require__(24);
- exports.WorkspaceFoldersRequest = protocol_workspaceFolders_1.WorkspaceFoldersRequest;
- exports.DidChangeWorkspaceFoldersNotification = protocol_workspaceFolders_1.DidChangeWorkspaceFoldersNotification;
- const protocol_configuration_1 = __webpack_require__(25);
- exports.ConfigurationRequest = protocol_configuration_1.ConfigurationRequest;
- const protocol_colorProvider_1 = __webpack_require__(26);
- exports.DocumentColorRequest = protocol_colorProvider_1.DocumentColorRequest;
- exports.ColorPresentationRequest = protocol_colorProvider_1.ColorPresentationRequest;
- const protocol_foldingRange_1 = __webpack_require__(27);
- exports.FoldingRangeRequest = protocol_foldingRange_1.FoldingRangeRequest;
- const protocol_declaration_1 = __webpack_require__(28);
- exports.DeclarationRequest = protocol_declaration_1.DeclarationRequest;
- const protocol_selectionRange_1 = __webpack_require__(29);
- exports.SelectionRangeRequest = protocol_selectionRange_1.SelectionRangeRequest;
- const protocol_progress_1 = __webpack_require__(30);
- exports.WorkDoneProgress = protocol_progress_1.WorkDoneProgress;
- exports.WorkDoneProgressCreateRequest = protocol_progress_1.WorkDoneProgressCreateRequest;
- exports.WorkDoneProgressCancelNotification = protocol_progress_1.WorkDoneProgressCancelNotification;
- // @ts-ignore: to avoid inlining LocatioLink as dynamic import
- let __noDynamicImport;
- /**
- * The DocumentFilter namespace provides helper functions to work with
- * [DocumentFilter](#DocumentFilter) literals.
- */
- var DocumentFilter;
- (function (DocumentFilter) {
- function is(value) {
- const candidate = value;
- return Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern);
- }
- DocumentFilter.is = is;
- })(DocumentFilter = exports.DocumentFilter || (exports.DocumentFilter = {}));
- /**
- * The DocumentSelector namespace provides helper functions to work with
- * [DocumentSelector](#DocumentSelector)s.
- */
- var DocumentSelector;
- (function (DocumentSelector) {
- function is(value) {
- if (!Array.isArray(value)) {
- return false;
- }
- for (let elem of value) {
- if (!Is.string(elem) && !DocumentFilter.is(elem)) {
- return false;
- }
- }
- return true;
- }
- DocumentSelector.is = is;
- })(DocumentSelector = exports.DocumentSelector || (exports.DocumentSelector = {}));
- /**
- * The `client/registerCapability` request is sent from the server to the client to register a new capability
- * handler on the client side.
- */
- var RegistrationRequest;
- (function (RegistrationRequest) {
- RegistrationRequest.type = new messages_1.ProtocolRequestType('client/registerCapability');
- })(RegistrationRequest = exports.RegistrationRequest || (exports.RegistrationRequest = {}));
- /**
- * The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability
- * handler on the client side.
- */
- var UnregistrationRequest;
- (function (UnregistrationRequest) {
- UnregistrationRequest.type = new messages_1.ProtocolRequestType('client/unregisterCapability');
- })(UnregistrationRequest = exports.UnregistrationRequest || (exports.UnregistrationRequest = {}));
- var ResourceOperationKind;
- (function (ResourceOperationKind) {
- /**
- * Supports creating new files and folders.
- */
- ResourceOperationKind.Create = 'create';
- /**
- * Supports renaming existing files and folders.
- */
- ResourceOperationKind.Rename = 'rename';
- /**
- * Supports deleting existing files and folders.
- */
- ResourceOperationKind.Delete = 'delete';
- })(ResourceOperationKind = exports.ResourceOperationKind || (exports.ResourceOperationKind = {}));
- var FailureHandlingKind;
- (function (FailureHandlingKind) {
- /**
- * Applying the workspace change is simply aborted if one of the changes provided
- * fails. All operations executed before the failing operation stay executed.
- */
- FailureHandlingKind.Abort = 'abort';
- /**
- * All operations are executed transactional. That means they either all
- * succeed or no changes at all are applied to the workspace.
- */
- FailureHandlingKind.Transactional = 'transactional';
- /**
- * If the workspace edit contains only textual file changes they are executed transactional.
- * If resource changes (create, rename or delete file) are part of the change the failure
- * handling startegy is abort.
- */
- FailureHandlingKind.TextOnlyTransactional = 'textOnlyTransactional';
- /**
- * The client tries to undo the operations already executed. But there is no
- * guarantee that this is succeeding.
- */
- FailureHandlingKind.Undo = 'undo';
- })(FailureHandlingKind = exports.FailureHandlingKind || (exports.FailureHandlingKind = {}));
- /**
- * The StaticRegistrationOptions namespace provides helper functions to work with
- * [StaticRegistrationOptions](#StaticRegistrationOptions) literals.
- */
- var StaticRegistrationOptions;
- (function (StaticRegistrationOptions) {
- function hasId(value) {
- const candidate = value;
- return candidate && Is.string(candidate.id) && candidate.id.length > 0;
- }
- StaticRegistrationOptions.hasId = hasId;
- })(StaticRegistrationOptions = exports.StaticRegistrationOptions || (exports.StaticRegistrationOptions = {}));
- /**
- * The TextDocumentRegistrationOptions namespace provides helper functions to work with
- * [TextDocumentRegistrationOptions](#TextDocumentRegistrationOptions) literals.
- */
- var TextDocumentRegistrationOptions;
- (function (TextDocumentRegistrationOptions) {
- function is(value) {
- const candidate = value;
- return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector));
- }
- TextDocumentRegistrationOptions.is = is;
- })(TextDocumentRegistrationOptions = exports.TextDocumentRegistrationOptions || (exports.TextDocumentRegistrationOptions = {}));
- /**
- * The WorkDoneProgressOptions namespace provides helper functions to work with
- * [WorkDoneProgressOptions](#WorkDoneProgressOptions) literals.
- */
- var WorkDoneProgressOptions;
- (function (WorkDoneProgressOptions) {
- function is(value) {
- const candidate = value;
- return Is.objectLiteral(candidate) && (candidate.workDoneProgress === undefined || Is.boolean(candidate.workDoneProgress));
- }
- WorkDoneProgressOptions.is = is;
- function hasWorkDoneProgress(value) {
- const candidate = value;
- return candidate && Is.boolean(candidate.workDoneProgress);
- }
- WorkDoneProgressOptions.hasWorkDoneProgress = hasWorkDoneProgress;
- })(WorkDoneProgressOptions = exports.WorkDoneProgressOptions || (exports.WorkDoneProgressOptions = {}));
- /**
- * The initialize request is sent from the client to the server.
- * It is sent once as the request after starting up the server.
- * The requests parameter is of type [InitializeParams](#InitializeParams)
- * the response if of type [InitializeResult](#InitializeResult) of a Thenable that
- * resolves to such.
- */
- var InitializeRequest;
- (function (InitializeRequest) {
- InitializeRequest.type = new messages_1.ProtocolRequestType('initialize');
- })(InitializeRequest = exports.InitializeRequest || (exports.InitializeRequest = {}));
- /**
- * Known error codes for an `InitializeError`;
- */
- var InitializeError;
- (function (InitializeError) {
- /**
- * If the protocol version provided by the client can't be handled by the server.
- * @deprecated This initialize error got replaced by client capabilities. There is
- * no version handshake in version 3.0x
- */
- InitializeError.unknownProtocolVersion = 1;
- })(InitializeError = exports.InitializeError || (exports.InitializeError = {}));
- /**
- * The intialized notification is sent from the client to the
- * server after the client is fully initialized and the server
- * is allowed to send requests from the server to the client.
- */
- var InitializedNotification;
- (function (InitializedNotification) {
- InitializedNotification.type = new messages_1.ProtocolNotificationType('initialized');
- })(InitializedNotification = exports.InitializedNotification || (exports.InitializedNotification = {}));
- //---- Shutdown Method ----
- /**
- * A shutdown request is sent from the client to the server.
- * It is sent once when the client decides to shutdown the
- * server. The only notification that is sent after a shutdown request
- * is the exit event.
- */
- var ShutdownRequest;
- (function (ShutdownRequest) {
- ShutdownRequest.type = new messages_1.ProtocolRequestType0('shutdown');
- })(ShutdownRequest = exports.ShutdownRequest || (exports.ShutdownRequest = {}));
- //---- Exit Notification ----
- /**
- * The exit event is sent from the client to the server to
- * ask the server to exit its process.
- */
- var ExitNotification;
- (function (ExitNotification) {
- ExitNotification.type = new messages_1.ProtocolNotificationType0('exit');
- })(ExitNotification = exports.ExitNotification || (exports.ExitNotification = {}));
- /**
- * The configuration change notification is sent from the client to the server
- * when the client's configuration has changed. The notification contains
- * the changed configuration as defined by the language client.
- */
- var DidChangeConfigurationNotification;
- (function (DidChangeConfigurationNotification) {
- DidChangeConfigurationNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeConfiguration');
- })(DidChangeConfigurationNotification = exports.DidChangeConfigurationNotification || (exports.DidChangeConfigurationNotification = {}));
- //---- Message show and log notifications ----
- /**
- * The message type
- */
- var MessageType;
- (function (MessageType) {
- /**
- * An error message.
- */
- MessageType.Error = 1;
- /**
- * A warning message.
- */
- MessageType.Warning = 2;
- /**
- * An information message.
- */
- MessageType.Info = 3;
- /**
- * A log message.
- */
- MessageType.Log = 4;
- })(MessageType = exports.MessageType || (exports.MessageType = {}));
- /**
- * The show message notification is sent from a server to a client to ask
- * the client to display a particular message in the user interface.
- */
- var ShowMessageNotification;
- (function (ShowMessageNotification) {
- ShowMessageNotification.type = new messages_1.ProtocolNotificationType('window/showMessage');
- })(ShowMessageNotification = exports.ShowMessageNotification || (exports.ShowMessageNotification = {}));
- /**
- * The show message request is sent from the server to the client to show a message
- * and a set of options actions to the user.
- */
- var ShowMessageRequest;
- (function (ShowMessageRequest) {
- ShowMessageRequest.type = new messages_1.ProtocolRequestType('window/showMessageRequest');
- })(ShowMessageRequest = exports.ShowMessageRequest || (exports.ShowMessageRequest = {}));
- /**
- * The log message notification is sent from the server to the client to ask
- * the client to log a particular message.
- */
- var LogMessageNotification;
- (function (LogMessageNotification) {
- LogMessageNotification.type = new messages_1.ProtocolNotificationType('window/logMessage');
- })(LogMessageNotification = exports.LogMessageNotification || (exports.LogMessageNotification = {}));
- //---- Telemetry notification
- /**
- * The telemetry event notification is sent from the server to the client to ask
- * the client to log telemetry data.
- */
- var TelemetryEventNotification;
- (function (TelemetryEventNotification) {
- TelemetryEventNotification.type = new messages_1.ProtocolNotificationType('telemetry/event');
- })(TelemetryEventNotification = exports.TelemetryEventNotification || (exports.TelemetryEventNotification = {}));
- /**
- * Defines how the host (editor) should sync
- * document changes to the language server.
- */
- var TextDocumentSyncKind;
- (function (TextDocumentSyncKind) {
- /**
- * Documents should not be synced at all.
- */
- TextDocumentSyncKind.None = 0;
- /**
- * Documents are synced by always sending the full content
- * of the document.
- */
- TextDocumentSyncKind.Full = 1;
- /**
- * Documents are synced by sending the full content on open.
- * After that only incremental updates to the document are
- * send.
- */
- TextDocumentSyncKind.Incremental = 2;
- })(TextDocumentSyncKind = exports.TextDocumentSyncKind || (exports.TextDocumentSyncKind = {}));
- /**
- * The document open notification is sent from the client to the server to signal
- * newly opened text documents. The document's truth is now managed by the client
- * and the server must not try to read the document's truth using the document's
- * uri. Open in this sense means it is managed by the client. It doesn't necessarily
- * mean that its content is presented in an editor. An open notification must not
- * be sent more than once without a corresponding close notification send before.
- * This means open and close notification must be balanced and the max open count
- * is one.
- */
- var DidOpenTextDocumentNotification;
- (function (DidOpenTextDocumentNotification) {
- DidOpenTextDocumentNotification.method = 'textDocument/didOpen';
- DidOpenTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification.method);
- })(DidOpenTextDocumentNotification = exports.DidOpenTextDocumentNotification || (exports.DidOpenTextDocumentNotification = {}));
- /**
- * The document change notification is sent from the client to the server to signal
- * changes to a text document.
- */
- var DidChangeTextDocumentNotification;
- (function (DidChangeTextDocumentNotification) {
- DidChangeTextDocumentNotification.method = 'textDocument/didChange';
- DidChangeTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification.method);
- })(DidChangeTextDocumentNotification = exports.DidChangeTextDocumentNotification || (exports.DidChangeTextDocumentNotification = {}));
- /**
- * The document close notification is sent from the client to the server when
- * the document got closed in the client. The document's truth now exists where
- * the document's uri points to (e.g. if the document's uri is a file uri the
- * truth now exists on disk). As with the open notification the close notification
- * is about managing the document's content. Receiving a close notification
- * doesn't mean that the document was open in an editor before. A close
- * notification requires a previous open notification to be sent.
- */
- var DidCloseTextDocumentNotification;
- (function (DidCloseTextDocumentNotification) {
- DidCloseTextDocumentNotification.method = 'textDocument/didClose';
- DidCloseTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification.method);
- })(DidCloseTextDocumentNotification = exports.DidCloseTextDocumentNotification || (exports.DidCloseTextDocumentNotification = {}));
- /**
- * The document save notification is sent from the client to the server when
- * the document got saved in the client.
- */
- var DidSaveTextDocumentNotification;
- (function (DidSaveTextDocumentNotification) {
- DidSaveTextDocumentNotification.method = 'textDocument/didSave';
- DidSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification.method);
- })(DidSaveTextDocumentNotification = exports.DidSaveTextDocumentNotification || (exports.DidSaveTextDocumentNotification = {}));
- /**
- * Represents reasons why a text document is saved.
- */
- var TextDocumentSaveReason;
- (function (TextDocumentSaveReason) {
- /**
- * Manually triggered, e.g. by the user pressing save, by starting debugging,
- * or by an API call.
- */
- TextDocumentSaveReason.Manual = 1;
- /**
- * Automatic after a delay.
- */
- TextDocumentSaveReason.AfterDelay = 2;
- /**
- * When the editor lost focus.
- */
- TextDocumentSaveReason.FocusOut = 3;
- })(TextDocumentSaveReason = exports.TextDocumentSaveReason || (exports.TextDocumentSaveReason = {}));
- /**
- * A document will save notification is sent from the client to the server before
- * the document is actually saved.
- */
- var WillSaveTextDocumentNotification;
- (function (WillSaveTextDocumentNotification) {
- WillSaveTextDocumentNotification.method = 'textDocument/willSave';
- WillSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification.method);
- })(WillSaveTextDocumentNotification = exports.WillSaveTextDocumentNotification || (exports.WillSaveTextDocumentNotification = {}));
- /**
- * A document will save request is sent from the client to the server before
- * the document is actually saved. The request can return an array of TextEdits
- * which will be applied to the text document before it is saved. Please note that
- * clients might drop results if computing the text edits took too long or if a
- * server constantly fails on this request. This is done to keep the save fast and
- * reliable.
- */
- var WillSaveTextDocumentWaitUntilRequest;
- (function (WillSaveTextDocumentWaitUntilRequest) {
- WillSaveTextDocumentWaitUntilRequest.method = 'textDocument/willSaveWaitUntil';
- WillSaveTextDocumentWaitUntilRequest.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest.method);
- })(WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentWaitUntilRequest || (exports.WillSaveTextDocumentWaitUntilRequest = {}));
- /**
- * The watched files notification is sent from the client to the server when
- * the client detects changes to file watched by the language client.
- */
- var DidChangeWatchedFilesNotification;
- (function (DidChangeWatchedFilesNotification) {
- DidChangeWatchedFilesNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWatchedFiles');
- })(DidChangeWatchedFilesNotification = exports.DidChangeWatchedFilesNotification || (exports.DidChangeWatchedFilesNotification = {}));
- /**
- * The file event type
- */
- var FileChangeType;
- (function (FileChangeType) {
- /**
- * The file got created.
- */
- FileChangeType.Created = 1;
- /**
- * The file got changed.
- */
- FileChangeType.Changed = 2;
- /**
- * The file got deleted.
- */
- FileChangeType.Deleted = 3;
- })(FileChangeType = exports.FileChangeType || (exports.FileChangeType = {}));
- var WatchKind;
- (function (WatchKind) {
- /**
- * Interested in create events.
- */
- WatchKind.Create = 1;
- /**
- * Interested in change events
- */
- WatchKind.Change = 2;
- /**
- * Interested in delete events
- */
- WatchKind.Delete = 4;
- })(WatchKind = exports.WatchKind || (exports.WatchKind = {}));
- /**
- * Diagnostics notification are sent from the server to the client to signal
- * results of validation runs.
- */
- var PublishDiagnosticsNotification;
- (function (PublishDiagnosticsNotification) {
- PublishDiagnosticsNotification.type = new messages_1.ProtocolNotificationType('textDocument/publishDiagnostics');
- })(PublishDiagnosticsNotification = exports.PublishDiagnosticsNotification || (exports.PublishDiagnosticsNotification = {}));
- /**
- * How a completion was triggered
- */
- var CompletionTriggerKind;
- (function (CompletionTriggerKind) {
- /**
- * Completion was triggered by typing an identifier (24x7 code
- * complete), manual invocation (e.g Ctrl+Space) or via API.
- */
- CompletionTriggerKind.Invoked = 1;
- /**
- * Completion was triggered by a trigger character specified by
- * the `triggerCharacters` properties of the `CompletionRegistrationOptions`.
- */
- CompletionTriggerKind.TriggerCharacter = 2;
- /**
- * Completion was re-triggered as current completion list is incomplete
- */
- CompletionTriggerKind.TriggerForIncompleteCompletions = 3;
- })(CompletionTriggerKind = exports.CompletionTriggerKind || (exports.CompletionTriggerKind = {}));
- /**
- * Request to request completion at a given text document position. The request's
- * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response
- * is of type [CompletionItem[]](#CompletionItem) or [CompletionList](#CompletionList)
- * or a Thenable that resolves to such.
- *
- * The request can delay the computation of the [`detail`](#CompletionItem.detail)
- * and [`documentation`](#CompletionItem.documentation) properties to the `completionItem/resolve`
- * request. However, properties that are needed for the initial sorting and filtering, like `sortText`,
- * `filterText`, `insertText`, and `textEdit`, must not be changed during resolve.
- */
- var CompletionRequest;
- (function (CompletionRequest) {
- CompletionRequest.method = 'textDocument/completion';
- CompletionRequest.type = new messages_1.ProtocolRequestType(CompletionRequest.method);
- /** @deprecated Use CompletionRequest.type */
- CompletionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(CompletionRequest = exports.CompletionRequest || (exports.CompletionRequest = {}));
- /**
- * Request to resolve additional information for a given completion item.The request's
- * parameter is of type [CompletionItem](#CompletionItem) the response
- * is of type [CompletionItem](#CompletionItem) or a Thenable that resolves to such.
- */
- var CompletionResolveRequest;
- (function (CompletionResolveRequest) {
- CompletionResolveRequest.method = 'completionItem/resolve';
- CompletionResolveRequest.type = new messages_1.ProtocolRequestType(CompletionResolveRequest.method);
- })(CompletionResolveRequest = exports.CompletionResolveRequest || (exports.CompletionResolveRequest = {}));
- /**
- * Request to request hover information at a given text document position. The request's
- * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response is of
- * type [Hover](#Hover) or a Thenable that resolves to such.
- */
- var HoverRequest;
- (function (HoverRequest) {
- HoverRequest.method = 'textDocument/hover';
- HoverRequest.type = new messages_1.ProtocolRequestType(HoverRequest.method);
- })(HoverRequest = exports.HoverRequest || (exports.HoverRequest = {}));
- /**
- * How a signature help was triggered.
- *
- * @since 3.15.0
- */
- var SignatureHelpTriggerKind;
- (function (SignatureHelpTriggerKind) {
- /**
- * Signature help was invoked manually by the user or by a command.
- */
- SignatureHelpTriggerKind.Invoked = 1;
- /**
- * Signature help was triggered by a trigger character.
- */
- SignatureHelpTriggerKind.TriggerCharacter = 2;
- /**
- * Signature help was triggered by the cursor moving or by the document content changing.
- */
- SignatureHelpTriggerKind.ContentChange = 3;
- })(SignatureHelpTriggerKind = exports.SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = {}));
- var SignatureHelpRequest;
- (function (SignatureHelpRequest) {
- SignatureHelpRequest.method = 'textDocument/signatureHelp';
- SignatureHelpRequest.type = new messages_1.ProtocolRequestType(SignatureHelpRequest.method);
- })(SignatureHelpRequest = exports.SignatureHelpRequest || (exports.SignatureHelpRequest = {}));
- /**
- * A request to resolve the definition location of a symbol at a given text
- * document position. The request's parameter is of type [TextDocumentPosition]
- * (#TextDocumentPosition) the response is of either type [Definition](#Definition)
- * or a typed array of [DefinitionLink](#DefinitionLink) or a Thenable that resolves
- * to such.
- */
- var DefinitionRequest;
- (function (DefinitionRequest) {
- DefinitionRequest.method = 'textDocument/definition';
- DefinitionRequest.type = new messages_1.ProtocolRequestType(DefinitionRequest.method);
- /** @deprecated Use DefinitionRequest.type */
- DefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(DefinitionRequest = exports.DefinitionRequest || (exports.DefinitionRequest = {}));
- /**
- * A request to resolve project-wide references for the symbol denoted
- * by the given text document position. The request's parameter is of
- * type [ReferenceParams](#ReferenceParams) the response is of type
- * [Location[]](#Location) or a Thenable that resolves to such.
- */
- var ReferencesRequest;
- (function (ReferencesRequest) {
- ReferencesRequest.method = 'textDocument/references';
- ReferencesRequest.type = new messages_1.ProtocolRequestType(ReferencesRequest.method);
- /** @deprecated Use ReferencesRequest.type */
- ReferencesRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(ReferencesRequest = exports.ReferencesRequest || (exports.ReferencesRequest = {}));
- /**
- * Request to resolve a [DocumentHighlight](#DocumentHighlight) for a given
- * text document position. The request's parameter is of type [TextDocumentPosition]
- * (#TextDocumentPosition) the request response is of type [DocumentHighlight[]]
- * (#DocumentHighlight) or a Thenable that resolves to such.
- */
- var DocumentHighlightRequest;
- (function (DocumentHighlightRequest) {
- DocumentHighlightRequest.method = 'textDocument/documentHighlight';
- DocumentHighlightRequest.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest.method);
- /** @deprecated Use DocumentHighlightRequest.type */
- DocumentHighlightRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(DocumentHighlightRequest = exports.DocumentHighlightRequest || (exports.DocumentHighlightRequest = {}));
- /**
- * A request to list all symbols found in a given text document. The request's
- * parameter is of type [TextDocumentIdentifier](#TextDocumentIdentifier) the
- * response is of type [SymbolInformation[]](#SymbolInformation) or a Thenable
- * that resolves to such.
- */
- var DocumentSymbolRequest;
- (function (DocumentSymbolRequest) {
- DocumentSymbolRequest.method = 'textDocument/documentSymbol';
- DocumentSymbolRequest.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest.method);
- /** @deprecated Use DocumentSymbolRequest.type */
- DocumentSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(DocumentSymbolRequest = exports.DocumentSymbolRequest || (exports.DocumentSymbolRequest = {}));
- /**
- * A request to provide commands for the given text document and range.
- */
- var CodeActionRequest;
- (function (CodeActionRequest) {
- CodeActionRequest.method = 'textDocument/codeAction';
- CodeActionRequest.type = new messages_1.ProtocolRequestType(CodeActionRequest.method);
- /** @deprecated Use CodeActionRequest.type */
- CodeActionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(CodeActionRequest = exports.CodeActionRequest || (exports.CodeActionRequest = {}));
- /**
- * A request to list project-wide symbols matching the query string given
- * by the [WorkspaceSymbolParams](#WorkspaceSymbolParams). The response is
- * of type [SymbolInformation[]](#SymbolInformation) or a Thenable that
- * resolves to such.
- */
- var WorkspaceSymbolRequest;
- (function (WorkspaceSymbolRequest) {
- WorkspaceSymbolRequest.method = 'workspace/symbol';
- WorkspaceSymbolRequest.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest.method);
- /** @deprecated Use WorkspaceSymbolRequest.type */
- WorkspaceSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(WorkspaceSymbolRequest = exports.WorkspaceSymbolRequest || (exports.WorkspaceSymbolRequest = {}));
- /**
- * A request to provide code lens for the given text document.
- */
- var CodeLensRequest;
- (function (CodeLensRequest) {
- CodeLensRequest.type = new messages_1.ProtocolRequestType('textDocument/codeLens');
- /** @deprecated Use CodeLensRequest.type */
- CodeLensRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(CodeLensRequest = exports.CodeLensRequest || (exports.CodeLensRequest = {}));
- /**
- * A request to resolve a command for a given code lens.
- */
- var CodeLensResolveRequest;
- (function (CodeLensResolveRequest) {
- CodeLensResolveRequest.type = new messages_1.ProtocolRequestType('codeLens/resolve');
- })(CodeLensResolveRequest = exports.CodeLensResolveRequest || (exports.CodeLensResolveRequest = {}));
- /**
- * A request to provide document links
- */
- var DocumentLinkRequest;
- (function (DocumentLinkRequest) {
- DocumentLinkRequest.method = 'textDocument/documentLink';
- DocumentLinkRequest.type = new messages_1.ProtocolRequestType(DocumentLinkRequest.method);
- /** @deprecated Use DocumentLinkRequest.type */
- DocumentLinkRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(DocumentLinkRequest = exports.DocumentLinkRequest || (exports.DocumentLinkRequest = {}));
- /**
- * Request to resolve additional information for a given document link. The request's
- * parameter is of type [DocumentLink](#DocumentLink) the response
- * is of type [DocumentLink](#DocumentLink) or a Thenable that resolves to such.
- */
- var DocumentLinkResolveRequest;
- (function (DocumentLinkResolveRequest) {
- DocumentLinkResolveRequest.type = new messages_1.ProtocolRequestType('documentLink/resolve');
- })(DocumentLinkResolveRequest = exports.DocumentLinkResolveRequest || (exports.DocumentLinkResolveRequest = {}));
- /**
- * A request to to format a whole document.
- */
- var DocumentFormattingRequest;
- (function (DocumentFormattingRequest) {
- DocumentFormattingRequest.method = 'textDocument/formatting';
- DocumentFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest.method);
- })(DocumentFormattingRequest = exports.DocumentFormattingRequest || (exports.DocumentFormattingRequest = {}));
- /**
- * A request to to format a range in a document.
- */
- var DocumentRangeFormattingRequest;
- (function (DocumentRangeFormattingRequest) {
- DocumentRangeFormattingRequest.method = 'textDocument/rangeFormatting';
- DocumentRangeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest.method);
- })(DocumentRangeFormattingRequest = exports.DocumentRangeFormattingRequest || (exports.DocumentRangeFormattingRequest = {}));
- /**
- * A request to format a document on type.
- */
- var DocumentOnTypeFormattingRequest;
- (function (DocumentOnTypeFormattingRequest) {
- DocumentOnTypeFormattingRequest.method = 'textDocument/onTypeFormatting';
- DocumentOnTypeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest.method);
- })(DocumentOnTypeFormattingRequest = exports.DocumentOnTypeFormattingRequest || (exports.DocumentOnTypeFormattingRequest = {}));
- /**
- * A request to rename a symbol.
- */
- var RenameRequest;
- (function (RenameRequest) {
- RenameRequest.method = 'textDocument/rename';
- RenameRequest.type = new messages_1.ProtocolRequestType(RenameRequest.method);
- })(RenameRequest = exports.RenameRequest || (exports.RenameRequest = {}));
- /**
- * A request to test and perform the setup necessary for a rename.
- */
- var PrepareRenameRequest;
- (function (PrepareRenameRequest) {
- PrepareRenameRequest.method = 'textDocument/prepareRename';
- PrepareRenameRequest.type = new messages_1.ProtocolRequestType(PrepareRenameRequest.method);
- })(PrepareRenameRequest = exports.PrepareRenameRequest || (exports.PrepareRenameRequest = {}));
- /**
- * A request send from the client to the server to execute a command. The request might return
- * a workspace edit which the client will apply to the workspace.
- */
- var ExecuteCommandRequest;
- (function (ExecuteCommandRequest) {
- ExecuteCommandRequest.type = new messages_1.ProtocolRequestType('workspace/executeCommand');
- })(ExecuteCommandRequest = exports.ExecuteCommandRequest || (exports.ExecuteCommandRequest = {}));
- /**
- * A request sent from the server to the client to modified certain resources.
- */
- var ApplyWorkspaceEditRequest;
- (function (ApplyWorkspaceEditRequest) {
- ApplyWorkspaceEditRequest.type = new messages_1.ProtocolRequestType('workspace/applyEdit');
- })(ApplyWorkspaceEditRequest = exports.ApplyWorkspaceEditRequest || (exports.ApplyWorkspaceEditRequest = {}));
-
-
- /***/ }),
- /* 20 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- function boolean(value) {
- return value === true || value === false;
- }
- exports.boolean = boolean;
- function string(value) {
- return typeof value === 'string' || value instanceof String;
- }
- exports.string = string;
- function number(value) {
- return typeof value === 'number' || value instanceof Number;
- }
- exports.number = number;
- function error(value) {
- return value instanceof Error;
- }
- exports.error = error;
- function func(value) {
- return typeof value === 'function';
- }
- exports.func = func;
- function array(value) {
- return Array.isArray(value);
- }
- exports.array = array;
- function stringArray(value) {
- return array(value) && value.every(elem => string(elem));
- }
- exports.stringArray = stringArray;
- function typedArray(value, check) {
- return Array.isArray(value) && value.every(check);
- }
- exports.typedArray = typedArray;
- function objectLiteral(value) {
- // Strictly speaking class instances pass this check as well. Since the LSP
- // doesn't use classes we ignore this for now. If we do we need to add something
- // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
- return value !== null && typeof value === 'object';
- }
- exports.objectLiteral = objectLiteral;
-
-
- /***/ }),
- /* 21 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const vscode_jsonrpc_1 = __webpack_require__(4);
- class ProtocolRequestType0 extends vscode_jsonrpc_1.RequestType0 {
- constructor(method) {
- super(method);
- }
- }
- exports.ProtocolRequestType0 = ProtocolRequestType0;
- class ProtocolRequestType extends vscode_jsonrpc_1.RequestType {
- constructor(method) {
- super(method);
- }
- }
- exports.ProtocolRequestType = ProtocolRequestType;
- class ProtocolNotificationType extends vscode_jsonrpc_1.NotificationType {
- constructor(method) {
- super(method);
- }
- }
- exports.ProtocolNotificationType = ProtocolNotificationType;
- class ProtocolNotificationType0 extends vscode_jsonrpc_1.NotificationType0 {
- constructor(method) {
- super(method);
- }
- }
- exports.ProtocolNotificationType0 = ProtocolNotificationType0;
-
-
- /***/ }),
- /* 22 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const vscode_jsonrpc_1 = __webpack_require__(4);
- const messages_1 = __webpack_require__(21);
- // @ts-ignore: to avoid inlining LocatioLink as dynamic import
- let __noDynamicImport;
- /**
- * A request to resolve the implementation locations of a symbol at a given text
- * document position. The request's parameter is of type [TextDocumentPositioParams]
- * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
- * Thenable that resolves to such.
- */
- var ImplementationRequest;
- (function (ImplementationRequest) {
- ImplementationRequest.method = 'textDocument/implementation';
- ImplementationRequest.type = new messages_1.ProtocolRequestType(ImplementationRequest.method);
- /** @deprecated Use ImplementationRequest.type */
- ImplementationRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(ImplementationRequest = exports.ImplementationRequest || (exports.ImplementationRequest = {}));
-
-
- /***/ }),
- /* 23 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const vscode_jsonrpc_1 = __webpack_require__(4);
- const messages_1 = __webpack_require__(21);
- // @ts-ignore: to avoid inlining LocatioLink as dynamic import
- let __noDynamicImport;
- /**
- * A request to resolve the type definition locations of a symbol at a given text
- * document position. The request's parameter is of type [TextDocumentPositioParams]
- * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
- * Thenable that resolves to such.
- */
- var TypeDefinitionRequest;
- (function (TypeDefinitionRequest) {
- TypeDefinitionRequest.method = 'textDocument/typeDefinition';
- TypeDefinitionRequest.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest.method);
- /** @deprecated Use TypeDefinitionRequest.type */
- TypeDefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(TypeDefinitionRequest = exports.TypeDefinitionRequest || (exports.TypeDefinitionRequest = {}));
-
-
- /***/ }),
- /* 24 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const messages_1 = __webpack_require__(21);
- /**
- * The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders.
- */
- var WorkspaceFoldersRequest;
- (function (WorkspaceFoldersRequest) {
- WorkspaceFoldersRequest.type = new messages_1.ProtocolRequestType0('workspace/workspaceFolders');
- })(WorkspaceFoldersRequest = exports.WorkspaceFoldersRequest || (exports.WorkspaceFoldersRequest = {}));
- /**
- * The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace
- * folder configuration changes.
- */
- var DidChangeWorkspaceFoldersNotification;
- (function (DidChangeWorkspaceFoldersNotification) {
- DidChangeWorkspaceFoldersNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWorkspaceFolders');
- })(DidChangeWorkspaceFoldersNotification = exports.DidChangeWorkspaceFoldersNotification || (exports.DidChangeWorkspaceFoldersNotification = {}));
-
-
- /***/ }),
- /* 25 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const messages_1 = __webpack_require__(21);
- /**
- * The 'workspace/configuration' request is sent from the server to the client to fetch a certain
- * configuration setting.
- *
- * This pull model replaces the old push model were the client signaled configuration change via an
- * event. If the server still needs to react to configuration changes (since the server caches the
- * result of `workspace/configuration` requests) the server should register for an empty configuration
- * change event and empty the cache if such an event is received.
- */
- var ConfigurationRequest;
- (function (ConfigurationRequest) {
- ConfigurationRequest.type = new messages_1.ProtocolRequestType('workspace/configuration');
- })(ConfigurationRequest = exports.ConfigurationRequest || (exports.ConfigurationRequest = {}));
-
-
- /***/ }),
- /* 26 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const vscode_jsonrpc_1 = __webpack_require__(4);
- const messages_1 = __webpack_require__(21);
- /**
- * A request to list all color symbols found in a given text document. The request's
- * parameter is of type [DocumentColorParams](#DocumentColorParams) the
- * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
- * that resolves to such.
- */
- var DocumentColorRequest;
- (function (DocumentColorRequest) {
- DocumentColorRequest.method = 'textDocument/documentColor';
- DocumentColorRequest.type = new messages_1.ProtocolRequestType(DocumentColorRequest.method);
- /** @deprecated Use DocumentColorRequest.type */
- DocumentColorRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(DocumentColorRequest = exports.DocumentColorRequest || (exports.DocumentColorRequest = {}));
- /**
- * A request to list all presentation for a color. The request's
- * parameter is of type [ColorPresentationParams](#ColorPresentationParams) the
- * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
- * that resolves to such.
- */
- var ColorPresentationRequest;
- (function (ColorPresentationRequest) {
- ColorPresentationRequest.type = new messages_1.ProtocolRequestType('textDocument/colorPresentation');
- })(ColorPresentationRequest = exports.ColorPresentationRequest || (exports.ColorPresentationRequest = {}));
-
-
- /***/ }),
- /* 27 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- Object.defineProperty(exports, "__esModule", { value: true });
- const vscode_jsonrpc_1 = __webpack_require__(4);
- const messages_1 = __webpack_require__(21);
- /**
- * Enum of known range kinds
- */
- var FoldingRangeKind;
- (function (FoldingRangeKind) {
- /**
- * Folding range for a comment
- */
- FoldingRangeKind["Comment"] = "comment";
- /**
- * Folding range for a imports or includes
- */
- FoldingRangeKind["Imports"] = "imports";
- /**
- * Folding range for a region (e.g. `#region`)
- */
- FoldingRangeKind["Region"] = "region";
- })(FoldingRangeKind = exports.FoldingRangeKind || (exports.FoldingRangeKind = {}));
- /**
- * A request to provide folding ranges in a document. The request's
- * parameter is of type [FoldingRangeParams](#FoldingRangeParams), the
- * response is of type [FoldingRangeList](#FoldingRangeList) or a Thenable
- * that resolves to such.
- */
- var FoldingRangeRequest;
- (function (FoldingRangeRequest) {
- FoldingRangeRequest.method = 'textDocument/foldingRange';
- FoldingRangeRequest.type = new messages_1.ProtocolRequestType(FoldingRangeRequest.method);
- /** @deprecated Use FoldingRangeRequest.type */
- FoldingRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(FoldingRangeRequest = exports.FoldingRangeRequest || (exports.FoldingRangeRequest = {}));
-
-
- /***/ }),
- /* 28 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const vscode_jsonrpc_1 = __webpack_require__(4);
- const messages_1 = __webpack_require__(21);
- // @ts-ignore: to avoid inlining LocatioLink as dynamic import
- let __noDynamicImport;
- /**
- * A request to resolve the type definition locations of a symbol at a given text
- * document position. The request's parameter is of type [TextDocumentPositioParams]
- * (#TextDocumentPositionParams) the response is of type [Declaration](#Declaration)
- * or a typed array of [DeclarationLink](#DeclarationLink) or a Thenable that resolves
- * to such.
- */
- var DeclarationRequest;
- (function (DeclarationRequest) {
- DeclarationRequest.method = 'textDocument/declaration';
- DeclarationRequest.type = new messages_1.ProtocolRequestType(DeclarationRequest.method);
- /** @deprecated Use DeclarationRequest.type */
- DeclarationRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(DeclarationRequest = exports.DeclarationRequest || (exports.DeclarationRequest = {}));
-
-
- /***/ }),
- /* 29 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- Object.defineProperty(exports, "__esModule", { value: true });
- const vscode_jsonrpc_1 = __webpack_require__(4);
- const messages_1 = __webpack_require__(21);
- /**
- * A request to provide selection ranges in a document. The request's
- * parameter is of type [SelectionRangeParams](#SelectionRangeParams), the
- * response is of type [SelectionRange[]](#SelectionRange[]) or a Thenable
- * that resolves to such.
- */
- var SelectionRangeRequest;
- (function (SelectionRangeRequest) {
- SelectionRangeRequest.method = 'textDocument/selectionRange';
- SelectionRangeRequest.type = new messages_1.ProtocolRequestType(SelectionRangeRequest.method);
- /** @deprecated Use SelectionRangeRequest.type */
- SelectionRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();
- })(SelectionRangeRequest = exports.SelectionRangeRequest || (exports.SelectionRangeRequest = {}));
-
-
- /***/ }),
- /* 30 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const vscode_jsonrpc_1 = __webpack_require__(4);
- const messages_1 = __webpack_require__(21);
- var WorkDoneProgress;
- (function (WorkDoneProgress) {
- WorkDoneProgress.type = new vscode_jsonrpc_1.ProgressType();
- })(WorkDoneProgress = exports.WorkDoneProgress || (exports.WorkDoneProgress = {}));
- /**
- * The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress
- * reporting from the server.
- */
- var WorkDoneProgressCreateRequest;
- (function (WorkDoneProgressCreateRequest) {
- WorkDoneProgressCreateRequest.type = new messages_1.ProtocolRequestType('window/workDoneProgress/create');
- })(WorkDoneProgressCreateRequest = exports.WorkDoneProgressCreateRequest || (exports.WorkDoneProgressCreateRequest = {}));
- /**
- * The `window/workDoneProgress/cancel` notification is sent from the client to the server to cancel a progress
- * initiated on the server side.
- */
- var WorkDoneProgressCancelNotification;
- (function (WorkDoneProgressCancelNotification) {
- WorkDoneProgressCancelNotification.type = new messages_1.ProtocolNotificationType('window/workDoneProgress/cancel');
- })(WorkDoneProgressCancelNotification = exports.WorkDoneProgressCancelNotification || (exports.WorkDoneProgressCancelNotification = {}));
-
-
- /***/ }),
- /* 31 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) TypeFox and others. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const messages_1 = __webpack_require__(21);
- /**
- * A request to result a `CallHierarchyItem` in a document at a given position.
- * Can be used as an input to a incoming or outgoing call hierarchy.
- *
- * @since 3.16.0 - Proposed state
- */
- var CallHierarchyPrepareRequest;
- (function (CallHierarchyPrepareRequest) {
- CallHierarchyPrepareRequest.method = 'textDocument/prepareCallHierarchy';
- CallHierarchyPrepareRequest.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest.method);
- })(CallHierarchyPrepareRequest = exports.CallHierarchyPrepareRequest || (exports.CallHierarchyPrepareRequest = {}));
- /**
- * A request to resolve the incoming calls for a given `CallHierarchyItem`.
- *
- * @since 3.16.0 - Proposed state
- */
- var CallHierarchyIncomingCallsRequest;
- (function (CallHierarchyIncomingCallsRequest) {
- CallHierarchyIncomingCallsRequest.method = 'callHierarchy/incomingCalls';
- CallHierarchyIncomingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest.method);
- })(CallHierarchyIncomingCallsRequest = exports.CallHierarchyIncomingCallsRequest || (exports.CallHierarchyIncomingCallsRequest = {}));
- /**
- * A request to resolve the outgoing calls for a given `CallHierarchyItem`.
- *
- * @since 3.16.0 - Proposed state
- */
- var CallHierarchyOutgoingCallsRequest;
- (function (CallHierarchyOutgoingCallsRequest) {
- CallHierarchyOutgoingCallsRequest.method = 'callHierarchy/outgoingCalls';
- CallHierarchyOutgoingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest.method);
- })(CallHierarchyOutgoingCallsRequest = exports.CallHierarchyOutgoingCallsRequest || (exports.CallHierarchyOutgoingCallsRequest = {}));
-
-
- /***/ }),
- /* 32 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
- /* --------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- * ------------------------------------------------------------------------------------------ */
-
- Object.defineProperty(exports, "__esModule", { value: true });
- const messages_1 = __webpack_require__(21);
- /**
- * A set of predefined token types. This set is not fixed
- * an clients can specify additional token types via the
- * corresponding client capabilities.
- *
- * @since 3.16.0 - Proposed state
- */
- var SemanticTokenTypes;
- (function (SemanticTokenTypes) {
- SemanticTokenTypes["comment"] = "comment";
- SemanticTokenTypes["keyword"] = "keyword";
- SemanticTokenTypes["string"] = "string";
- SemanticTokenTypes["number"] = "number";
- SemanticTokenTypes["regexp"] = "regexp";
- SemanticTokenTypes["operator"] = "operator";
- SemanticTokenTypes["namespace"] = "namespace";
- SemanticTokenTypes["type"] = "type";
- SemanticTokenTypes["struct"] = "struct";
- SemanticTokenTypes["class"] = "class";
- SemanticTokenTypes["interface"] = "interface";
- SemanticTokenTypes["enum"] = "enum";
- SemanticTokenTypes["typeParameter"] = "typeParameter";
- SemanticTokenTypes["function"] = "function";
- SemanticTokenTypes["member"] = "member";
- SemanticTokenTypes["property"] = "property";
- SemanticTokenTypes["macro"] = "macro";
- SemanticTokenTypes["variable"] = "variable";
- SemanticTokenTypes["parameter"] = "parameter";
- SemanticTokenTypes["label"] = "label";
- })(SemanticTokenTypes = exports.SemanticTokenTypes || (exports.SemanticTokenTypes = {}));
- /**
- * A set of predefined token modifiers. This set is not fixed
- * an clients can specify additional token types via the
- * corresponding client capabilities.
- *
- * @since 3.16.0 - Proposed state
- */
- var SemanticTokenModifiers;
- (function (SemanticTokenModifiers) {
- SemanticTokenModifiers["documentation"] = "documentation";
- SemanticTokenModifiers["declaration"] = "declaration";
- SemanticTokenModifiers["definition"] = "definition";
- SemanticTokenModifiers["reference"] = "reference";
- SemanticTokenModifiers["static"] = "static";
- SemanticTokenModifiers["abstract"] = "abstract";
- SemanticTokenModifiers["deprecated"] = "deprecated";
- SemanticTokenModifiers["async"] = "async";
- SemanticTokenModifiers["volatile"] = "volatile";
- SemanticTokenModifiers["readonly"] = "readonly";
- })(SemanticTokenModifiers = exports.SemanticTokenModifiers || (exports.SemanticTokenModifiers = {}));
- /**
- * @since 3.16.0 - Proposed state
- */
- var SemanticTokens;
- (function (SemanticTokens) {
- function is(value) {
- const candidate = value;
- return candidate !== undefined && (candidate.resultId === undefined || typeof candidate.resultId === 'string') &&
- Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number');
- }
- SemanticTokens.is = is;
- })(SemanticTokens = exports.SemanticTokens || (exports.SemanticTokens = {}));
- /**
- * @since 3.16.0 - Proposed state
- */
- var SemanticTokensRequest;
- (function (SemanticTokensRequest) {
- SemanticTokensRequest.method = 'textDocument/semanticTokens';
- SemanticTokensRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRequest.method);
- })(SemanticTokensRequest = exports.SemanticTokensRequest || (exports.SemanticTokensRequest = {}));
- /**
- * @since 3.16.0 - Proposed state
- */
- var SemanticTokensEditsRequest;
- (function (SemanticTokensEditsRequest) {
- SemanticTokensEditsRequest.method = 'textDocument/semanticTokens/edits';
- SemanticTokensEditsRequest.type = new messages_1.ProtocolRequestType(SemanticTokensEditsRequest.method);
- })(SemanticTokensEditsRequest = exports.SemanticTokensEditsRequest || (exports.SemanticTokensEditsRequest = {}));
- /**
- * @since 3.16.0 - Proposed state
- */
- var SemanticTokensRangeRequest;
- (function (SemanticTokensRangeRequest) {
- SemanticTokensRangeRequest.method = 'textDocument/semanticTokens/range';
- SemanticTokensRangeRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest.method);
- })(SemanticTokensRangeRequest = exports.SemanticTokensRangeRequest || (exports.SemanticTokensRangeRequest = {}));
-
-
- /***/ }),
- /* 33 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const coc_nvim_1 = __webpack_require__(1);
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- const languageProvider_1 = __importDefault(__webpack_require__(34));
- const PConst = __importStar(__webpack_require__(39));
- const typescriptServiceClient_1 = __importDefault(__webpack_require__(117));
- const typeConverters = __importStar(__webpack_require__(37));
- const typingsStatus_1 = __importStar(__webpack_require__(139));
- // Style check diagnostics that can be reported as warnings
- const styleCheckDiagnostics = [
- 6133,
- 6138,
- 7027,
- 7028,
- 7029,
- 7030 // not all code paths return a value
- ];
- class TypeScriptServiceClientHost {
- constructor(descriptions, pluginManager) {
- this.languages = [];
- this.languagePerId = new Map();
- this.disposables = [];
- this.reportStyleCheckAsWarnings = true;
- let timer;
- const handleProjectChange = () => {
- if (timer)
- clearTimeout(timer);
- timer = setTimeout(() => {
- this.triggerAllDiagnostics();
- }, 1500);
- };
- const configFileWatcher = coc_nvim_1.workspace.createFileSystemWatcher('**/[tj]sconfig.json');
- this.disposables.push(configFileWatcher);
- configFileWatcher.onDidCreate(this.reloadProjects, this, this.disposables);
- configFileWatcher.onDidDelete(this.reloadProjects, this, this.disposables);
- configFileWatcher.onDidChange(handleProjectChange, this, this.disposables);
- const packageFileWatcher = coc_nvim_1.workspace.createFileSystemWatcher('**/package.json');
- packageFileWatcher.onDidCreate(this.reloadProjects, this, this.disposables);
- packageFileWatcher.onDidChange(handleProjectChange, this, this.disposables);
- this.client = new typescriptServiceClient_1.default(pluginManager);
- this.disposables.push(this.client);
- this.client.onDiagnosticsReceived(({ kind, resource, diagnostics }) => {
- this.diagnosticsReceived(kind, resource, diagnostics);
- }, null, this.disposables);
- this.client.onConfigDiagnosticsReceived(diag => {
- let { body } = diag;
- if (body) {
- let { configFile, diagnostics } = body;
- let uri = coc_nvim_1.Uri.file(configFile);
- if (diagnostics.length == 0) {
- this.client.diagnosticsManager.configFileDiagnosticsReceived(uri.toString(), []);
- }
- else {
- let diagnosticList = diagnostics.map(o => {
- let { text, code, category, start, end } = o;
- let range;
- if (!start || !end) {
- range = vscode_languageserver_protocol_1.Range.create(vscode_languageserver_protocol_1.Position.create(0, 0), vscode_languageserver_protocol_1.Position.create(0, 1));
- }
- else {
- range = vscode_languageserver_protocol_1.Range.create(start.line - 1, start.offset - 1, end.line - 1, end.offset - 1);
- }
- let severity = category == 'error' ? vscode_languageserver_protocol_1.DiagnosticSeverity.Error : vscode_languageserver_protocol_1.DiagnosticSeverity.Warning;
- return vscode_languageserver_protocol_1.Diagnostic.create(range, text, severity, code);
- });
- this.client.diagnosticsManager.configFileDiagnosticsReceived(uri.toString(), diagnosticList);
- }
- }
- }, null, this.disposables);
- this.typingsStatus = new typingsStatus_1.default(this.client);
- this.ataProgressReporter = new typingsStatus_1.AtaProgressReporter(this.client);
- for (const description of descriptions) { // tslint:disable-line
- const manager = new languageProvider_1.default(this.client, description, this.typingsStatus);
- this.languages.push(manager);
- this.disposables.push(manager);
- this.languagePerId.set(description.id, manager);
- }
- this.client.ensureServiceStarted();
- this.client.onTsServerStarted(() => {
- this.triggerAllDiagnostics();
- });
- coc_nvim_1.workspace.onDidChangeConfiguration(this.configurationChanged, this, this.disposables);
- this.configurationChanged();
- }
- dispose() {
- coc_nvim_1.disposeAll(this.disposables);
- this.typingsStatus.dispose();
- this.ataProgressReporter.dispose();
- }
- reset() {
- for (let lang of this.languages) {
- lang.fileConfigurationManager.reset();
- }
- }
- get serviceClient() {
- return this.client;
- }
- reloadProjects() {
- this.client.execute('reloadProjects', null, vscode_languageserver_protocol_1.CancellationToken.None);
- this.triggerAllDiagnostics();
- }
- // typescript or javascript
- getProvider(languageId) {
- return this.languagePerId.get(languageId);
- }
- configurationChanged() {
- const config = coc_nvim_1.workspace.getConfiguration('tsserver');
- this.reportStyleCheckAsWarnings = config.get('reportStyleChecksAsWarnings', true);
- }
- findLanguage(resource) {
- try {
- return this.languages.find(language => language.handles(resource));
- }
- catch (_a) {
- return null;
- }
- }
- handles(uri) {
- return this.findLanguage(coc_nvim_1.Uri.parse(uri)) != null;
- }
- triggerAllDiagnostics() {
- for (const language of this.languagePerId.values()) {
- language.triggerAllDiagnostics();
- }
- }
- diagnosticsReceived(kind, resource, diagnostics) {
- const language = this.findLanguage(resource);
- if (language) {
- language.diagnosticsReceived(kind, resource, this.createMarkerDatas(diagnostics));
- }
- }
- createMarkerDatas(diagnostics) {
- return diagnostics.map(tsDiag => this.tsDiagnosticToLspDiagnostic(tsDiag));
- }
- tsDiagnosticToLspDiagnostic(diagnostic) {
- const { start, end, text } = diagnostic;
- const range = {
- start: typeConverters.Position.fromLocation(start),
- end: typeConverters.Position.fromLocation(end)
- };
- let relatedInformation;
- if (diagnostic.relatedInformation) {
- relatedInformation = diagnostic.relatedInformation.map(o => {
- let { span, message } = o;
- return {
- location: typeConverters.Location.fromTextSpan(this.client.toResource(span.file), span),
- message
- };
- });
- }
- return {
- range,
- message: text,
- code: diagnostic.code ? diagnostic.code : null,
- severity: this.getDiagnosticSeverity(diagnostic),
- reportUnnecessary: diagnostic.reportsUnnecessary,
- source: diagnostic.source || 'tsserver',
- relatedInformation
- };
- }
- getDiagnosticSeverity(diagnostic) {
- if (this.reportStyleCheckAsWarnings &&
- this.isStyleCheckDiagnostic(diagnostic.code) &&
- diagnostic.category === PConst.DiagnosticCategory.error) {
- return vscode_languageserver_protocol_1.DiagnosticSeverity.Warning;
- }
- switch (diagnostic.category) {
- case PConst.DiagnosticCategory.error:
- return vscode_languageserver_protocol_1.DiagnosticSeverity.Error;
- case PConst.DiagnosticCategory.warning:
- return vscode_languageserver_protocol_1.DiagnosticSeverity.Warning;
- case PConst.DiagnosticCategory.suggestion:
- return vscode_languageserver_protocol_1.DiagnosticSeverity.Information;
- default:
- return vscode_languageserver_protocol_1.DiagnosticSeverity.Error;
- }
- }
- isStyleCheckDiagnostic(code) {
- return code ? styleCheckDiagnostics.indexOf(code) !== -1 : false;
- }
- }
- exports.default = TypeScriptServiceClientHost;
-
-
- /***/ }),
- /* 34 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- const coc_nvim_1 = __webpack_require__(1);
- const baseCodeLensProvider_1 = __webpack_require__(35);
- const completionItemProvider_1 = __importDefault(__webpack_require__(38));
- const definitionProvider_1 = __importDefault(__webpack_require__(88));
- const directiveCommentCompletions_1 = __importDefault(__webpack_require__(89));
- const documentHighlight_1 = __importDefault(__webpack_require__(90));
- const documentSymbol_1 = __importDefault(__webpack_require__(92));
- const fileConfigurationManager_1 = __importDefault(__webpack_require__(93));
- const folding_1 = __importDefault(__webpack_require__(94));
- const formatting_1 = __importDefault(__webpack_require__(95));
- const hover_1 = __importDefault(__webpack_require__(96));
- const implementationsCodeLens_1 = __importDefault(__webpack_require__(97));
- // import TagCompletionProvider from './features/tagCompletion'
- const quickfix_1 = __importDefault(__webpack_require__(98));
- const importFix_1 = __importDefault(__webpack_require__(99));
- const refactor_1 = __importDefault(__webpack_require__(101));
- const references_1 = __importDefault(__webpack_require__(102));
- const referencesCodeLens_1 = __importDefault(__webpack_require__(103));
- const rename_1 = __importDefault(__webpack_require__(104));
- const signatureHelp_1 = __importDefault(__webpack_require__(105));
- const updatePathOnRename_1 = __importDefault(__webpack_require__(106));
- const watchBuild_1 = __importDefault(__webpack_require__(108));
- const workspaceSymbols_1 = __importDefault(__webpack_require__(109));
- const smartSelect_1 = __importDefault(__webpack_require__(110));
- const moduleInstall_1 = __importDefault(__webpack_require__(111));
- const api_1 = __importDefault(__webpack_require__(40));
- const organizeImports_1 = __webpack_require__(114);
- const suggestionSetting = 'suggestionActions.enabled';
- class LanguageProvider {
- constructor(client, description, typingsStatus) {
- this.client = client;
- this.description = description;
- this.disposables = [];
- this.fileConfigurationManager = new fileConfigurationManager_1.default(client);
- coc_nvim_1.workspace.onDidChangeConfiguration(this.configurationChanged, this, this.disposables);
- this.configurationChanged();
- let initialized = false;
- client.onTsServerStarted(() => __awaiter(this, void 0, void 0, function* () {
- if (!initialized) {
- initialized = true;
- this.registerProviders(client, typingsStatus);
- }
- else {
- this.client.diagnosticsManager.reInitialize();
- }
- }));
- }
- configurationChanged() {
- const config = coc_nvim_1.workspace.getConfiguration(this.id, null);
- this.client.diagnosticsManager.setEnableSuggestions(this.id, config.get(suggestionSetting, true));
- }
- dispose() {
- coc_nvim_1.disposeAll(this.disposables);
- }
- registerProviders(client, typingsStatus) {
- let languageIds = this.description.modeIds;
- this.disposables.push(coc_nvim_1.languages.registerCompletionItemProvider(`tsserver-${this.description.id}`, 'TSC', languageIds, new completionItemProvider_1.default(client, typingsStatus, this.fileConfigurationManager, this.description.id), completionItemProvider_1.default.triggerCharacters));
- if (this.client.apiVersion.gte(api_1.default.v230)) {
- this.disposables.push(coc_nvim_1.languages.registerCompletionItemProvider(`${this.description.id}-directive`, 'TSC', languageIds, new directiveCommentCompletions_1.default(client), ['@']));
- }
- let definitionProvider = new definitionProvider_1.default(client);
- this.disposables.push(coc_nvim_1.languages.registerDefinitionProvider(languageIds, definitionProvider));
- this.disposables.push(coc_nvim_1.languages.registerTypeDefinitionProvider(languageIds, definitionProvider));
- this.disposables.push(coc_nvim_1.languages.registerImplementationProvider(languageIds, definitionProvider));
- this.disposables.push(coc_nvim_1.languages.registerReferencesProvider(languageIds, new references_1.default(client)));
- this.disposables.push(coc_nvim_1.languages.registerHoverProvider(languageIds, new hover_1.default(client)));
- this.disposables.push(coc_nvim_1.languages.registerDocumentHighlightProvider(languageIds, new documentHighlight_1.default(this.client)));
- this.disposables.push(coc_nvim_1.languages.registerSignatureHelpProvider(languageIds, new signatureHelp_1.default(client), ['(', ',', '<', ')']));
- this.disposables.push(coc_nvim_1.languages.registerDocumentSymbolProvider(languageIds, new documentSymbol_1.default(client)));
- this.disposables.push(coc_nvim_1.languages.registerWorkspaceSymbolProvider(languageIds, new workspaceSymbols_1.default(client, languageIds)));
- this.disposables.push(coc_nvim_1.languages.registerRenameProvider(languageIds, new rename_1.default(client)));
- let formatProvider = new formatting_1.default(client, this.fileConfigurationManager);
- this.disposables.push(coc_nvim_1.languages.registerDocumentFormatProvider(languageIds, formatProvider));
- this.disposables.push(coc_nvim_1.languages.registerDocumentRangeFormatProvider(languageIds, formatProvider));
- this.disposables.push(coc_nvim_1.languages.registerOnTypeFormattingEditProvider(languageIds, formatProvider, [';', '}', '\n', String.fromCharCode(27)]));
- // this.disposables.push(
- // new ProjectError(client, commandManager)
- // )
- if (this.client.apiVersion.gte(api_1.default.v280)) {
- this.disposables.push(coc_nvim_1.languages.registerFoldingRangeProvider(languageIds, new folding_1.default(this.client)));
- this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new organizeImports_1.OrganizeImportsCodeActionProvider(this.client, this.fileConfigurationManager), `tsserver-${this.description.id}`, [vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports]));
- }
- let { fileConfigurationManager } = this;
- let conf = fileConfigurationManager.getLanguageConfiguration(this.id);
- if (this.client.apiVersion.gte(api_1.default.v290)
- && conf.get('updateImportsOnFileMove.enable')) {
- this.disposables.push(new updatePathOnRename_1.default(client, this.fileConfigurationManager, this.id));
- }
- if (this.client.apiVersion.gte(api_1.default.v240)) {
- this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new refactor_1.default(client, this.fileConfigurationManager), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.Refactor]));
- }
- this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new moduleInstall_1.default(client), 'tsserver'));
- this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new quickfix_1.default(client), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.QuickFix]));
- this.disposables.push(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new importFix_1.default(this.client.bufferSyncSupport), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.QuickFix]));
- let cachedResponse = new baseCodeLensProvider_1.CachedNavTreeResponse();
- if (this.client.apiVersion.gte(api_1.default.v206)
- && conf.get('referencesCodeLens.enable')) {
- this.disposables.push(coc_nvim_1.languages.registerCodeLensProvider(languageIds, new referencesCodeLens_1.default(client, cachedResponse)));
- }
- if (this.client.apiVersion.gte(api_1.default.v220)
- && conf.get('implementationsCodeLens.enable')) {
- this.disposables.push(coc_nvim_1.languages.registerCodeLensProvider(languageIds, new implementationsCodeLens_1.default(client, cachedResponse)));
- }
- if (this.client.apiVersion.gte(api_1.default.v350)) {
- this.disposables.push(coc_nvim_1.languages.registerSelectionRangeProvider(languageIds, new smartSelect_1.default(this.client)));
- }
- if (this.description.id == 'typescript') {
- // this.client.apiVersion
- this.disposables.push(new watchBuild_1.default(coc_nvim_1.commands, this.client));
- }
- // if (this.client.apiVersion.gte(API.v300)) {
- // this.disposables.push(
- // languages.registerCompletionItemProvider(
- // `tsserver-${this.description.id}-tag`,
- // 'TSC',
- // languageIds,
- // new TagCompletionProvider(client),
- // ['>']
- // )
- // )
- // }
- }
- handles(resource) {
- let { modeIds, configFile } = this.description;
- if (resource.toString().endsWith(configFile)) {
- return true;
- }
- let doc = coc_nvim_1.workspace.getDocument(resource.toString());
- if (doc && modeIds.indexOf(doc.filetype) !== -1) {
- return true;
- }
- let str = resource.toString();
- if (this.id === 'typescript' && /\.ts(x)?$/.test(str)) {
- return true;
- }
- if (this.id === 'javascript' && /\.js(x)?$/.test(str)) {
- return true;
- }
- return false;
- }
- get id() {
- return this.description.id;
- }
- get diagnosticSource() {
- return this.description.diagnosticSource;
- }
- triggerAllDiagnostics() {
- this.client.bufferSyncSupport.requestAllDiagnostics();
- }
- diagnosticsReceived(diagnosticsKind, file, diagnostics) {
- if (!this.client.bufferSyncSupport.shouldValidate(file.toString())) {
- return;
- }
- const config = coc_nvim_1.workspace.getConfiguration(this.id, file.toString());
- const reportUnnecessary = config.get('showUnused', true);
- this.client.diagnosticsManager.diagnosticsReceived(diagnosticsKind, file.toString(), diagnostics.filter(diag => {
- if (!reportUnnecessary) {
- diag.tags = undefined;
- if (diag.reportUnnecessary && diag.severity === vscode_languageserver_protocol_1.DiagnosticSeverity.Information) {
- return false;
- }
- }
- return true;
- }));
- }
- }
- exports.default = LanguageProvider;
-
-
- /***/ }),
- /* 35 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.TypeScriptBaseCodeLensProvider = exports.CachedNavTreeResponse = void 0;
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- const regexp_1 = __webpack_require__(36);
- const typeConverters = __importStar(__webpack_require__(37));
- class CachedNavTreeResponse {
- constructor() {
- this.version = -1;
- this.document = '';
- }
- execute(document, f) {
- if (this.matches(document)) {
- return this.response;
- }
- return this.update(document, f());
- }
- matches(document) {
- return (this.version === document.version &&
- this.document === document.uri.toString());
- }
- update(document, response) {
- this.response = response;
- this.version = document.version;
- this.document = document.uri.toString();
- return response;
- }
- }
- exports.CachedNavTreeResponse = CachedNavTreeResponse;
- class TypeScriptBaseCodeLensProvider {
- constructor(client, cachedResponse) {
- this.client = client;
- this.cachedResponse = cachedResponse;
- this.onDidChangeCodeLensesEmitter = new vscode_languageserver_protocol_1.Emitter();
- }
- get onDidChangeCodeLenses() {
- return this.onDidChangeCodeLensesEmitter.event;
- }
- provideCodeLenses(document, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const filepath = this.client.toPath(document.uri);
- if (!filepath) {
- return [];
- }
- try {
- const response = yield this.cachedResponse.execute(document, () => this.client.execute('navtree', { file: filepath }, token));
- if (!response) {
- return [];
- }
- const tree = response.body;
- const referenceableSpans = [];
- if (tree && tree.childItems) {
- tree.childItems.forEach(item => this.walkNavTree(document, item, null, referenceableSpans));
- }
- return referenceableSpans.map(range => {
- return {
- range,
- data: { uri: document.uri }
- };
- });
- }
- catch (_a) {
- return [];
- }
- });
- }
- walkNavTree(document, item, parent, results) {
- if (!item) {
- return;
- }
- const range = this.extractSymbol(document, item, parent);
- if (range) {
- results.push(range);
- }
- if (item.childItems) {
- item.childItems.forEach(child => this.walkNavTree(document, child, item, results));
- }
- }
- getSymbolRange(document, item) {
- if (!item) {
- return null;
- }
- // TS 3.0+ provides a span for just the symbol
- if (item.nameSpan) {
- return typeConverters.Range.fromTextSpan(item.nameSpan);
- }
- // In older versions, we have to calculate this manually. See #23924
- const span = item.spans && item.spans[0];
- if (!span) {
- return null;
- }
- const range = typeConverters.Range.fromTextSpan(span);
- const text = document.getText(range);
- const identifierMatch = new RegExp(`^(.*?(\\b|\\W))${regexp_1.escapeRegExp(item.text || '')}(\\b|\\W)`, 'gm');
- const match = identifierMatch.exec(text);
- const prefixLength = match ? match.index + match[1].length : 0;
- const startOffset = document.offsetAt(range.start) + prefixLength;
- return {
- start: document.positionAt(startOffset),
- end: document.positionAt(startOffset + item.text.length)
- };
- }
- }
- exports.TypeScriptBaseCodeLensProvider = TypeScriptBaseCodeLensProvider;
-
-
- /***/ }),
- /* 36 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.escapeRegExp = void 0;
- function escapeRegExp(text) {
- return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
- }
- exports.escapeRegExp = escapeRegExp;
-
-
- /***/ }),
- /* 37 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.WorkspaceEdit = exports.TextEdit = exports.Location = exports.Position = exports.Range = void 0;
- var Range;
- (function (Range) {
- Range.fromTextSpan = (span) => {
- return {
- start: {
- line: span.start.line - 1,
- character: span.start.offset - 1
- },
- end: {
- line: span.end.line - 1,
- character: span.end.offset - 1
- }
- };
- };
- Range.toFormattingRequestArgs = (file, range) => ({
- file,
- line: range.start.line + 1,
- offset: range.start.character + 1,
- endLine: range.end.line + 1,
- endOffset: range.end.character + 1
- });
- Range.toFileRangeRequestArgs = (file, range) => ({
- file,
- startLine: range.start.line + 1,
- startOffset: range.start.character + 1,
- endLine: range.end.line + 1,
- endOffset: range.end.character + 1
- });
- })(Range = exports.Range || (exports.Range = {}));
- var Position;
- (function (Position) {
- Position.fromLocation = (tslocation) => {
- return {
- line: tslocation.line - 1,
- character: tslocation.offset - 1
- };
- };
- Position.toLocation = (position) => ({
- line: position.line + 1,
- offset: position.character + 1,
- });
- Position.toFileLocationRequestArgs = (file, position) => ({
- file,
- line: position.line + 1,
- offset: position.character + 1
- });
- })(Position = exports.Position || (exports.Position = {}));
- var Location;
- (function (Location) {
- Location.fromTextSpan = (uri, tsTextSpan) => {
- return {
- uri,
- range: Range.fromTextSpan(tsTextSpan)
- };
- };
- })(Location = exports.Location || (exports.Location = {}));
- var TextEdit;
- (function (TextEdit) {
- TextEdit.fromCodeEdit = (edit) => {
- return {
- range: Range.fromTextSpan(edit),
- newText: edit.newText
- };
- };
- })(TextEdit = exports.TextEdit || (exports.TextEdit = {}));
- var WorkspaceEdit;
- (function (WorkspaceEdit) {
- function fromFileCodeEdits(client, edits) {
- let changes = {};
- for (const edit of edits) {
- let uri = client.toResource(edit.fileName);
- changes[uri] = edit.textChanges.map(change => {
- return TextEdit.fromCodeEdit(change);
- });
- }
- return { changes };
- }
- WorkspaceEdit.fromFileCodeEdits = fromFileCodeEdits;
- })(WorkspaceEdit = exports.WorkspaceEdit || (exports.WorkspaceEdit = {}));
-
-
- /***/ }),
- /* 38 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- const coc_nvim_1 = __webpack_require__(1);
- const PConst = __importStar(__webpack_require__(39));
- const api_1 = __importDefault(__webpack_require__(40));
- const codeAction_1 = __webpack_require__(84);
- const completionItem_1 = __webpack_require__(85);
- const Previewer = __importStar(__webpack_require__(86));
- const typeConverters = __importStar(__webpack_require__(37));
- const SnippetString_1 = __importDefault(__webpack_require__(87));
- class ApplyCompletionCodeActionCommand {
- constructor(client) {
- this.client = client;
- this.id = ApplyCompletionCodeActionCommand.ID;
- }
- // apply code action on complete
- execute(codeActions) {
- return __awaiter(this, void 0, void 0, function* () {
- if (codeActions.length === 0) {
- return;
- }
- if (codeActions.length === 1) {
- yield codeAction_1.applyCodeAction(this.client, codeActions[0]);
- return;
- }
- const idx = yield coc_nvim_1.workspace.showQuickpick(codeActions.map(o => o.description), 'Select code action to apply');
- if (idx < 0)
- return;
- const action = codeActions[idx];
- yield codeAction_1.applyCodeAction(this.client, action);
- return;
- });
- }
- }
- ApplyCompletionCodeActionCommand.ID = '_typescript.applyCompletionCodeAction';
- class TypeScriptCompletionItemProvider {
- constructor(client, typingsStatus, fileConfigurationManager, languageId) {
- this.client = client;
- this.typingsStatus = typingsStatus;
- this.fileConfigurationManager = fileConfigurationManager;
- this.setCompleteOption(languageId);
- coc_nvim_1.commands.register(new ApplyCompletionCodeActionCommand(this.client));
- coc_nvim_1.workspace.onDidChangeConfiguration(_e => {
- this.setCompleteOption(languageId);
- });
- }
- setCompleteOption(languageId) {
- this.completeOption = this.fileConfigurationManager.getCompleteOptions(languageId);
- }
- /**
- * Get completionItems
- *
- * @public
- * @param {TextDocument} document
- * @param {Position} position
- * @param {CancellationToken} token
- * @param {string} triggerCharacter
- * @returns {Promise<CompletionItem[]>}
- */
- provideCompletionItems(document, position, token, context) {
- return __awaiter(this, void 0, void 0, function* () {
- if (this.typingsStatus.isAcquiringTypings) {
- return Promise.resolve({
- isIncomplete: true,
- items: [{
- label: 'Acquiring typings...',
- detail: 'Acquiring typings definitions for IntelliSense.'
- }]
- });
- }
- let { uri } = document;
- const file = this.client.toPath(document.uri);
- if (!file)
- return null;
- let preText = document.getText({
- start: { line: position.line, character: 0 },
- end: position
- });
- let { triggerCharacter, option } = context;
- if (!this.shouldTrigger(triggerCharacter, preText, option)) {
- return null;
- }
- const { completeOption } = this;
- const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { includeExternalModuleExports: completeOption.autoImports, includeInsertTextCompletions: true, triggerCharacter: this.getTsTriggerCharacter(context), includeAutomaticOptionalChainCompletions: completeOption.includeAutomaticOptionalChainCompletions });
- let entries;
- let dotAccessorContext;
- let isNewIdentifierLocation = true;
- let isMemberCompletion = false;
- let isIncomplete = false;
- const isInValidCommitCharacterContext = this.isInValidCommitCharacterContext(document, position);
- if (this.client.apiVersion.gte(api_1.default.v300)) {
- try {
- const response = yield this.client.interruptGetErr(() => this.client.execute('completionInfo', args, token));
- if (response.type !== 'response' || !response.body) {
- return null;
- }
- isNewIdentifierLocation = response.body.isNewIdentifierLocation;
- isMemberCompletion = response.body.isMemberCompletion;
- if (isMemberCompletion) {
- const dotMatch = preText.slice(0, position.character).match(/\??\.\s*$/) || undefined;
- if (dotMatch) {
- const range = vscode_languageserver_protocol_1.Range.create({
- line: position.line,
- character: position.character - dotMatch.length
- }, position);
- const text = document.getText(range);
- dotAccessorContext = { range, text };
- }
- }
- isIncomplete = response.metadata && response.metadata.isIncomplete;
- entries = response.body.entries;
- }
- catch (e) {
- if (e.message == 'No content available.') {
- return null;
- }
- throw e;
- }
- }
- else {
- const response = yield this.client.interruptGetErr(() => this.client.execute('completions', args, token));
- if (response.type !== 'response' || !response.body) {
- return null;
- }
- entries = response.body;
- }
- const completionItems = [];
- for (const element of entries) {
- if (shouldExcludeCompletionEntry(element, completeOption)) {
- continue;
- }
- const item = completionItem_1.convertCompletionEntry(element, uri, position, {
- isNewIdentifierLocation,
- isMemberCompletion,
- enableCallCompletions: completeOption.completeFunctionCalls,
- isInValidCommitCharacterContext,
- dotAccessorContext,
- });
- completionItems.push(item);
- }
- return { isIncomplete, items: completionItems };
- });
- }
- getTsTriggerCharacter(context) {
- // return context.triggerCharacter as Proto.CompletionsTriggerCharacter
- switch (context.triggerCharacter) {
- case '@': // Workaround for https://github.com/Microsoft/TypeScript/issues/27321
- return this.client.apiVersion.gte(api_1.default.v310) && this.client.apiVersion.lt(api_1.default.v320) ? undefined : '@';
- case '#': // Workaround for https://github.com/microsoft/TypeScript/issues/36367
- return this.client.apiVersion.lt(api_1.default.v381) ? undefined : '#';
- case '.':
- case '"':
- case '\'':
- case '`':
- case '/':
- case '<':
- return context.triggerCharacter;
- }
- return undefined;
- }
- /**
- * Resolve complete item, could have documentation added
- *
- * @public
- * @param {CompletionItem} item
- * @param {CancellationToken} token
- * @returns {Promise<CompletionItem>}
- */
- resolveCompletionItem(item, token) {
- return __awaiter(this, void 0, void 0, function* () {
- if (item == null)
- return undefined;
- let { uri, position, source } = item.data;
- const filepath = this.client.toPath(uri);
- if (!filepath)
- return undefined;
- let document = coc_nvim_1.workspace.getDocument(uri);
- if (!document)
- return undefined;
- const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(filepath, position)), { entryNames: [
- source
- ? { name: item.label, source }
- : item.label
- ] });
- let response;
- try {
- response = yield this.client.interruptGetErr(() => this.client.execute('completionEntryDetails', args, token));
- }
- catch (_a) {
- return item;
- }
- if (response.type !== 'response' || !response.body) {
- return item;
- }
- const details = response.body;
- if (!details || !details.length || !details[0]) {
- return item;
- }
- const detail = details[0];
- if (!item.detail && detail.displayParts.length) {
- item.detail = Previewer.plain(detail.displayParts);
- }
- item.documentation = this.getDocumentation(detail);
- const { command, additionalTextEdits } = this.getCodeActions(detail, filepath);
- if (command)
- item.command = command;
- item.additionalTextEdits = additionalTextEdits;
- if (detail && item.insertTextFormat == vscode_languageserver_protocol_1.InsertTextFormat.Snippet) {
- const shouldCompleteFunction = yield this.isValidFunctionCompletionContext(filepath, position, token);
- if (shouldCompleteFunction) {
- this.createSnippetOfFunctionCall(item, detail);
- }
- }
- return item;
- });
- }
- getCodeActions(detail, filepath) {
- if (!detail.codeActions || !detail.codeActions.length) {
- return {};
- }
- // Try to extract out the additionalTextEdits for the current file.
- // Also check if we still have to apply other workspace edits
- const additionalTextEdits = [];
- let hasRemainingCommandsOrEdits = false;
- for (const tsAction of detail.codeActions) {
- if (tsAction.commands) {
- hasRemainingCommandsOrEdits = true;
- }
- // Convert all edits in the current file using `additionalTextEdits`
- if (tsAction.changes) {
- for (const change of tsAction.changes) {
- if (change.fileName === filepath) {
- additionalTextEdits.push(...change.textChanges.map(typeConverters.TextEdit.fromCodeEdit));
- }
- else {
- hasRemainingCommandsOrEdits = true;
- }
- }
- }
- }
- let command = null;
- if (hasRemainingCommandsOrEdits) {
- // Create command that applies all edits not in the current file.
- command = {
- title: '',
- command: ApplyCompletionCodeActionCommand.ID,
- arguments: [
- detail.codeActions.map((x) => ({
- commands: x.commands,
- description: x.description,
- changes: x.changes.filter(x => x.fileName !== filepath)
- }))
- ]
- };
- }
- return {
- command,
- additionalTextEdits: additionalTextEdits.length
- ? additionalTextEdits
- : undefined
- };
- }
- shouldTrigger(triggerCharacter, pre, option) {
- if (triggerCharacter && this.client.apiVersion.lt(api_1.default.v290)) {
- if (triggerCharacter === '@') {
- // trigger in string
- if (option.synname && /string/i.test(option.synname)) {
- return true;
- }
- // make sure we are in something that looks like the start of a jsdoc comment
- if (!pre.match(/^\s*\*[ ]?@/) && !pre.match(/\/\*\*+[ ]?@/)) {
- return false;
- }
- }
- else if (triggerCharacter === '<') {
- return false;
- }
- }
- return true;
- }
- // complete item documentation
- getDocumentation(detail) {
- let documentation = '';
- if (detail.source) {
- const importPath = `'${Previewer.plain(detail.source)}'`;
- const autoImportLabel = `Auto import from ${importPath}`;
- documentation += `${autoImportLabel}\n`;
- }
- let parts = [
- Previewer.plain(detail.documentation),
- Previewer.tagsMarkdownPreview(detail.tags)
- ];
- parts = parts.filter(s => s && s.trim() != '');
- documentation += parts.join('\n\n');
- if (documentation.length) {
- return {
- kind: vscode_languageserver_protocol_1.MarkupKind.Markdown,
- value: documentation
- };
- }
- return undefined;
- }
- createSnippetOfFunctionCall(item, detail) {
- let { displayParts } = detail;
- const parameterListParts = completionItem_1.getParameterListParts(displayParts);
- const snippet = new SnippetString_1.default();
- snippet.appendText(`${item.insertText || item.label}(`);
- appendJoinedPlaceholders(snippet, parameterListParts.parts, ', ');
- if (parameterListParts.hasOptionalParameters) {
- snippet.appendTabstop();
- }
- snippet.appendText(')');
- snippet.appendTabstop(0);
- item.insertText = snippet.value;
- }
- isValidFunctionCompletionContext(filepath, position, token) {
- return __awaiter(this, void 0, void 0, function* () {
- // Workaround for https://github.com/Microsoft/TypeScript/issues/12677
- // Don't complete function calls inside of destructive assigments or imports
- try {
- const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
- const response = yield this.client.execute('quickinfo', args, token);
- if (response.type !== 'response') {
- return true;
- }
- const { body } = response;
- switch (body && body.kind) {
- case 'var':
- case 'let':
- case 'const':
- case 'alias':
- return false;
- default:
- return true;
- }
- }
- catch (e) {
- return true;
- }
- });
- }
- isInValidCommitCharacterContext(document, position) {
- if (this.client.apiVersion.lt(api_1.default.v320)) {
- // Workaround for https://github.com/Microsoft/TypeScript/issues/27742
- // Only enable dot completions when previous character not a dot preceded by whitespace.
- // Prevents incorrectly completing while typing spread operators.
- if (position.character > 1) {
- const preText = document.getText(vscode_languageserver_protocol_1.Range.create(position.line, 0, position.line, position.character));
- return preText.match(/(\s|^)\.$/ig) === null;
- }
- }
- return true;
- }
- }
- exports.default = TypeScriptCompletionItemProvider;
- TypeScriptCompletionItemProvider.triggerCharacters = ['.', '"', '\'', '`', '/', '@', '<', '#'];
- function shouldExcludeCompletionEntry(element, completionConfiguration) {
- return ((!completionConfiguration.names && element.kind === PConst.Kind.warning)
- || (!completionConfiguration.paths &&
- (element.kind === PConst.Kind.directory || element.kind === PConst.Kind.script || element.kind === PConst.Kind.externalModuleName))
- || (!completionConfiguration.autoImports && element.hasAction));
- }
- function appendJoinedPlaceholders(snippet, parts, joiner) {
- for (let i = 0; i < parts.length; ++i) {
- const paramterPart = parts[i];
- snippet.appendPlaceholder(paramterPart.text);
- if (i !== parts.length - 1) {
- snippet.appendText(joiner);
- }
- }
- }
-
-
- /***/ }),
- /* 39 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.DisplayPartKind = exports.KindModifiers = exports.DiagnosticCategory = exports.Kind = void 0;
- class Kind {
- }
- exports.Kind = Kind;
- Kind.alias = 'alias';
- Kind.callSignature = 'call';
- Kind.class = 'class';
- Kind.const = 'const';
- Kind.constructorImplementation = 'constructor';
- Kind.constructSignature = 'construct';
- Kind.directory = 'directory';
- Kind.enum = 'enum';
- Kind.enumMember = 'enum member';
- Kind.externalModuleName = 'external module name';
- Kind.function = 'function';
- Kind.indexSignature = 'index';
- Kind.interface = 'interface';
- Kind.keyword = 'keyword';
- Kind.let = 'let';
- Kind.localFunction = 'local function';
- Kind.localVariable = 'local var';
- Kind.method = 'method';
- Kind.memberGetAccessor = 'getter';
- Kind.memberSetAccessor = 'setter';
- Kind.memberVariable = 'property';
- Kind.module = 'module';
- Kind.primitiveType = 'primitive type';
- Kind.script = 'script';
- Kind.type = 'type';
- Kind.variable = 'var';
- Kind.warning = 'warning';
- Kind.string = 'string';
- Kind.parameter = 'parameter';
- Kind.typeParameter = 'type parameter';
- class DiagnosticCategory {
- }
- exports.DiagnosticCategory = DiagnosticCategory;
- DiagnosticCategory.error = 'error';
- DiagnosticCategory.warning = 'warning';
- DiagnosticCategory.suggestion = 'suggestion';
- class KindModifiers {
- }
- exports.KindModifiers = KindModifiers;
- KindModifiers.optional = 'optional';
- KindModifiers.color = 'color';
- KindModifiers.dtsFile = '.d.ts';
- KindModifiers.tsFile = '.ts';
- KindModifiers.tsxFile = '.tsx';
- KindModifiers.jsFile = '.js';
- KindModifiers.jsxFile = '.jsx';
- KindModifiers.jsonFile = '.json';
- KindModifiers.fileExtensionKindModifiers = [
- KindModifiers.dtsFile,
- KindModifiers.tsFile,
- KindModifiers.tsxFile,
- KindModifiers.jsFile,
- KindModifiers.jsxFile,
- KindModifiers.jsonFile,
- ];
- class DisplayPartKind {
- }
- exports.DisplayPartKind = DisplayPartKind;
- DisplayPartKind.functionName = 'functionName';
- DisplayPartKind.methodName = 'methodName';
- DisplayPartKind.parameterName = 'parameterName';
- DisplayPartKind.propertyName = 'propertyName';
- DisplayPartKind.punctuation = 'punctuation';
- DisplayPartKind.text = 'text';
-
-
- /***/ }),
- /* 40 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const semver = __importStar(__webpack_require__(41));
- class API {
- constructor(versionString, version) {
- this.versionString = versionString;
- this.version = version;
- }
- static fromSimpleString(value) {
- return new API(value, value);
- }
- static fromVersionString(versionString) {
- let version = semver.valid(versionString);
- if (!version) {
- return new API('invalid version', '1.0.0');
- }
- // Cut off any prerelease tag since we sometimes consume those on purpose.
- const index = versionString.indexOf('-');
- if (index >= 0) {
- version = version.substr(0, index);
- }
- return new API(versionString, version);
- }
- gte(other) {
- return semver.gte(this.version, other.version);
- }
- lt(other) {
- return !this.gte(other);
- }
- }
- exports.default = API;
- API.defaultVersion = API.fromSimpleString('1.0.0');
- API.v203 = API.fromSimpleString('2.0.3');
- API.v206 = API.fromSimpleString('2.0.6');
- API.v208 = API.fromSimpleString('2.0.8');
- API.v213 = API.fromSimpleString('2.1.3');
- API.v220 = API.fromSimpleString('2.2.0');
- API.v222 = API.fromSimpleString('2.2.2');
- API.v230 = API.fromSimpleString('2.3.0');
- API.v234 = API.fromSimpleString('2.3.4');
- API.v240 = API.fromSimpleString('2.4.0');
- API.v250 = API.fromSimpleString('2.5.0');
- API.v260 = API.fromSimpleString('2.6.0');
- API.v270 = API.fromSimpleString('2.7.0');
- API.v280 = API.fromSimpleString('2.8.0');
- API.v290 = API.fromSimpleString('2.9.0');
- API.v291 = API.fromSimpleString('2.9.1');
- API.v292 = API.fromSimpleString('2.9.2');
- API.v300 = API.fromSimpleString('3.0.0');
- API.v310 = API.fromSimpleString('3.1.0');
- API.v314 = API.fromSimpleString('3.1.4');
- API.v320 = API.fromSimpleString('3.2.0');
- API.v330 = API.fromSimpleString('3.3.0');
- API.v333 = API.fromSimpleString('3.3.3');
- API.v340 = API.fromSimpleString('3.4.0');
- API.v345 = API.fromSimpleString('3.4.5');
- API.v350 = API.fromSimpleString('3.5.0');
- API.v380 = API.fromSimpleString('3.8.0');
- API.v381 = API.fromSimpleString('3.8.1');
- API.v390 = API.fromSimpleString('3.9.0');
-
-
- /***/ }),
- /* 41 */
- /***/ (function(module, exports, __webpack_require__) {
-
- // just pre-load all the stuff that index.js lazily exports
- const internalRe = __webpack_require__(42)
- module.exports = {
- re: internalRe.re,
- src: internalRe.src,
- tokens: internalRe.t,
- SEMVER_SPEC_VERSION: __webpack_require__(43).SEMVER_SPEC_VERSION,
- SemVer: __webpack_require__(45),
- compareIdentifiers: __webpack_require__(46).compareIdentifiers,
- rcompareIdentifiers: __webpack_require__(46).rcompareIdentifiers,
- parse: __webpack_require__(47),
- valid: __webpack_require__(48),
- clean: __webpack_require__(49),
- inc: __webpack_require__(50),
- diff: __webpack_require__(51),
- major: __webpack_require__(54),
- minor: __webpack_require__(55),
- patch: __webpack_require__(56),
- prerelease: __webpack_require__(57),
- compare: __webpack_require__(53),
- rcompare: __webpack_require__(58),
- compareLoose: __webpack_require__(59),
- compareBuild: __webpack_require__(60),
- sort: __webpack_require__(61),
- rsort: __webpack_require__(62),
- gt: __webpack_require__(63),
- lt: __webpack_require__(64),
- eq: __webpack_require__(52),
- neq: __webpack_require__(65),
- gte: __webpack_require__(66),
- lte: __webpack_require__(67),
- cmp: __webpack_require__(68),
- coerce: __webpack_require__(69),
- Comparator: __webpack_require__(70),
- Range: __webpack_require__(71),
- satisfies: __webpack_require__(72),
- toComparators: __webpack_require__(73),
- maxSatisfying: __webpack_require__(74),
- minSatisfying: __webpack_require__(75),
- minVersion: __webpack_require__(76),
- validRange: __webpack_require__(77),
- outside: __webpack_require__(78),
- gtr: __webpack_require__(79),
- ltr: __webpack_require__(80),
- intersects: __webpack_require__(81),
- simplifyRange: __webpack_require__(82),
- subset: __webpack_require__(83),
- }
-
-
- /***/ }),
- /* 42 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const { MAX_SAFE_COMPONENT_LENGTH } = __webpack_require__(43)
- const debug = __webpack_require__(44)
- exports = module.exports = {}
-
- // The actual regexps go on exports.re
- const re = exports.re = []
- const src = exports.src = []
- const t = exports.t = {}
- let R = 0
-
- const createToken = (name, value, isGlobal) => {
- const index = R++
- debug(index, value)
- t[name] = index
- src[index] = value
- re[index] = new RegExp(value, isGlobal ? 'g' : undefined)
- }
-
- // The following Regular Expressions can be used for tokenizing,
- // validating, and parsing SemVer version strings.
-
- // ## Numeric Identifier
- // A single `0`, or a non-zero digit followed by zero or more digits.
-
- createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*')
- createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+')
-
- // ## Non-numeric Identifier
- // Zero or more digits, followed by a letter or hyphen, and then zero or
- // more letters, digits, or hyphens.
-
- createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*')
-
- // ## Main Version
- // Three dot-separated numeric identifiers.
-
- createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
- `(${src[t.NUMERICIDENTIFIER]})\\.` +
- `(${src[t.NUMERICIDENTIFIER]})`)
-
- createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
- `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
- `(${src[t.NUMERICIDENTIFIERLOOSE]})`)
-
- // ## Pre-release Version Identifier
- // A numeric identifier, or a non-numeric identifier.
-
- createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]
- }|${src[t.NONNUMERICIDENTIFIER]})`)
-
- createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]
- }|${src[t.NONNUMERICIDENTIFIER]})`)
-
- // ## Pre-release Version
- // Hyphen, followed by one or more dot-separated pre-release version
- // identifiers.
-
- createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
- }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`)
-
- createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
- }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)
-
- // ## Build Metadata Identifier
- // Any combination of digits, letters, or hyphens.
-
- createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+')
-
- // ## Build Metadata
- // Plus sign, followed by one or more period-separated build metadata
- // identifiers.
-
- createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
- }(?:\\.${src[t.BUILDIDENTIFIER]})*))`)
-
- // ## Full Version String
- // A main version, followed optionally by a pre-release version and
- // build metadata.
-
- // Note that the only major, minor, patch, and pre-release sections of
- // the version string are capturing groups. The build metadata is not a
- // capturing group, because it should not ever be used in version
- // comparison.
-
- createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
- }${src[t.PRERELEASE]}?${
- src[t.BUILD]}?`)
-
- createToken('FULL', `^${src[t.FULLPLAIN]}$`)
-
- // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
- // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
- // common in the npm registry.
- createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
- }${src[t.PRERELEASELOOSE]}?${
- src[t.BUILD]}?`)
-
- createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)
-
- createToken('GTLT', '((?:<|>)?=?)')
-
- // Something like "2.*" or "1.2.x".
- // Note that "x.x" is a valid xRange identifer, meaning "any version"
- // Only the first item is strictly required.
- createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`)
- createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`)
-
- createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
- `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
- `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
- `(?:${src[t.PRERELEASE]})?${
- src[t.BUILD]}?` +
- `)?)?`)
-
- createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
- `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
- `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
- `(?:${src[t.PRERELEASELOOSE]})?${
- src[t.BUILD]}?` +
- `)?)?`)
-
- createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`)
- createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`)
-
- // Coercion.
- // Extract anything that could conceivably be a part of a valid semver
- createToken('COERCE', `${'(^|[^\\d])' +
- '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
- `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
- `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
- `(?:$|[^\\d])`)
- createToken('COERCERTL', src[t.COERCE], true)
-
- // Tilde ranges.
- // Meaning is "reasonably at or greater than"
- createToken('LONETILDE', '(?:~>?)')
-
- createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true)
- exports.tildeTrimReplace = '$1~'
-
- createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)
- createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)
-
- // Caret ranges.
- // Meaning is "at least and backwards compatible with"
- createToken('LONECARET', '(?:\\^)')
-
- createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true)
- exports.caretTrimReplace = '$1^'
-
- createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)
- createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)
-
- // A simple gt/lt/eq thing, or just "" to indicate "any version"
- createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`)
- createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`)
-
- // An expression to strip any whitespace between the gtlt and the thing
- // it modifies, so that `> 1.2.3` ==> `>1.2.3`
- createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
- }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)
- exports.comparatorTrimReplace = '$1$2$3'
-
- // Something like `1.2.3 - 1.2.4`
- // Note that these all use the loose form, because they'll be
- // checked against either the strict or loose comparator form
- // later.
- createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
- `\\s+-\\s+` +
- `(${src[t.XRANGEPLAIN]})` +
- `\\s*$`)
-
- createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
- `\\s+-\\s+` +
- `(${src[t.XRANGEPLAINLOOSE]})` +
- `\\s*$`)
-
- // Star ranges basically just allow anything at all.
- createToken('STAR', '(<|>)?=?\\s*\\*')
- // >=0.0.0 is like a star
- createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$')
- createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$')
-
-
- /***/ }),
- /* 43 */
- /***/ (function(module, exports) {
-
- // Note: this is the semver.org version of the spec that it implements
- // Not necessarily the package version of this code.
- const SEMVER_SPEC_VERSION = '2.0.0'
-
- const MAX_LENGTH = 256
- const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
- /* istanbul ignore next */ 9007199254740991
-
- // Max safe segment length for coercion.
- const MAX_SAFE_COMPONENT_LENGTH = 16
-
- module.exports = {
- SEMVER_SPEC_VERSION,
- MAX_LENGTH,
- MAX_SAFE_INTEGER,
- MAX_SAFE_COMPONENT_LENGTH
- }
-
-
- /***/ }),
- /* 44 */
- /***/ (function(module, exports) {
-
- const debug = (
- typeof process === 'object' &&
- process.env &&
- process.env.NODE_DEBUG &&
- /\bsemver\b/i.test(process.env.NODE_DEBUG)
- ) ? (...args) => console.error('SEMVER', ...args)
- : () => {}
-
- module.exports = debug
-
-
- /***/ }),
- /* 45 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const debug = __webpack_require__(44)
- const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(43)
- const { re, t } = __webpack_require__(42)
-
- const { compareIdentifiers } = __webpack_require__(46)
- class SemVer {
- constructor (version, options) {
- if (!options || typeof options !== 'object') {
- options = {
- loose: !!options,
- includePrerelease: false
- }
- }
- if (version instanceof SemVer) {
- if (version.loose === !!options.loose &&
- version.includePrerelease === !!options.includePrerelease) {
- return version
- } else {
- version = version.version
- }
- } else if (typeof version !== 'string') {
- throw new TypeError(`Invalid Version: ${version}`)
- }
-
- if (version.length > MAX_LENGTH) {
- throw new TypeError(
- `version is longer than ${MAX_LENGTH} characters`
- )
- }
-
- debug('SemVer', version, options)
- this.options = options
- this.loose = !!options.loose
- // this isn't actually relevant for versions, but keep it so that we
- // don't run into trouble passing this.options around.
- this.includePrerelease = !!options.includePrerelease
-
- const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])
-
- if (!m) {
- throw new TypeError(`Invalid Version: ${version}`)
- }
-
- this.raw = version
-
- // these are actually numbers
- this.major = +m[1]
- this.minor = +m[2]
- this.patch = +m[3]
-
- if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
- throw new TypeError('Invalid major version')
- }
-
- if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
- throw new TypeError('Invalid minor version')
- }
-
- if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
- throw new TypeError('Invalid patch version')
- }
-
- // numberify any prerelease numeric ids
- if (!m[4]) {
- this.prerelease = []
- } else {
- this.prerelease = m[4].split('.').map((id) => {
- if (/^[0-9]+$/.test(id)) {
- const num = +id
- if (num >= 0 && num < MAX_SAFE_INTEGER) {
- return num
- }
- }
- return id
- })
- }
-
- this.build = m[5] ? m[5].split('.') : []
- this.format()
- }
-
- format () {
- this.version = `${this.major}.${this.minor}.${this.patch}`
- if (this.prerelease.length) {
- this.version += `-${this.prerelease.join('.')}`
- }
- return this.version
- }
-
- toString () {
- return this.version
- }
-
- compare (other) {
- debug('SemVer.compare', this.version, this.options, other)
- if (!(other instanceof SemVer)) {
- if (typeof other === 'string' && other === this.version) {
- return 0
- }
- other = new SemVer(other, this.options)
- }
-
- if (other.version === this.version) {
- return 0
- }
-
- return this.compareMain(other) || this.comparePre(other)
- }
-
- compareMain (other) {
- if (!(other instanceof SemVer)) {
- other = new SemVer(other, this.options)
- }
-
- return (
- compareIdentifiers(this.major, other.major) ||
- compareIdentifiers(this.minor, other.minor) ||
- compareIdentifiers(this.patch, other.patch)
- )
- }
-
- comparePre (other) {
- if (!(other instanceof SemVer)) {
- other = new SemVer(other, this.options)
- }
-
- // NOT having a prerelease is > having one
- if (this.prerelease.length && !other.prerelease.length) {
- return -1
- } else if (!this.prerelease.length && other.prerelease.length) {
- return 1
- } else if (!this.prerelease.length && !other.prerelease.length) {
- return 0
- }
-
- let i = 0
- do {
- const a = this.prerelease[i]
- const b = other.prerelease[i]
- debug('prerelease compare', i, a, b)
- if (a === undefined && b === undefined) {
- return 0
- } else if (b === undefined) {
- return 1
- } else if (a === undefined) {
- return -1
- } else if (a === b) {
- continue
- } else {
- return compareIdentifiers(a, b)
- }
- } while (++i)
- }
-
- compareBuild (other) {
- if (!(other instanceof SemVer)) {
- other = new SemVer(other, this.options)
- }
-
- let i = 0
- do {
- const a = this.build[i]
- const b = other.build[i]
- debug('prerelease compare', i, a, b)
- if (a === undefined && b === undefined) {
- return 0
- } else if (b === undefined) {
- return 1
- } else if (a === undefined) {
- return -1
- } else if (a === b) {
- continue
- } else {
- return compareIdentifiers(a, b)
- }
- } while (++i)
- }
-
- // preminor will bump the version up to the next minor release, and immediately
- // down to pre-release. premajor and prepatch work the same way.
- inc (release, identifier) {
- switch (release) {
- case 'premajor':
- this.prerelease.length = 0
- this.patch = 0
- this.minor = 0
- this.major++
- this.inc('pre', identifier)
- break
- case 'preminor':
- this.prerelease.length = 0
- this.patch = 0
- this.minor++
- this.inc('pre', identifier)
- break
- case 'prepatch':
- // If this is already a prerelease, it will bump to the next version
- // drop any prereleases that might already exist, since they are not
- // relevant at this point.
- this.prerelease.length = 0
- this.inc('patch', identifier)
- this.inc('pre', identifier)
- break
- // If the input is a non-prerelease version, this acts the same as
- // prepatch.
- case 'prerelease':
- if (this.prerelease.length === 0) {
- this.inc('patch', identifier)
- }
- this.inc('pre', identifier)
- break
-
- case 'major':
- // If this is a pre-major version, bump up to the same major version.
- // Otherwise increment major.
- // 1.0.0-5 bumps to 1.0.0
- // 1.1.0 bumps to 2.0.0
- if (
- this.minor !== 0 ||
- this.patch !== 0 ||
- this.prerelease.length === 0
- ) {
- this.major++
- }
- this.minor = 0
- this.patch = 0
- this.prerelease = []
- break
- case 'minor':
- // If this is a pre-minor version, bump up to the same minor version.
- // Otherwise increment minor.
- // 1.2.0-5 bumps to 1.2.0
- // 1.2.1 bumps to 1.3.0
- if (this.patch !== 0 || this.prerelease.length === 0) {
- this.minor++
- }
- this.patch = 0
- this.prerelease = []
- break
- case 'patch':
- // If this is not a pre-release version, it will increment the patch.
- // If it is a pre-release it will bump up to the same patch version.
- // 1.2.0-5 patches to 1.2.0
- // 1.2.0 patches to 1.2.1
- if (this.prerelease.length === 0) {
- this.patch++
- }
- this.prerelease = []
- break
- // This probably shouldn't be used publicly.
- // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
- case 'pre':
- if (this.prerelease.length === 0) {
- this.prerelease = [0]
- } else {
- let i = this.prerelease.length
- while (--i >= 0) {
- if (typeof this.prerelease[i] === 'number') {
- this.prerelease[i]++
- i = -2
- }
- }
- if (i === -1) {
- // didn't increment anything
- this.prerelease.push(0)
- }
- }
- if (identifier) {
- // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
- // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
- if (this.prerelease[0] === identifier) {
- if (isNaN(this.prerelease[1])) {
- this.prerelease = [identifier, 0]
- }
- } else {
- this.prerelease = [identifier, 0]
- }
- }
- break
-
- default:
- throw new Error(`invalid increment argument: ${release}`)
- }
- this.format()
- this.raw = this.version
- return this
- }
- }
-
- module.exports = SemVer
-
-
- /***/ }),
- /* 46 */
- /***/ (function(module, exports) {
-
- const numeric = /^[0-9]+$/
- const compareIdentifiers = (a, b) => {
- const anum = numeric.test(a)
- const bnum = numeric.test(b)
-
- if (anum && bnum) {
- a = +a
- b = +b
- }
-
- return a === b ? 0
- : (anum && !bnum) ? -1
- : (bnum && !anum) ? 1
- : a < b ? -1
- : 1
- }
-
- const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)
-
- module.exports = {
- compareIdentifiers,
- rcompareIdentifiers
- }
-
-
- /***/ }),
- /* 47 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const {MAX_LENGTH} = __webpack_require__(43)
- const { re, t } = __webpack_require__(42)
- const SemVer = __webpack_require__(45)
-
- const parse = (version, options) => {
- if (!options || typeof options !== 'object') {
- options = {
- loose: !!options,
- includePrerelease: false
- }
- }
-
- if (version instanceof SemVer) {
- return version
- }
-
- if (typeof version !== 'string') {
- return null
- }
-
- if (version.length > MAX_LENGTH) {
- return null
- }
-
- const r = options.loose ? re[t.LOOSE] : re[t.FULL]
- if (!r.test(version)) {
- return null
- }
-
- try {
- return new SemVer(version, options)
- } catch (er) {
- return null
- }
- }
-
- module.exports = parse
-
-
- /***/ }),
- /* 48 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const parse = __webpack_require__(47)
- const valid = (version, options) => {
- const v = parse(version, options)
- return v ? v.version : null
- }
- module.exports = valid
-
-
- /***/ }),
- /* 49 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const parse = __webpack_require__(47)
- const clean = (version, options) => {
- const s = parse(version.trim().replace(/^[=v]+/, ''), options)
- return s ? s.version : null
- }
- module.exports = clean
-
-
- /***/ }),
- /* 50 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const SemVer = __webpack_require__(45)
-
- const inc = (version, release, options, identifier) => {
- if (typeof (options) === 'string') {
- identifier = options
- options = undefined
- }
-
- try {
- return new SemVer(version, options).inc(release, identifier).version
- } catch (er) {
- return null
- }
- }
- module.exports = inc
-
-
- /***/ }),
- /* 51 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const parse = __webpack_require__(47)
- const eq = __webpack_require__(52)
-
- const diff = (version1, version2) => {
- if (eq(version1, version2)) {
- return null
- } else {
- const v1 = parse(version1)
- const v2 = parse(version2)
- const hasPre = v1.prerelease.length || v2.prerelease.length
- const prefix = hasPre ? 'pre' : ''
- const defaultResult = hasPre ? 'prerelease' : ''
- for (const key in v1) {
- if (key === 'major' || key === 'minor' || key === 'patch') {
- if (v1[key] !== v2[key]) {
- return prefix + key
- }
- }
- }
- return defaultResult // may be undefined
- }
- }
- module.exports = diff
-
-
- /***/ }),
- /* 52 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const compare = __webpack_require__(53)
- const eq = (a, b, loose) => compare(a, b, loose) === 0
- module.exports = eq
-
-
- /***/ }),
- /* 53 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const SemVer = __webpack_require__(45)
- const compare = (a, b, loose) =>
- new SemVer(a, loose).compare(new SemVer(b, loose))
-
- module.exports = compare
-
-
- /***/ }),
- /* 54 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const SemVer = __webpack_require__(45)
- const major = (a, loose) => new SemVer(a, loose).major
- module.exports = major
-
-
- /***/ }),
- /* 55 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const SemVer = __webpack_require__(45)
- const minor = (a, loose) => new SemVer(a, loose).minor
- module.exports = minor
-
-
- /***/ }),
- /* 56 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const SemVer = __webpack_require__(45)
- const patch = (a, loose) => new SemVer(a, loose).patch
- module.exports = patch
-
-
- /***/ }),
- /* 57 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const parse = __webpack_require__(47)
- const prerelease = (version, options) => {
- const parsed = parse(version, options)
- return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
- }
- module.exports = prerelease
-
-
- /***/ }),
- /* 58 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const compare = __webpack_require__(53)
- const rcompare = (a, b, loose) => compare(b, a, loose)
- module.exports = rcompare
-
-
- /***/ }),
- /* 59 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const compare = __webpack_require__(53)
- const compareLoose = (a, b) => compare(a, b, true)
- module.exports = compareLoose
-
-
- /***/ }),
- /* 60 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const SemVer = __webpack_require__(45)
- const compareBuild = (a, b, loose) => {
- const versionA = new SemVer(a, loose)
- const versionB = new SemVer(b, loose)
- return versionA.compare(versionB) || versionA.compareBuild(versionB)
- }
- module.exports = compareBuild
-
-
- /***/ }),
- /* 61 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const compareBuild = __webpack_require__(60)
- const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))
- module.exports = sort
-
-
- /***/ }),
- /* 62 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const compareBuild = __webpack_require__(60)
- const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))
- module.exports = rsort
-
-
- /***/ }),
- /* 63 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const compare = __webpack_require__(53)
- const gt = (a, b, loose) => compare(a, b, loose) > 0
- module.exports = gt
-
-
- /***/ }),
- /* 64 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const compare = __webpack_require__(53)
- const lt = (a, b, loose) => compare(a, b, loose) < 0
- module.exports = lt
-
-
- /***/ }),
- /* 65 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const compare = __webpack_require__(53)
- const neq = (a, b, loose) => compare(a, b, loose) !== 0
- module.exports = neq
-
-
- /***/ }),
- /* 66 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const compare = __webpack_require__(53)
- const gte = (a, b, loose) => compare(a, b, loose) >= 0
- module.exports = gte
-
-
- /***/ }),
- /* 67 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const compare = __webpack_require__(53)
- const lte = (a, b, loose) => compare(a, b, loose) <= 0
- module.exports = lte
-
-
- /***/ }),
- /* 68 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const eq = __webpack_require__(52)
- const neq = __webpack_require__(65)
- const gt = __webpack_require__(63)
- const gte = __webpack_require__(66)
- const lt = __webpack_require__(64)
- const lte = __webpack_require__(67)
-
- const cmp = (a, op, b, loose) => {
- switch (op) {
- case '===':
- if (typeof a === 'object')
- a = a.version
- if (typeof b === 'object')
- b = b.version
- return a === b
-
- case '!==':
- if (typeof a === 'object')
- a = a.version
- if (typeof b === 'object')
- b = b.version
- return a !== b
-
- case '':
- case '=':
- case '==':
- return eq(a, b, loose)
-
- case '!=':
- return neq(a, b, loose)
-
- case '>':
- return gt(a, b, loose)
-
- case '>=':
- return gte(a, b, loose)
-
- case '<':
- return lt(a, b, loose)
-
- case '<=':
- return lte(a, b, loose)
-
- default:
- throw new TypeError(`Invalid operator: ${op}`)
- }
- }
- module.exports = cmp
-
-
- /***/ }),
- /* 69 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const SemVer = __webpack_require__(45)
- const parse = __webpack_require__(47)
- const {re, t} = __webpack_require__(42)
-
- const coerce = (version, options) => {
- if (version instanceof SemVer) {
- return version
- }
-
- if (typeof version === 'number') {
- version = String(version)
- }
-
- if (typeof version !== 'string') {
- return null
- }
-
- options = options || {}
-
- let match = null
- if (!options.rtl) {
- match = version.match(re[t.COERCE])
- } else {
- // Find the right-most coercible string that does not share
- // a terminus with a more left-ward coercible string.
- // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
- //
- // Walk through the string checking with a /g regexp
- // Manually set the index so as to pick up overlapping matches.
- // Stop when we get a match that ends at the string end, since no
- // coercible string can be more right-ward without the same terminus.
- let next
- while ((next = re[t.COERCERTL].exec(version)) &&
- (!match || match.index + match[0].length !== version.length)
- ) {
- if (!match ||
- next.index + next[0].length !== match.index + match[0].length) {
- match = next
- }
- re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length
- }
- // leave it in a clean state
- re[t.COERCERTL].lastIndex = -1
- }
-
- if (match === null)
- return null
-
- return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options)
- }
- module.exports = coerce
-
-
- /***/ }),
- /* 70 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const ANY = Symbol('SemVer ANY')
- // hoisted class for cyclic dependency
- class Comparator {
- static get ANY () {
- return ANY
- }
- constructor (comp, options) {
- if (!options || typeof options !== 'object') {
- options = {
- loose: !!options,
- includePrerelease: false
- }
- }
-
- if (comp instanceof Comparator) {
- if (comp.loose === !!options.loose) {
- return comp
- } else {
- comp = comp.value
- }
- }
-
- debug('comparator', comp, options)
- this.options = options
- this.loose = !!options.loose
- this.parse(comp)
-
- if (this.semver === ANY) {
- this.value = ''
- } else {
- this.value = this.operator + this.semver.version
- }
-
- debug('comp', this)
- }
-
- parse (comp) {
- const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
- const m = comp.match(r)
-
- if (!m) {
- throw new TypeError(`Invalid comparator: ${comp}`)
- }
-
- this.operator = m[1] !== undefined ? m[1] : ''
- if (this.operator === '=') {
- this.operator = ''
- }
-
- // if it literally is just '>' or '' then allow anything.
- if (!m[2]) {
- this.semver = ANY
- } else {
- this.semver = new SemVer(m[2], this.options.loose)
- }
- }
-
- toString () {
- return this.value
- }
-
- test (version) {
- debug('Comparator.test', version, this.options.loose)
-
- if (this.semver === ANY || version === ANY) {
- return true
- }
-
- if (typeof version === 'string') {
- try {
- version = new SemVer(version, this.options)
- } catch (er) {
- return false
- }
- }
-
- return cmp(version, this.operator, this.semver, this.options)
- }
-
- intersects (comp, options) {
- if (!(comp instanceof Comparator)) {
- throw new TypeError('a Comparator is required')
- }
-
- if (!options || typeof options !== 'object') {
- options = {
- loose: !!options,
- includePrerelease: false
- }
- }
-
- if (this.operator === '') {
- if (this.value === '') {
- return true
- }
- return new Range(comp.value, options).test(this.value)
- } else if (comp.operator === '') {
- if (comp.value === '') {
- return true
- }
- return new Range(this.value, options).test(comp.semver)
- }
-
- const sameDirectionIncreasing =
- (this.operator === '>=' || this.operator === '>') &&
- (comp.operator === '>=' || comp.operator === '>')
- const sameDirectionDecreasing =
- (this.operator === '<=' || this.operator === '<') &&
- (comp.operator === '<=' || comp.operator === '<')
- const sameSemVer = this.semver.version === comp.semver.version
- const differentDirectionsInclusive =
- (this.operator === '>=' || this.operator === '<=') &&
- (comp.operator === '>=' || comp.operator === '<=')
- const oppositeDirectionsLessThan =
- cmp(this.semver, '<', comp.semver, options) &&
- (this.operator === '>=' || this.operator === '>') &&
- (comp.operator === '<=' || comp.operator === '<')
- const oppositeDirectionsGreaterThan =
- cmp(this.semver, '>', comp.semver, options) &&
- (this.operator === '<=' || this.operator === '<') &&
- (comp.operator === '>=' || comp.operator === '>')
-
- return (
- sameDirectionIncreasing ||
- sameDirectionDecreasing ||
- (sameSemVer && differentDirectionsInclusive) ||
- oppositeDirectionsLessThan ||
- oppositeDirectionsGreaterThan
- )
- }
- }
-
- module.exports = Comparator
-
- const {re, t} = __webpack_require__(42)
- const cmp = __webpack_require__(68)
- const debug = __webpack_require__(44)
- const SemVer = __webpack_require__(45)
- const Range = __webpack_require__(71)
-
-
- /***/ }),
- /* 71 */
- /***/ (function(module, exports, __webpack_require__) {
-
- // hoisted class for cyclic dependency
- class Range {
- constructor (range, options) {
- if (!options || typeof options !== 'object') {
- options = {
- loose: !!options,
- includePrerelease: false
- }
- }
-
- if (range instanceof Range) {
- if (
- range.loose === !!options.loose &&
- range.includePrerelease === !!options.includePrerelease
- ) {
- return range
- } else {
- return new Range(range.raw, options)
- }
- }
-
- if (range instanceof Comparator) {
- // just put it in the set and return
- this.raw = range.value
- this.set = [[range]]
- this.format()
- return this
- }
-
- this.options = options
- this.loose = !!options.loose
- this.includePrerelease = !!options.includePrerelease
-
- // First, split based on boolean or ||
- this.raw = range
- this.set = range
- .split(/\s*\|\|\s*/)
- // map the range to a 2d array of comparators
- .map(range => this.parseRange(range.trim()))
- // throw out any comparator lists that are empty
- // this generally means that it was not a valid range, which is allowed
- // in loose mode, but will still throw if the WHOLE range is invalid.
- .filter(c => c.length)
-
- if (!this.set.length) {
- throw new TypeError(`Invalid SemVer Range: ${range}`)
- }
-
- this.format()
- }
-
- format () {
- this.range = this.set
- .map((comps) => {
- return comps.join(' ').trim()
- })
- .join('||')
- .trim()
- return this.range
- }
-
- toString () {
- return this.range
- }
-
- parseRange (range) {
- const loose = this.options.loose
- range = range.trim()
- // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
- const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]
- range = range.replace(hr, hyphenReplace(this.options.includePrerelease))
- debug('hyphen replace', range)
- // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
- range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)
- debug('comparator trim', range, re[t.COMPARATORTRIM])
-
- // `~ 1.2.3` => `~1.2.3`
- range = range.replace(re[t.TILDETRIM], tildeTrimReplace)
-
- // `^ 1.2.3` => `^1.2.3`
- range = range.replace(re[t.CARETTRIM], caretTrimReplace)
-
- // normalize spaces
- range = range.split(/\s+/).join(' ')
-
- // At this point, the range is completely trimmed and
- // ready to be split into comparators.
-
- const compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
- return range
- .split(' ')
- .map(comp => parseComparator(comp, this.options))
- .join(' ')
- .split(/\s+/)
- .map(comp => replaceGTE0(comp, this.options))
- // in loose mode, throw out any that are not valid comparators
- .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true)
- .map(comp => new Comparator(comp, this.options))
- }
-
- intersects (range, options) {
- if (!(range instanceof Range)) {
- throw new TypeError('a Range is required')
- }
-
- return this.set.some((thisComparators) => {
- return (
- isSatisfiable(thisComparators, options) &&
- range.set.some((rangeComparators) => {
- return (
- isSatisfiable(rangeComparators, options) &&
- thisComparators.every((thisComparator) => {
- return rangeComparators.every((rangeComparator) => {
- return thisComparator.intersects(rangeComparator, options)
- })
- })
- )
- })
- )
- })
- }
-
- // if ANY of the sets match ALL of its comparators, then pass
- test (version) {
- if (!version) {
- return false
- }
-
- if (typeof version === 'string') {
- try {
- version = new SemVer(version, this.options)
- } catch (er) {
- return false
- }
- }
-
- for (let i = 0; i < this.set.length; i++) {
- if (testSet(this.set[i], version, this.options)) {
- return true
- }
- }
- return false
- }
- }
- module.exports = Range
-
- const Comparator = __webpack_require__(70)
- const debug = __webpack_require__(44)
- const SemVer = __webpack_require__(45)
- const {
- re,
- t,
- comparatorTrimReplace,
- tildeTrimReplace,
- caretTrimReplace
- } = __webpack_require__(42)
-
- // take a set of comparators and determine whether there
- // exists a version which can satisfy it
- const isSatisfiable = (comparators, options) => {
- let result = true
- const remainingComparators = comparators.slice()
- let testComparator = remainingComparators.pop()
-
- while (result && remainingComparators.length) {
- result = remainingComparators.every((otherComparator) => {
- return testComparator.intersects(otherComparator, options)
- })
-
- testComparator = remainingComparators.pop()
- }
-
- return result
- }
-
- // comprised of xranges, tildes, stars, and gtlt's at this point.
- // already replaced the hyphen ranges
- // turn into a set of JUST comparators.
- const parseComparator = (comp, options) => {
- debug('comp', comp, options)
- comp = replaceCarets(comp, options)
- debug('caret', comp)
- comp = replaceTildes(comp, options)
- debug('tildes', comp)
- comp = replaceXRanges(comp, options)
- debug('xrange', comp)
- comp = replaceStars(comp, options)
- debug('stars', comp)
- return comp
- }
-
- const isX = id => !id || id.toLowerCase() === 'x' || id === '*'
-
- // ~, ~> --> * (any, kinda silly)
- // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
- // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
- // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
- // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
- // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
- const replaceTildes = (comp, options) =>
- comp.trim().split(/\s+/).map((comp) => {
- return replaceTilde(comp, options)
- }).join(' ')
-
- const replaceTilde = (comp, options) => {
- const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]
- return comp.replace(r, (_, M, m, p, pr) => {
- debug('tilde', comp, _, M, m, p, pr)
- let ret
-
- if (isX(M)) {
- ret = ''
- } else if (isX(m)) {
- ret = `>=${M}.0.0 <${+M + 1}.0.0-0`
- } else if (isX(p)) {
- // ~1.2 == >=1.2.0 <1.3.0-0
- ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`
- } else if (pr) {
- debug('replaceTilde pr', pr)
- ret = `>=${M}.${m}.${p}-${pr
- } <${M}.${+m + 1}.0-0`
- } else {
- // ~1.2.3 == >=1.2.3 <1.3.0-0
- ret = `>=${M}.${m}.${p
- } <${M}.${+m + 1}.0-0`
- }
-
- debug('tilde return', ret)
- return ret
- })
- }
-
- // ^ --> * (any, kinda silly)
- // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
- // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
- // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
- // ^1.2.3 --> >=1.2.3 <2.0.0-0
- // ^1.2.0 --> >=1.2.0 <2.0.0-0
- const replaceCarets = (comp, options) =>
- comp.trim().split(/\s+/).map((comp) => {
- return replaceCaret(comp, options)
- }).join(' ')
-
- const replaceCaret = (comp, options) => {
- debug('caret', comp, options)
- const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]
- const z = options.includePrerelease ? '-0' : ''
- return comp.replace(r, (_, M, m, p, pr) => {
- debug('caret', comp, _, M, m, p, pr)
- let ret
-
- if (isX(M)) {
- ret = ''
- } else if (isX(m)) {
- ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`
- } else if (isX(p)) {
- if (M === '0') {
- ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`
- } else {
- ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`
- }
- } else if (pr) {
- debug('replaceCaret pr', pr)
- if (M === '0') {
- if (m === '0') {
- ret = `>=${M}.${m}.${p}-${pr
- } <${M}.${m}.${+p + 1}-0`
- } else {
- ret = `>=${M}.${m}.${p}-${pr
- } <${M}.${+m + 1}.0-0`
- }
- } else {
- ret = `>=${M}.${m}.${p}-${pr
- } <${+M + 1}.0.0-0`
- }
- } else {
- debug('no pr')
- if (M === '0') {
- if (m === '0') {
- ret = `>=${M}.${m}.${p
- }${z} <${M}.${m}.${+p + 1}-0`
- } else {
- ret = `>=${M}.${m}.${p
- }${z} <${M}.${+m + 1}.0-0`
- }
- } else {
- ret = `>=${M}.${m}.${p
- } <${+M + 1}.0.0-0`
- }
- }
-
- debug('caret return', ret)
- return ret
- })
- }
-
- const replaceXRanges = (comp, options) => {
- debug('replaceXRanges', comp, options)
- return comp.split(/\s+/).map((comp) => {
- return replaceXRange(comp, options)
- }).join(' ')
- }
-
- const replaceXRange = (comp, options) => {
- comp = comp.trim()
- const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]
- return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
- debug('xRange', comp, ret, gtlt, M, m, p, pr)
- const xM = isX(M)
- const xm = xM || isX(m)
- const xp = xm || isX(p)
- const anyX = xp
-
- if (gtlt === '=' && anyX) {
- gtlt = ''
- }
-
- // if we're including prereleases in the match, then we need
- // to fix this to -0, the lowest possible prerelease value
- pr = options.includePrerelease ? '-0' : ''
-
- if (xM) {
- if (gtlt === '>' || gtlt === '<') {
- // nothing is allowed
- ret = '<0.0.0-0'
- } else {
- // nothing is forbidden
- ret = '*'
- }
- } else if (gtlt && anyX) {
- // we know patch is an x, because we have any x at all.
- // replace X with 0
- if (xm) {
- m = 0
- }
- p = 0
-
- if (gtlt === '>') {
- // >1 => >=2.0.0
- // >1.2 => >=1.3.0
- gtlt = '>='
- if (xm) {
- M = +M + 1
- m = 0
- p = 0
- } else {
- m = +m + 1
- p = 0
- }
- } else if (gtlt === '<=') {
- // <=0.7.x is actually <0.8.0, since any 0.7.x should
- // pass. Similarly, <=7.x is actually <8.0.0, etc.
- gtlt = '<'
- if (xm) {
- M = +M + 1
- } else {
- m = +m + 1
- }
- }
-
- if (gtlt === '<')
- pr = '-0'
-
- ret = `${gtlt + M}.${m}.${p}${pr}`
- } else if (xm) {
- ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`
- } else if (xp) {
- ret = `>=${M}.${m}.0${pr
- } <${M}.${+m + 1}.0-0`
- }
-
- debug('xRange return', ret)
-
- return ret
- })
- }
-
- // Because * is AND-ed with everything else in the comparator,
- // and '' means "any version", just remove the *s entirely.
- const replaceStars = (comp, options) => {
- debug('replaceStars', comp, options)
- // Looseness is ignored here. star is always as loose as it gets!
- return comp.trim().replace(re[t.STAR], '')
- }
-
- const replaceGTE0 = (comp, options) => {
- debug('replaceGTE0', comp, options)
- return comp.trim()
- .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
- }
-
- // This function is passed to string.replace(re[t.HYPHENRANGE])
- // M, m, patch, prerelease, build
- // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
- // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
- // 1.2 - 3.4 => >=1.2.0 <3.5.0-0
- const hyphenReplace = incPr => ($0,
- from, fM, fm, fp, fpr, fb,
- to, tM, tm, tp, tpr, tb) => {
- if (isX(fM)) {
- from = ''
- } else if (isX(fm)) {
- from = `>=${fM}.0.0${incPr ? '-0' : ''}`
- } else if (isX(fp)) {
- from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`
- } else if (fpr) {
- from = `>=${from}`
- } else {
- from = `>=${from}${incPr ? '-0' : ''}`
- }
-
- if (isX(tM)) {
- to = ''
- } else if (isX(tm)) {
- to = `<${+tM + 1}.0.0-0`
- } else if (isX(tp)) {
- to = `<${tM}.${+tm + 1}.0-0`
- } else if (tpr) {
- to = `<=${tM}.${tm}.${tp}-${tpr}`
- } else if (incPr) {
- to = `<${tM}.${tm}.${+tp + 1}-0`
- } else {
- to = `<=${to}`
- }
-
- return (`${from} ${to}`).trim()
- }
-
- const testSet = (set, version, options) => {
- for (let i = 0; i < set.length; i++) {
- if (!set[i].test(version)) {
- return false
- }
- }
-
- if (version.prerelease.length && !options.includePrerelease) {
- // Find the set of versions that are allowed to have prereleases
- // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
- // That should allow `1.2.3-pr.2` to pass.
- // However, `1.2.4-alpha.notready` should NOT be allowed,
- // even though it's within the range set by the comparators.
- for (let i = 0; i < set.length; i++) {
- debug(set[i].semver)
- if (set[i].semver === Comparator.ANY) {
- continue
- }
-
- if (set[i].semver.prerelease.length > 0) {
- const allowed = set[i].semver
- if (allowed.major === version.major &&
- allowed.minor === version.minor &&
- allowed.patch === version.patch) {
- return true
- }
- }
- }
-
- // Version has a -pre, but it's not one of the ones we like.
- return false
- }
-
- return true
- }
-
-
- /***/ }),
- /* 72 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const Range = __webpack_require__(71)
- const satisfies = (version, range, options) => {
- try {
- range = new Range(range, options)
- } catch (er) {
- return false
- }
- return range.test(version)
- }
- module.exports = satisfies
-
-
- /***/ }),
- /* 73 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const Range = __webpack_require__(71)
-
- // Mostly just for testing and legacy API reasons
- const toComparators = (range, options) =>
- new Range(range, options).set
- .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))
-
- module.exports = toComparators
-
-
- /***/ }),
- /* 74 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const SemVer = __webpack_require__(45)
- const Range = __webpack_require__(71)
-
- const maxSatisfying = (versions, range, options) => {
- let max = null
- let maxSV = null
- let rangeObj = null
- try {
- rangeObj = new Range(range, options)
- } catch (er) {
- return null
- }
- versions.forEach((v) => {
- if (rangeObj.test(v)) {
- // satisfies(v, range, options)
- if (!max || maxSV.compare(v) === -1) {
- // compare(max, v, true)
- max = v
- maxSV = new SemVer(max, options)
- }
- }
- })
- return max
- }
- module.exports = maxSatisfying
-
-
- /***/ }),
- /* 75 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const SemVer = __webpack_require__(45)
- const Range = __webpack_require__(71)
- const minSatisfying = (versions, range, options) => {
- let min = null
- let minSV = null
- let rangeObj = null
- try {
- rangeObj = new Range(range, options)
- } catch (er) {
- return null
- }
- versions.forEach((v) => {
- if (rangeObj.test(v)) {
- // satisfies(v, range, options)
- if (!min || minSV.compare(v) === 1) {
- // compare(min, v, true)
- min = v
- minSV = new SemVer(min, options)
- }
- }
- })
- return min
- }
- module.exports = minSatisfying
-
-
- /***/ }),
- /* 76 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const SemVer = __webpack_require__(45)
- const Range = __webpack_require__(71)
- const gt = __webpack_require__(63)
-
- const minVersion = (range, loose) => {
- range = new Range(range, loose)
-
- let minver = new SemVer('0.0.0')
- if (range.test(minver)) {
- return minver
- }
-
- minver = new SemVer('0.0.0-0')
- if (range.test(minver)) {
- return minver
- }
-
- minver = null
- for (let i = 0; i < range.set.length; ++i) {
- const comparators = range.set[i]
-
- comparators.forEach((comparator) => {
- // Clone to avoid manipulating the comparator's semver object.
- const compver = new SemVer(comparator.semver.version)
- switch (comparator.operator) {
- case '>':
- if (compver.prerelease.length === 0) {
- compver.patch++
- } else {
- compver.prerelease.push(0)
- }
- compver.raw = compver.format()
- /* fallthrough */
- case '':
- case '>=':
- if (!minver || gt(minver, compver)) {
- minver = compver
- }
- break
- case '<':
- case '<=':
- /* Ignore maximum versions */
- break
- /* istanbul ignore next */
- default:
- throw new Error(`Unexpected operation: ${comparator.operator}`)
- }
- })
- }
-
- if (minver && range.test(minver)) {
- return minver
- }
-
- return null
- }
- module.exports = minVersion
-
-
- /***/ }),
- /* 77 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const Range = __webpack_require__(71)
- const validRange = (range, options) => {
- try {
- // Return '*' instead of '' so that truthiness works.
- // This will throw if it's invalid anyway
- return new Range(range, options).range || '*'
- } catch (er) {
- return null
- }
- }
- module.exports = validRange
-
-
- /***/ }),
- /* 78 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const SemVer = __webpack_require__(45)
- const Comparator = __webpack_require__(70)
- const {ANY} = Comparator
- const Range = __webpack_require__(71)
- const satisfies = __webpack_require__(72)
- const gt = __webpack_require__(63)
- const lt = __webpack_require__(64)
- const lte = __webpack_require__(67)
- const gte = __webpack_require__(66)
-
- const outside = (version, range, hilo, options) => {
- version = new SemVer(version, options)
- range = new Range(range, options)
-
- let gtfn, ltefn, ltfn, comp, ecomp
- switch (hilo) {
- case '>':
- gtfn = gt
- ltefn = lte
- ltfn = lt
- comp = '>'
- ecomp = '>='
- break
- case '<':
- gtfn = lt
- ltefn = gte
- ltfn = gt
- comp = '<'
- ecomp = '<='
- break
- default:
- throw new TypeError('Must provide a hilo val of "<" or ">"')
- }
-
- // If it satisifes the range it is not outside
- if (satisfies(version, range, options)) {
- return false
- }
-
- // From now on, variable terms are as if we're in "gtr" mode.
- // but note that everything is flipped for the "ltr" function.
-
- for (let i = 0; i < range.set.length; ++i) {
- const comparators = range.set[i]
-
- let high = null
- let low = null
-
- comparators.forEach((comparator) => {
- if (comparator.semver === ANY) {
- comparator = new Comparator('>=0.0.0')
- }
- high = high || comparator
- low = low || comparator
- if (gtfn(comparator.semver, high.semver, options)) {
- high = comparator
- } else if (ltfn(comparator.semver, low.semver, options)) {
- low = comparator
- }
- })
-
- // If the edge version comparator has a operator then our version
- // isn't outside it
- if (high.operator === comp || high.operator === ecomp) {
- return false
- }
-
- // If the lowest version comparator has an operator and our version
- // is less than it then it isn't higher than the range
- if ((!low.operator || low.operator === comp) &&
- ltefn(version, low.semver)) {
- return false
- } else if (low.operator === ecomp && ltfn(version, low.semver)) {
- return false
- }
- }
- return true
- }
-
- module.exports = outside
-
-
- /***/ }),
- /* 79 */
- /***/ (function(module, exports, __webpack_require__) {
-
- // Determine if version is greater than all the versions possible in the range.
- const outside = __webpack_require__(78)
- const gtr = (version, range, options) => outside(version, range, '>', options)
- module.exports = gtr
-
-
- /***/ }),
- /* 80 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const outside = __webpack_require__(78)
- // Determine if version is less than all the versions possible in the range
- const ltr = (version, range, options) => outside(version, range, '<', options)
- module.exports = ltr
-
-
- /***/ }),
- /* 81 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const Range = __webpack_require__(71)
- const intersects = (r1, r2, options) => {
- r1 = new Range(r1, options)
- r2 = new Range(r2, options)
- return r1.intersects(r2)
- }
- module.exports = intersects
-
-
- /***/ }),
- /* 82 */
- /***/ (function(module, exports, __webpack_require__) {
-
- // given a set of versions and a range, create a "simplified" range
- // that includes the same versions that the original range does
- // If the original range is shorter than the simplified one, return that.
- const satisfies = __webpack_require__(72)
- const compare = __webpack_require__(53)
- module.exports = (versions, range, options) => {
- const set = []
- let min = null
- let prev = null
- const v = versions.sort((a, b) => compare(a, b, options))
- for (const version of v) {
- const included = satisfies(version, range, options)
- if (included) {
- prev = version
- if (!min)
- min = version
- } else {
- if (prev) {
- set.push([min, prev])
- }
- prev = null
- min = null
- }
- }
- if (min)
- set.push([min, null])
-
- const ranges = []
- for (const [min, max] of set) {
- if (min === max)
- ranges.push(min)
- else if (!max && min === v[0])
- ranges.push('*')
- else if (!max)
- ranges.push(`>=${min}`)
- else if (min === v[0])
- ranges.push(`<=${max}`)
- else
- ranges.push(`${min} - ${max}`)
- }
- const simplified = ranges.join(' || ')
- const original = typeof range.raw === 'string' ? range.raw : String(range)
- return simplified.length < original.length ? simplified : range
- }
-
-
- /***/ }),
- /* 83 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const Range = __webpack_require__(71)
- const { ANY } = __webpack_require__(70)
- const satisfies = __webpack_require__(72)
- const compare = __webpack_require__(53)
-
- // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:
- // - Every simple range `r1, r2, ...` is a subset of some `R1, R2, ...`
- //
- // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:
- // - If c is only the ANY comparator
- // - If C is only the ANY comparator, return true
- // - Else return false
- // - Let EQ be the set of = comparators in c
- // - If EQ is more than one, return true (null set)
- // - Let GT be the highest > or >= comparator in c
- // - Let LT be the lowest < or <= comparator in c
- // - If GT and LT, and GT.semver > LT.semver, return true (null set)
- // - If EQ
- // - If GT, and EQ does not satisfy GT, return true (null set)
- // - If LT, and EQ does not satisfy LT, return true (null set)
- // - If EQ satisfies every C, return true
- // - Else return false
- // - If GT
- // - If GT is lower than any > or >= comp in C, return false
- // - If GT is >=, and GT.semver does not satisfy every C, return false
- // - If LT
- // - If LT.semver is greater than that of any > comp in C, return false
- // - If LT is <=, and LT.semver does not satisfy every C, return false
- // - If any C is a = range, and GT or LT are set, return false
- // - Else return true
-
- const subset = (sub, dom, options) => {
- sub = new Range(sub, options)
- dom = new Range(dom, options)
- let sawNonNull = false
-
- OUTER: for (const simpleSub of sub.set) {
- for (const simpleDom of dom.set) {
- const isSub = simpleSubset(simpleSub, simpleDom, options)
- sawNonNull = sawNonNull || isSub !== null
- if (isSub)
- continue OUTER
- }
- // the null set is a subset of everything, but null simple ranges in
- // a complex range should be ignored. so if we saw a non-null range,
- // then we know this isn't a subset, but if EVERY simple range was null,
- // then it is a subset.
- if (sawNonNull)
- return false
- }
- return true
- }
-
- const simpleSubset = (sub, dom, options) => {
- if (sub.length === 1 && sub[0].semver === ANY)
- return dom.length === 1 && dom[0].semver === ANY
-
- const eqSet = new Set()
- let gt, lt
- for (const c of sub) {
- if (c.operator === '>' || c.operator === '>=')
- gt = higherGT(gt, c, options)
- else if (c.operator === '<' || c.operator === '<=')
- lt = lowerLT(lt, c, options)
- else
- eqSet.add(c.semver)
- }
-
- if (eqSet.size > 1)
- return null
-
- let gtltComp
- if (gt && lt) {
- gtltComp = compare(gt.semver, lt.semver, options)
- if (gtltComp > 0)
- return null
- else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<='))
- return null
- }
-
- // will iterate one or zero times
- for (const eq of eqSet) {
- if (gt && !satisfies(eq, String(gt), options))
- return null
-
- if (lt && !satisfies(eq, String(lt), options))
- return null
-
- for (const c of dom) {
- if (!satisfies(eq, String(c), options))
- return false
- }
- return true
- }
-
- let higher, lower
- let hasDomLT, hasDomGT
- for (const c of dom) {
- hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='
- hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='
- if (gt) {
- if (c.operator === '>' || c.operator === '>=') {
- higher = higherGT(gt, c, options)
- if (higher === c)
- return false
- } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options))
- return false
- }
- if (lt) {
- if (c.operator === '<' || c.operator === '<=') {
- lower = lowerLT(lt, c, options)
- if (lower === c)
- return false
- } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options))
- return false
- }
- if (!c.operator && (lt || gt) && gtltComp !== 0)
- return false
- }
-
- // if there was a < or >, and nothing in the dom, then must be false
- // UNLESS it was limited by another range in the other direction.
- // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0
- if (gt && hasDomLT && !lt && gtltComp !== 0)
- return false
-
- if (lt && hasDomGT && !gt && gtltComp !== 0)
- return false
-
- return true
- }
-
- // >=1.2.3 is lower than >1.2.3
- const higherGT = (a, b, options) => {
- if (!a)
- return b
- const comp = compare(a.semver, b.semver, options)
- return comp > 0 ? a
- : comp < 0 ? b
- : b.operator === '>' && a.operator === '>=' ? b
- : a
- }
-
- // <=1.2.3 is higher than <1.2.3
- const lowerLT = (a, b, options) => {
- if (!a)
- return b
- const comp = compare(a.semver, b.semver, options)
- return comp < 0 ? a
- : comp > 0 ? b
- : b.operator === '<' && a.operator === '<=' ? b
- : a
- }
-
- module.exports = subset
-
-
- /***/ }),
- /* 84 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.applyCodeActionCommands = exports.applyCodeAction = exports.getEditForCodeAction = void 0;
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- const coc_nvim_1 = __webpack_require__(1);
- const typeConverters = __importStar(__webpack_require__(37));
- function getEditForCodeAction(client, action) {
- return action.changes && action.changes.length
- ? typeConverters.WorkspaceEdit.fromFileCodeEdits(client, action.changes)
- : undefined;
- }
- exports.getEditForCodeAction = getEditForCodeAction;
- function applyCodeAction(client, action) {
- return __awaiter(this, void 0, void 0, function* () {
- const workspaceEdit = getEditForCodeAction(client, action);
- if (workspaceEdit) {
- if (!(yield coc_nvim_1.workspace.applyEdit(workspaceEdit))) {
- return false;
- }
- }
- return applyCodeActionCommands(client, action);
- });
- }
- exports.applyCodeAction = applyCodeAction;
- function applyCodeActionCommands(client, action) {
- return __awaiter(this, void 0, void 0, function* () {
- // make sure there is command
- if (action.commands && action.commands.length) {
- for (const command of action.commands) {
- const response = yield client.execute('applyCodeActionCommand', { command }, vscode_languageserver_protocol_1.CancellationToken.None);
- if (!response || response.type != 'response' || !response.body) {
- return false;
- }
- }
- }
- return true;
- });
- }
- exports.applyCodeActionCommands = applyCodeActionCommands;
-
-
- /***/ }),
- /* 85 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getParameterListParts = exports.convertCompletionEntry = void 0;
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- const PConst = __importStar(__webpack_require__(39));
- function convertCompletionEntry(tsEntry, uri, position, context) {
- let label = tsEntry.name;
- let sortText = tsEntry.sortText;
- let preselect = false;
- let detail;
- if (tsEntry.isRecommended) {
- preselect = true;
- }
- if (tsEntry.source) {
- // De-prioritze auto-imports https://github.com/Microsoft/vscode/issues/40311
- sortText = '\uffff' + sortText;
- }
- else {
- sortText = tsEntry.sortText;
- }
- let kind = convertKind(tsEntry.kind);
- let insertTextFormat = (context.enableCallCompletions &&
- (kind === vscode_languageserver_protocol_1.CompletionItemKind.Function ||
- kind === vscode_languageserver_protocol_1.CompletionItemKind.Method)) ? vscode_languageserver_protocol_1.InsertTextFormat.Snippet : vscode_languageserver_protocol_1.InsertTextFormat.PlainText;
- let insertText = tsEntry.insertText;
- let commitCharacters = getCommitCharacters(tsEntry, context);
- let textEdit = null;
- if (tsEntry.replacementSpan) {
- let { start, end } = tsEntry.replacementSpan;
- if (start.line == end.line) {
- textEdit = {
- range: vscode_languageserver_protocol_1.Range.create(start.line - 1, start.offset - 1, end.line - 1, end.offset - 1),
- newText: insertText || label
- };
- }
- }
- if (tsEntry.kindModifiers) {
- const kindModifiers = new Set(tsEntry.kindModifiers.split(/,|\s+/g));
- if (kindModifiers.has(PConst.KindModifiers.optional)) {
- insertText = label;
- label += '?';
- }
- if (kindModifiers.has(PConst.KindModifiers.color)) {
- kind = vscode_languageserver_protocol_1.CompletionItemKind.Color;
- }
- if (tsEntry.kind === PConst.Kind.script) {
- for (const extModifier of PConst.KindModifiers.fileExtensionKindModifiers) {
- if (kindModifiers.has(extModifier)) {
- if (tsEntry.name.toLowerCase().endsWith(extModifier)) {
- detail = tsEntry.name;
- }
- else {
- detail = tsEntry.name + extModifier;
- }
- break;
- }
- }
- }
- }
- return {
- label,
- insertText,
- textEdit,
- kind,
- preselect,
- insertTextFormat,
- sortText,
- commitCharacters,
- detail,
- data: {
- uri,
- position,
- source: tsEntry.source || ''
- }
- };
- }
- exports.convertCompletionEntry = convertCompletionEntry;
- function convertKind(kind) {
- switch (kind) {
- case PConst.Kind.primitiveType:
- case PConst.Kind.keyword:
- return vscode_languageserver_protocol_1.CompletionItemKind.Keyword;
- case PConst.Kind.const:
- return vscode_languageserver_protocol_1.CompletionItemKind.Constant;
- case PConst.Kind.let:
- case PConst.Kind.variable:
- case PConst.Kind.localVariable:
- case PConst.Kind.alias:
- return vscode_languageserver_protocol_1.CompletionItemKind.Variable;
- case PConst.Kind.memberVariable:
- case PConst.Kind.memberGetAccessor:
- case PConst.Kind.memberSetAccessor:
- return vscode_languageserver_protocol_1.CompletionItemKind.Field;
- case PConst.Kind.function:
- return vscode_languageserver_protocol_1.CompletionItemKind.Function;
- case PConst.Kind.method:
- case PConst.Kind.constructSignature:
- case PConst.Kind.callSignature:
- case PConst.Kind.indexSignature:
- return vscode_languageserver_protocol_1.CompletionItemKind.Method;
- case PConst.Kind.enum:
- return vscode_languageserver_protocol_1.CompletionItemKind.Enum;
- case PConst.Kind.module:
- case PConst.Kind.externalModuleName:
- return vscode_languageserver_protocol_1.CompletionItemKind.Module;
- case PConst.Kind.class:
- case PConst.Kind.type:
- return vscode_languageserver_protocol_1.CompletionItemKind.Class;
- case PConst.Kind.interface:
- return vscode_languageserver_protocol_1.CompletionItemKind.Interface;
- case PConst.Kind.warning:
- case PConst.Kind.script:
- return vscode_languageserver_protocol_1.CompletionItemKind.File;
- case PConst.Kind.directory:
- return vscode_languageserver_protocol_1.CompletionItemKind.Folder;
- }
- return vscode_languageserver_protocol_1.CompletionItemKind.Variable;
- }
- function getCommitCharacters(tsEntry, context) {
- if (context.isNewIdentifierLocation || !context.isInValidCommitCharacterContext) {
- return undefined;
- }
- const commitCharacters = [];
- switch (tsEntry.kind) {
- case PConst.Kind.memberGetAccessor:
- case PConst.Kind.memberSetAccessor:
- case PConst.Kind.constructSignature:
- case PConst.Kind.callSignature:
- case PConst.Kind.indexSignature:
- case PConst.Kind.enum:
- case PConst.Kind.interface:
- commitCharacters.push('.', ';');
- break;
- case PConst.Kind.module:
- case PConst.Kind.alias:
- case PConst.Kind.const:
- case PConst.Kind.let:
- case PConst.Kind.variable:
- case PConst.Kind.localVariable:
- case PConst.Kind.memberVariable:
- case PConst.Kind.class:
- case PConst.Kind.function:
- case PConst.Kind.method:
- case PConst.Kind.keyword:
- case PConst.Kind.parameter:
- commitCharacters.push('.', ',', ';');
- if (context.enableCallCompletions) {
- commitCharacters.push('(');
- }
- break;
- }
- return commitCharacters.length === 0 ? undefined : commitCharacters;
- }
- function getParameterListParts(displayParts) {
- const parts = [];
- let isInMethod = false;
- let hasOptionalParameters = false;
- let parenCount = 0;
- let braceCount = 0;
- outer: for (let i = 0; i < displayParts.length; ++i) {
- const part = displayParts[i];
- switch (part.kind) {
- case PConst.DisplayPartKind.methodName:
- case PConst.DisplayPartKind.functionName:
- case PConst.DisplayPartKind.text:
- case PConst.DisplayPartKind.propertyName:
- if (parenCount === 0 && braceCount === 0) {
- isInMethod = true;
- }
- break;
- case PConst.DisplayPartKind.parameterName:
- if (parenCount === 1 && braceCount === 0 && isInMethod) {
- // Only take top level paren names
- const next = displayParts[i + 1];
- // Skip optional parameters
- const nameIsFollowedByOptionalIndicator = next && next.text === '?';
- if (!nameIsFollowedByOptionalIndicator) {
- parts.push(part);
- }
- hasOptionalParameters = hasOptionalParameters || nameIsFollowedByOptionalIndicator;
- }
- break;
- case PConst.DisplayPartKind.punctuation:
- if (part.text === '(') {
- ++parenCount;
- }
- else if (part.text === ')') {
- --parenCount;
- if (parenCount <= 0 && isInMethod) {
- break outer;
- }
- }
- else if (part.text === '...' && parenCount === 1) {
- // Found rest parmeter. Do not fill in any further arguments
- hasOptionalParameters = true;
- break outer;
- }
- else if (part.text === '{') {
- ++braceCount;
- }
- else if (part.text === '}') {
- --braceCount;
- }
- break;
- }
- }
- return { hasOptionalParameters, parts };
- }
- exports.getParameterListParts = getParameterListParts;
-
-
- /***/ }),
- /* 86 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.markdownDocumentation = exports.tagsMarkdownPreview = exports.plain = void 0;
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- function getTagBodyText(tag) {
- if (!tag.text) {
- return undefined;
- }
- switch (tag.name) {
- case 'example':
- case 'default':
- // Convert to markdown code block if it not already one
- if (tag.text.match(/^\s*[~`]{3}/g)) {
- return tag.text;
- }
- return '```\n' + tag.text + '\n```';
- }
- return tag.text;
- }
- function getTagDocumentation(tag) {
- switch (tag.name) {
- case 'param':
- const body = (tag.text || '').split(/^([\w\.]+)\s*/);
- if (body && body.length === 3) {
- const param = body[1];
- const doc = body[2];
- const label = `*@${tag.name}* \`${param}\``;
- if (!doc) {
- return label;
- }
- return label + (doc.match(/\r\n|\n/g) ? '\n' + doc : ` — ${doc}`);
- }
- }
- // Generic tag
- const label = `*@${tag.name}*`;
- const text = getTagBodyText(tag);
- if (!text) {
- return label;
- }
- return label + (text.match(/\r\n|\n/g) ? '\n' + text : ` — ${text}`);
- }
- function plain(parts) {
- if (!parts || !parts.length)
- return '';
- return parts.map(part => part.text).join('');
- }
- exports.plain = plain;
- function tagsMarkdownPreview(tags) {
- return (tags || []).map(getTagDocumentation).join(' \n\n');
- }
- exports.tagsMarkdownPreview = tagsMarkdownPreview;
- function markdownDocumentation(documentation, tags) {
- let out = plain(documentation);
- const tagsPreview = tagsMarkdownPreview(tags);
- if (tagsPreview) {
- out = out + ('\n\n' + tagsPreview);
- }
- return {
- kind: vscode_languageserver_protocol_1.MarkupKind.Markdown,
- value: out
- };
- }
- exports.markdownDocumentation = markdownDocumentation;
-
-
- /***/ }),
- /* 87 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- Object.defineProperty(exports, "__esModule", { value: true });
- class SnippetString {
- constructor(value) {
- this._tabstop = 1;
- this.value = value || '';
- }
- static isSnippetString(thing) {
- if (thing instanceof SnippetString) {
- return true;
- }
- if (!thing) {
- return false;
- }
- return typeof thing.value === 'string';
- }
- static _escape(value) {
- return value.replace(/\$|}|\\/g, '\\$&');
- }
- appendText(str) {
- this.value += SnippetString._escape(str);
- return this;
- }
- appendTabstop(n = this._tabstop++) {
- this.value += '$';
- this.value += n;
- return this;
- }
- appendPlaceholder(value, n = this._tabstop++) {
- if (typeof value === 'function') {
- const nested = new SnippetString();
- nested._tabstop = this._tabstop;
- value(nested);
- this._tabstop = nested._tabstop;
- value = nested.value;
- }
- else {
- value = SnippetString._escape(value);
- }
- this.value += '${';
- this.value += n;
- this.value += ':';
- this.value += value;
- this.value += '}';
- return this;
- }
- appendVariable(name, defaultValue) {
- if (typeof defaultValue === 'function') {
- const nested = new SnippetString();
- nested._tabstop = this._tabstop;
- defaultValue(nested);
- this._tabstop = nested._tabstop;
- defaultValue = nested.value;
- }
- else if (typeof defaultValue === 'string') {
- defaultValue = defaultValue.replace(/\$|}/g, '\\$&');
- }
- this.value += '${';
- this.value += name;
- if (defaultValue) {
- this.value += ':';
- this.value += defaultValue;
- }
- this.value += '}';
- return this;
- }
- }
- exports.default = SnippetString;
-
-
- /***/ }),
- /* 88 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- const typeConverters = __importStar(__webpack_require__(37));
- class TypeScriptDefinitionProvider {
- constructor(client) {
- this.client = client;
- }
- getSymbolLocations(definitionType, document, position, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const filepath = this.client.toPath(document.uri);
- if (!filepath) {
- return undefined;
- }
- const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
- try {
- const response = yield this.client.execute(definitionType, args, token);
- const locations = (response.type == 'response' && response.body) || [];
- return locations.map(location => typeConverters.Location.fromTextSpan(this.client.toResource(location.file), location));
- }
- catch (_a) {
- return [];
- }
- });
- }
- provideDefinition(document, position, token) {
- return this.getSymbolLocations('definition', document, position, token);
- }
- provideTypeDefinition(document, position, token) {
- return this.getSymbolLocations('typeDefinition', document, position, token);
- }
- provideImplementation(document, position, token) {
- return this.getSymbolLocations('implementation', document, position, token);
- }
- }
- exports.default = TypeScriptDefinitionProvider;
-
-
- /***/ }),
- /* 89 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- const coc_nvim_1 = __webpack_require__(1);
- const api_1 = __importDefault(__webpack_require__(40));
- const tsDirectives = [
- {
- value: '@ts-check',
- description: 'Enables semantic checking in a JavaScript file. Must be at the top of a file.'
- },
- {
- value: '@ts-nocheck',
- description: 'Disables semantic checking in a JavaScript file. Must be at the top of a file.'
- },
- {
- value: '@ts-ignore',
- description: 'Suppresses @ts-check errors on the next line of a file.'
- }
- ];
- const tsDirectives390 = [
- ...tsDirectives,
- {
- value: '@ts-expect-error',
- description: 'Suppresses @ts-check errors on the next line of a file, expecting at least one to exist.'
- }
- ];
- class DirectiveCommentCompletionProvider {
- constructor(client) {
- this.client = client;
- }
- provideCompletionItems(document, position, _token, context) {
- if (context.triggerCharacter != '@') {
- return [];
- }
- const file = this.client.toPath(document.uri);
- if (!file) {
- return [];
- }
- const doc = coc_nvim_1.workspace.getDocument(document.uri);
- const line = doc.getline(position.line);
- const prefix = line.slice(0, position.character);
- const match = prefix.match(/^\s*\/\/+\s?(@[a-zA-Z\-]*)?$/);
- if (match) {
- const directives = this.client.apiVersion.gte(api_1.default.v390)
- ? tsDirectives390
- : tsDirectives;
- let items = directives.map(directive => {
- const item = vscode_languageserver_protocol_1.CompletionItem.create(directive.value);
- item.kind = vscode_languageserver_protocol_1.CompletionItemKind.Snippet;
- item.detail = directive.description;
- item.textEdit = {
- range: vscode_languageserver_protocol_1.Range.create(position.line, Math.max(0, position.character - (match[1] ? match[1].length : 0)), position.line, position.character),
- newText: directive.value
- };
- return item;
- });
- let res = {
- isIncomplete: false,
- items
- };
- res.startcol = doc.fixStartcol(position, ['@']);
- return res;
- }
- return [];
- }
- }
- exports.default = DirectiveCommentCompletionProvider;
-
-
- /***/ }),
- /* 90 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- const typeConverters = __importStar(__webpack_require__(37));
- const arrays_1 = __webpack_require__(91);
- class TypeScriptDocumentHighlightProvider {
- constructor(client) {
- this.client = client;
- }
- provideDocumentHighlights(resource, position, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const file = this.client.toPath(resource.uri);
- if (!file)
- return [];
- const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { filesToSearch: [file] });
- try {
- const response = yield this.client.execute('documentHighlights', args, token);
- if (response.type !== 'response' || !response.body) {
- return [];
- }
- return arrays_1.flatten(response.body
- .filter(highlight => highlight.file === file)
- .map(convertDocumentHighlight));
- }
- catch (_e) {
- return [];
- }
- });
- }
- }
- exports.default = TypeScriptDocumentHighlightProvider;
- function convertDocumentHighlight(highlight) {
- return highlight.highlightSpans.map(span => {
- return {
- range: typeConverters.Range.fromTextSpan(span),
- kind: span.kind === 'writtenReference' ? vscode_languageserver_protocol_1.DocumentHighlightKind.Write : vscode_languageserver_protocol_1.DocumentHighlightKind.Read
- };
- });
- }
-
-
- /***/ }),
- /* 91 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.flatten = exports.equals = void 0;
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- function equals(one, other, itemEquals = (a, b) => a === b) {
- if (one.length !== other.length) {
- return false;
- }
- for (let i = 0, len = one.length; i < len; i++) {
- if (!itemEquals(one[i], other[i])) {
- return false;
- }
- }
- return true;
- }
- exports.equals = equals;
- function flatten(arr) {
- return [].concat.apply([], arr);
- }
- exports.flatten = flatten;
-
-
- /***/ }),
- /* 92 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- const PConst = __importStar(__webpack_require__(39));
- const typeConverters = __importStar(__webpack_require__(37));
- const getSymbolKind = (kind) => {
- switch (kind) {
- case PConst.Kind.module:
- return vscode_languageserver_protocol_1.SymbolKind.Module;
- case PConst.Kind.class:
- return vscode_languageserver_protocol_1.SymbolKind.Class;
- case PConst.Kind.enum:
- return vscode_languageserver_protocol_1.SymbolKind.Enum;
- case PConst.Kind.interface:
- return vscode_languageserver_protocol_1.SymbolKind.Interface;
- case PConst.Kind.method:
- return vscode_languageserver_protocol_1.SymbolKind.Method;
- case PConst.Kind.memberVariable:
- return vscode_languageserver_protocol_1.SymbolKind.Property;
- case PConst.Kind.memberGetAccessor:
- return vscode_languageserver_protocol_1.SymbolKind.Property;
- case PConst.Kind.memberSetAccessor:
- return vscode_languageserver_protocol_1.SymbolKind.Property;
- case PConst.Kind.variable:
- return vscode_languageserver_protocol_1.SymbolKind.Variable;
- case PConst.Kind.const:
- return vscode_languageserver_protocol_1.SymbolKind.Variable;
- case PConst.Kind.localVariable:
- return vscode_languageserver_protocol_1.SymbolKind.Variable;
- case PConst.Kind.variable:
- return vscode_languageserver_protocol_1.SymbolKind.Variable;
- case PConst.Kind.constructSignature:
- case PConst.Kind.constructorImplementation:
- case PConst.Kind.function:
- case PConst.Kind.localFunction:
- return vscode_languageserver_protocol_1.SymbolKind.Function;
- }
- return vscode_languageserver_protocol_1.SymbolKind.Variable;
- };
- class TypeScriptDocumentSymbolProvider {
- constructor(client) {
- this.client = client;
- }
- provideDocumentSymbols(resource, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const filepath = this.client.toPath(resource.uri);
- if (!filepath)
- return [];
- const args = {
- file: filepath
- };
- try {
- const response = yield this.client.execute('navtree', args, token);
- if (response.type == 'response' && response.body) {
- // The root represents the file. Ignore this when showing in the UI
- const tree = response.body;
- if (tree.childItems) {
- const result = new Array();
- tree.childItems.forEach(item => TypeScriptDocumentSymbolProvider.convertNavTree(result, item));
- return result;
- }
- }
- return [];
- }
- catch (e) {
- return [];
- }
- });
- }
- static convertNavTree(bucket, item) {
- let shouldInclude = TypeScriptDocumentSymbolProvider.shouldInclueEntry(item);
- const children = new Set(item.childItems || []);
- for (const span of item.spans) {
- const range = typeConverters.Range.fromTextSpan(span);
- const symbolInfo = vscode_languageserver_protocol_1.DocumentSymbol.create(item.text, '', getSymbolKind(item.kind), range, range);
- symbolInfo.children = children.size > 0 ? [] : null;
- for (const child of children) {
- if (child.spans.some(span => !!containsRange(range, typeConverters.Range.fromTextSpan(span)))) {
- const includedChild = TypeScriptDocumentSymbolProvider.convertNavTree(symbolInfo.children, child);
- shouldInclude = shouldInclude || includedChild;
- children.delete(child);
- }
- }
- if (shouldInclude) {
- bucket.push(symbolInfo);
- }
- }
- return shouldInclude;
- }
- static shouldInclueEntry(item) {
- if (item.kind === PConst.Kind.alias) {
- return false;
- }
- return !!(item.text &&
- item.text !== '<function>' &&
- item.text !== '<class>');
- }
- }
- exports.default = TypeScriptDocumentSymbolProvider;
- function containsRange(range, otherRange) {
- if (otherRange.start.line < range.start.line || otherRange.end.line < range.start.line) {
- return false;
- }
- if (otherRange.start.line > range.end.line || otherRange.end.line > range.end.line) {
- return false;
- }
- if (otherRange.start.line === range.start.line && otherRange.start.character < range.start.character) {
- return false;
- }
- if (otherRange.end.line === range.end.line && otherRange.end.character > range.end.character) {
- return false;
- }
- return true;
- }
-
-
- /***/ }),
- /* 93 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const coc_nvim_1 = __webpack_require__(1);
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- const api_1 = __importDefault(__webpack_require__(40));
- function objAreEqual(a, b) {
- let keys = Object.keys(a);
- for (let i = 0; i < keys.length; i++) { // tslint:disable-line
- let key = keys[i];
- if (a[key] !== b[key]) {
- return false;
- }
- }
- return true;
- }
- class FileConfigurationManager {
- constructor(client) {
- this.client = client;
- this.cachedMap = new Map();
- }
- ensureConfigurationOptions(document, insertSpaces, tabSize) {
- return __awaiter(this, void 0, void 0, function* () {
- const file = this.client.toPath(document.uri);
- let options = {
- tabSize,
- insertSpaces
- };
- let cachedOption = this.cachedMap.get(document.uri);
- const currentOptions = this.getFileOptions(options, document);
- if (cachedOption
- && objAreEqual(cachedOption.formatOptions, currentOptions.formatOptions)
- && objAreEqual(cachedOption.preferences, currentOptions.preferences))
- return;
- this.cachedMap.set(document.uri, currentOptions);
- const args = Object.assign({ file }, currentOptions);
- yield this.client.execute('configure', args, vscode_languageserver_protocol_1.CancellationToken.None);
- });
- }
- ensureConfigurationForDocument(document) {
- return __awaiter(this, void 0, void 0, function* () {
- let opts = yield coc_nvim_1.workspace.getFormatOptions(document.uri);
- return this.ensureConfigurationOptions(document, opts.insertSpaces, opts.tabSize);
- });
- }
- reset() {
- this.cachedMap.clear();
- }
- getLanguageConfiguration(languageId) {
- return coc_nvim_1.workspace.getConfiguration(languageId);
- }
- isTypeScriptDocument(languageId) {
- return languageId.startsWith('typescript');
- }
- formatEnabled(document) {
- let { languageId, uri } = document;
- let language = languageId.startsWith('typescript') ? 'typescript' : 'javascript';
- const config = coc_nvim_1.workspace.getConfiguration(`${language}.format`, uri);
- return config.get('enabled');
- }
- enableJavascript() {
- const config = coc_nvim_1.workspace.getConfiguration('tsserver');
- return !!config.get('enableJavascript');
- }
- getFileOptions(options, document) {
- const lang = this.isTypeScriptDocument(document.languageId) ? 'typescript' : 'javascript';
- return {
- formatOptions: this.getFormatOptions(options, lang, document.uri),
- preferences: this.getPreferences(lang, document.uri)
- };
- }
- getFormatOptions(options, language, uri) {
- const config = coc_nvim_1.workspace.getConfiguration(`${language}.format`, uri);
- return {
- tabSize: options.tabSize,
- indentSize: options.tabSize,
- convertTabsToSpaces: options.insertSpaces,
- // We can use \n here since the editor normalizes later on to its line endings.
- newLineCharacter: '\n',
- insertSpaceAfterCommaDelimiter: config.get('insertSpaceAfterCommaDelimiter'),
- insertSpaceAfterConstructor: config.get('insertSpaceAfterConstructor'),
- insertSpaceAfterSemicolonInForStatements: config.get('insertSpaceAfterSemicolonInForStatements'),
- insertSpaceBeforeAndAfterBinaryOperators: config.get('insertSpaceBeforeAndAfterBinaryOperators'),
- insertSpaceAfterKeywordsInControlFlowStatements: config.get('insertSpaceAfterKeywordsInControlFlowStatements'),
- insertSpaceAfterFunctionKeywordForAnonymousFunctions: config.get('insertSpaceAfterFunctionKeywordForAnonymousFunctions'),
- insertSpaceBeforeFunctionParenthesis: config.get('insertSpaceBeforeFunctionParenthesis'),
- insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis'),
- insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets'),
- insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces'),
- insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces'),
- insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces'),
- insertSpaceAfterTypeAssertion: config.get('insertSpaceAfterTypeAssertion'),
- placeOpenBraceOnNewLineForFunctions: config.get('placeOpenBraceOnNewLineForFunctions'),
- placeOpenBraceOnNewLineForControlBlocks: config.get('placeOpenBraceOnNewLineForControlBlocks'),
- semicolons: config.get('semicolons', undefined)
- };
- }
- getCompleteOptions(languageId) {
- const lang = this.isTypeScriptDocument(languageId) ? 'typescript' : 'javascript';
- const config = coc_nvim_1.workspace.getConfiguration(`${lang}.suggest`);
- return {
- enabled: config.get('enabled', true),
- names: config.get('names', true),
- paths: config.get('paths', true),
- completeFunctionCalls: config.get('completeFunctionCalls', true),
- autoImports: config.get('autoImports', true),
- includeAutomaticOptionalChainCompletions: config.get('includeAutomaticOptionalChainCompletions', true)
- };
- }
- getPreferences(language, uri) {
- if (this.client.apiVersion.lt(api_1.default.v290)) {
- return {};
- }
- const config = coc_nvim_1.workspace.getConfiguration(`${language}.preferences`, uri);
- // getImportModuleSpecifierEndingPreference available on ts 2.9.0
- const preferences = {
- quotePreference: this.getQuoteStyle(config),
- importModuleSpecifierPreference: getImportModuleSpecifier(config),
- importModuleSpecifierEnding: getImportModuleSpecifierEndingPreference(config),
- allowTextChangesInNewFiles: uri.startsWith('file:'),
- allowRenameOfImportPath: true,
- providePrefixAndSuffixTextForRename: true,
- };
- return preferences;
- }
- getQuoteStyle(config) {
- let quoteStyle = config.get('quoteStyle', 'auto');
- if (this.client.apiVersion.gte(api_1.default.v333) || quoteStyle != 'auto')
- return quoteStyle;
- return 'single';
- }
- }
- exports.default = FileConfigurationManager;
- function getImportModuleSpecifier(config) {
- let val = config.get('importModuleSpecifier');
- switch (val) {
- case 'relative':
- return 'relative';
- case 'non-relative':
- return 'non-relative';
- default:
- return 'auto';
- }
- }
- function getImportModuleSpecifierEndingPreference(config) {
- switch (config.get('importModuleSpecifierEnding')) {
- case 'minimal': return 'minimal';
- case 'index': return 'index';
- case 'js': return 'js';
- default: return 'auto';
- }
- }
-
-
- /***/ }),
- /* 94 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- const vscode_languageserver_types_1 = __webpack_require__(18);
- const coc_nvim_1 = __webpack_require__(1);
- const typeConverters = __importStar(__webpack_require__(37));
- class TypeScriptFoldingProvider {
- constructor(client) {
- this.client = client;
- }
- provideFoldingRanges(document, _context, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const file = this.client.toPath(document.uri);
- if (!file) {
- return;
- }
- const args = { file };
- const res = yield this.client.execute('getOutliningSpans', args, token);
- if (res.type != 'response') {
- return;
- }
- const { body } = res;
- if (!body) {
- return;
- }
- return body
- .map(span => this.convertOutliningSpan(span, document))
- .filter(foldingRange => !!foldingRange);
- });
- }
- convertOutliningSpan(span, document) {
- const range = typeConverters.Range.fromTextSpan(span.textSpan);
- const kind = TypeScriptFoldingProvider.getFoldingRangeKind(span);
- // Workaround for #49904
- if (span.kind === 'comment') {
- let doc = coc_nvim_1.workspace.getDocument(document.uri);
- const line = doc.getline(range.start.line);
- if (line.match(/\/\/\s*#endregion/gi)) {
- return undefined;
- }
- }
- let { start, end } = range;
- return vscode_languageserver_types_1.FoldingRange.create(start.line, end.line, start.character, end.character, kind);
- }
- static getFoldingRangeKind(span) {
- switch (span.kind) {
- case 'comment':
- case 'region':
- case 'imports':
- case 'code':
- return span.kind;
- default:
- return undefined;
- }
- }
- }
- exports.default = TypeScriptFoldingProvider;
-
-
- /***/ }),
- /* 95 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const coc_nvim_1 = __webpack_require__(1);
- const typeConverters = __importStar(__webpack_require__(37));
- class TypeScriptFormattingProvider {
- constructor(client, formattingOptionsManager) {
- this.client = client;
- this.formattingOptionsManager = formattingOptionsManager;
- }
- enabled(document) {
- return this.formattingOptionsManager.formatEnabled(document);
- }
- doFormat(document, options, args, token) {
- return __awaiter(this, void 0, void 0, function* () {
- if (!this.enabled(document))
- return [];
- yield this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize);
- try {
- const response = yield this.client.execute('format', args, token);
- if (response.type == 'response' && response.body) {
- let edits = response.body.map(typeConverters.TextEdit.fromCodeEdit);
- return edits;
- }
- }
- catch (_a) {
- // noop
- }
- return [];
- });
- }
- provideDocumentRangeFormattingEdits(document, range, options, token) {
- return __awaiter(this, void 0, void 0, function* () {
- if (!this.enabled(document))
- return [];
- const filepath = this.client.toPath(document.uri);
- if (!filepath)
- return [];
- const args = {
- file: filepath,
- line: range.start.line + 1,
- offset: range.start.character + 1,
- endLine: range.end.line + 1,
- endOffset: range.end.character + 1
- };
- return this.doFormat(document, options, args, token);
- });
- }
- provideDocumentFormattingEdits(document, options, token) {
- return __awaiter(this, void 0, void 0, function* () {
- if (!this.enabled(document))
- return [];
- const filepath = this.client.toPath(document.uri);
- if (!filepath)
- return [];
- const args = {
- file: filepath,
- line: 1,
- offset: 1,
- endLine: document.lineCount + 1,
- endOffset: 1
- };
- return this.doFormat(document, options, args, token);
- });
- }
- provideOnTypeFormattingEdits(document, position, ch, options, token) {
- return __awaiter(this, void 0, void 0, function* () {
- if (!this.enabled(document))
- return [];
- if (!this.client.configuration.formatOnType)
- return [];
- const file = this.client.toPath(document.uri);
- if (!file)
- return [];
- yield this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize);
- const doc = coc_nvim_1.workspace.getDocument(document.uri);
- const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { key: ch });
- try {
- const res = yield this.client.execute('formatonkey', args, token);
- if (res.type != 'response') {
- return [];
- }
- const { body } = res;
- const edits = body;
- const result = [];
- if (!edits) {
- return result;
- }
- for (const edit of edits) {
- const textEdit = typeConverters.TextEdit.fromCodeEdit(edit);
- const range = textEdit.range;
- // Work around for https://github.com/Microsoft/TypeScript/issues/6700.
- // Check if we have an edit at the beginning of the line which only removes white spaces and leaves
- // an empty line. Drop those edits
- if (range.start.character === 0 &&
- range.start.line === range.end.line &&
- textEdit.newText === '') {
- const lText = doc.getline(range.start.line);
- // If the edit leaves something on the line keep the edit (note that the end character is exclusive).
- // Keep it also if it removes something else than whitespace
- if (lText.trim().length > 0 || lText.length > range.end.character) {
- result.push(textEdit);
- }
- }
- else {
- result.push(textEdit);
- }
- }
- return result;
- }
- catch (_a) {
- // noop
- }
- return [];
- });
- }
- }
- exports.default = TypeScriptFormattingProvider;
-
-
- /***/ }),
- /* 96 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- const previewer_1 = __webpack_require__(86);
- const typeConverters = __importStar(__webpack_require__(37));
- class TypeScriptHoverProvider {
- constructor(client) {
- this.client = client;
- }
- provideHover(document, position, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const filepath = this.client.toPath(document.uri);
- if (!filepath) {
- return undefined;
- }
- const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
- try {
- const response = yield this.client.interruptGetErr(() => this.client.execute('quickinfo', args, token));
- if (response && response.type == 'response' && response.body) {
- const data = response.body;
- return {
- contents: TypeScriptHoverProvider.getContents(data),
- range: typeConverters.Range.fromTextSpan(data)
- };
- }
- }
- catch (e) {
- // noop
- }
- return undefined;
- });
- }
- static getContents(data) {
- const parts = [];
- if (data.displayString) {
- parts.push({ language: 'typescript', value: data.displayString });
- }
- const tags = previewer_1.tagsMarkdownPreview(data.tags);
- parts.push(data.documentation + (tags ? '\n\n' + tags : ''));
- return parts;
- }
- }
- exports.default = TypeScriptHoverProvider;
-
-
- /***/ }),
- /* 97 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- const PConst = __importStar(__webpack_require__(39));
- const typeConverters = __importStar(__webpack_require__(37));
- const baseCodeLensProvider_1 = __webpack_require__(35);
- class TypeScriptImplementationsCodeLensProvider extends baseCodeLensProvider_1.TypeScriptBaseCodeLensProvider {
- resolveCodeLens(codeLens, token) {
- return __awaiter(this, void 0, void 0, function* () {
- let { uri } = codeLens.data;
- let filepath = this.client.toPath(uri);
- const args = typeConverters.Position.toFileLocationRequestArgs(filepath, codeLens.range.start);
- try {
- const response = yield this.client.execute('implementation', args, token, true);
- if (response && response.type == 'response' && response.body) {
- const locations = response.body
- .map(reference => {
- return {
- uri: this.client.toResource(reference.file),
- range: {
- start: typeConverters.Position.fromLocation(reference.start),
- end: {
- line: reference.start.line,
- character: 0
- }
- }
- };
- })
- // Exclude original from implementations
- .filter(location => !(location.uri.toString() === uri &&
- location.range.start.line === codeLens.range.start.line &&
- location.range.start.character ===
- codeLens.range.start.character));
- codeLens.command = this.getCommand(locations, codeLens);
- return codeLens;
- }
- }
- catch (_a) {
- // noop
- }
- codeLens.command = {
- title: '0 implementations',
- command: ''
- };
- return codeLens;
- });
- }
- getCommand(locations, codeLens) {
- let { uri } = codeLens.data;
- return {
- title: this.getTitle(locations),
- command: locations.length ? 'editor.action.showReferences' : '',
- arguments: [uri, codeLens.range.start, locations]
- };
- }
- getTitle(locations) {
- return locations.length === 1 ? '1 implementation' : `${locations.length} implementations`;
- }
- extractSymbol(document, item, _parent) {
- switch (item.kind) {
- case PConst.Kind.interface:
- return super.getSymbolRange(document, item);
- case PConst.Kind.class:
- case PConst.Kind.method:
- case PConst.Kind.memberVariable:
- case PConst.Kind.memberGetAccessor:
- case PConst.Kind.memberSetAccessor:
- if (item.kindModifiers.match(/\babstract\b/g)) {
- return super.getSymbolRange(document, item);
- }
- break;
- }
- return null;
- }
- }
- exports.default = TypeScriptImplementationsCodeLensProvider;
-
-
- /***/ }),
- /* 98 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const coc_nvim_1 = __webpack_require__(1);
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- const api_1 = __importDefault(__webpack_require__(40));
- const codeAction_1 = __webpack_require__(84);
- const typeConverters = __importStar(__webpack_require__(37));
- class ApplyCodeActionCommand {
- constructor(client) {
- this.client = client;
- this.id = ApplyCodeActionCommand.ID;
- }
- execute(action) {
- return __awaiter(this, void 0, void 0, function* () {
- return codeAction_1.applyCodeActionCommands(this.client, action);
- });
- }
- }
- ApplyCodeActionCommand.ID = '_typescript.applyCodeActionCommand';
- class ApplyFixAllCodeAction {
- constructor(client) {
- this.client = client;
- this.id = ApplyFixAllCodeAction.ID;
- }
- execute(file, tsAction) {
- return __awaiter(this, void 0, void 0, function* () {
- if (!tsAction.fixId) {
- return;
- }
- const args = {
- scope: {
- type: 'file',
- args: { file }
- },
- fixId: tsAction.fixId
- };
- try {
- const res = yield this.client.execute('getCombinedCodeFix', args, vscode_languageserver_protocol_1.CancellationToken.None);
- if (res.type != 'response') {
- return;
- }
- let { body } = res;
- const edit = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, body.changes);
- yield coc_nvim_1.workspace.applyEdit(edit);
- const token = vscode_languageserver_protocol_1.CancellationToken.None;
- const { commands } = body;
- if (commands && commands.length) {
- for (const command of commands) {
- yield this.client.execute('applyCodeActionCommand', { command }, token);
- }
- }
- }
- catch (_a) {
- // noop
- }
- });
- }
- }
- ApplyFixAllCodeAction.ID = '_typescript.applyFixAllCodeAction';
- /**
- * Unique set of diagnostics keyed on diagnostic range and error code.
- */
- class DiagnosticsSet {
- constructor(_values) {
- this._values = _values;
- }
- static from(diagnostics) {
- const values = new Map();
- for (const diagnostic of diagnostics) {
- values.set(DiagnosticsSet.key(diagnostic), diagnostic);
- }
- return new DiagnosticsSet(values);
- }
- static key(diagnostic) {
- const { start, end } = diagnostic.range;
- return `${diagnostic.code}-${start.line},${start.character}-${end.line},${end.character}`;
- }
- get values() {
- return this._values.values();
- }
- }
- class SupportedCodeActionProvider {
- constructor(client) {
- this.client = client;
- }
- getFixableDiagnosticsForContext(context) {
- return __awaiter(this, void 0, void 0, function* () {
- const supportedActions = yield this.supportedCodeActions;
- const fixableDiagnostics = DiagnosticsSet.from(context.diagnostics.filter(diagnostic => supportedActions.has(+diagnostic.code)));
- return Array.from(fixableDiagnostics.values);
- });
- }
- get supportedCodeActions() {
- if (!this._supportedCodeActions) {
- return new Promise((resolve, reject) => {
- this.client.execute('getSupportedCodeFixes', null, vscode_languageserver_protocol_1.CancellationToken.None).then(res => {
- if (res.type !== 'response') {
- resolve(new Set());
- return;
- }
- let codes = res.body.map(code => +code).filter(code => !isNaN(code));
- resolve(new Set(codes));
- }, reject);
- });
- }
- return Promise.resolve(this._supportedCodeActions);
- }
- }
- class TypeScriptQuickFixProvider {
- constructor(client) {
- this.client = client;
- coc_nvim_1.commands.register(new ApplyCodeActionCommand(client));
- coc_nvim_1.commands.register(new ApplyFixAllCodeAction(client));
- this.supportedCodeActionProvider = new SupportedCodeActionProvider(client);
- }
- provideCodeActions(document, _range, context, token) {
- return __awaiter(this, void 0, void 0, function* () {
- if (!this.client.apiVersion.gte(api_1.default.v213)) {
- return [];
- }
- const file = this.client.toPath(document.uri);
- if (!file) {
- return [];
- }
- const fixableDiagnostics = yield this.supportedCodeActionProvider.getFixableDiagnosticsForContext(context);
- if (!fixableDiagnostics.length) {
- return [];
- }
- if (this.client.bufferSyncSupport.hasPendingDiagnostics(document.uri)) {
- return [];
- }
- const results = [];
- for (const diagnostic of fixableDiagnostics) {
- results.push(...(yield this.getFixesForDiagnostic(document, file, diagnostic, token)));
- }
- return results;
- });
- }
- getFixesForDiagnostic(document, file, diagnostic, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, diagnostic.range)), { errorCodes: [+diagnostic.code] });
- const codeFixesResponse = yield this.client.execute('getCodeFixes', args, token);
- if (codeFixesResponse.type != 'response') {
- return [];
- }
- if (codeFixesResponse.body) {
- const results = [];
- for (const tsCodeFix of codeFixesResponse.body) {
- results.push(...(yield this.getAllFixesForTsCodeAction(document, file, diagnostic, tsCodeFix)));
- }
- return results;
- }
- return [];
- });
- }
- getAllFixesForTsCodeAction(document, file, diagnostic, tsAction) {
- return __awaiter(this, void 0, void 0, function* () {
- const singleFix = this.getSingleFixForTsCodeAction(diagnostic, tsAction);
- const fixAll = yield this.getFixAllForTsCodeAction(document, file, diagnostic, tsAction);
- return fixAll ? [singleFix, fixAll] : [singleFix];
- });
- }
- getSingleFixForTsCodeAction(diagnostic, tsAction) {
- const codeAction = {
- title: tsAction.description,
- kind: vscode_languageserver_protocol_1.CodeActionKind.QuickFix
- };
- codeAction.edit = codeAction_1.getEditForCodeAction(this.client, tsAction);
- codeAction.diagnostics = [diagnostic];
- codeAction.isPrefered = true;
- if (tsAction.commands) {
- codeAction.command = {
- command: ApplyCodeActionCommand.ID,
- arguments: [tsAction],
- title: tsAction.description
- };
- }
- return codeAction;
- }
- getFixAllForTsCodeAction(document, file, diagnostic, tsAction) {
- return __awaiter(this, void 0, void 0, function* () {
- if (!tsAction.fixId || !this.client.apiVersion.gte(api_1.default.v270)) {
- return undefined;
- }
- // Make sure there are multiple diagnostics of the same type in the file
- if (!this.client.diagnosticsManager
- .getDiagnostics(document.uri)
- .some(x => x.code === diagnostic.code && x !== diagnostic)) {
- return;
- }
- const action = {
- title: tsAction.fixAllDescription || 'Fix all in file',
- kind: vscode_languageserver_protocol_1.CodeActionKind.QuickFix
- };
- action.diagnostics = [diagnostic];
- action.command = {
- command: ApplyFixAllCodeAction.ID,
- arguments: [file, tsAction],
- title: ''
- };
- return action;
- });
- }
- }
- exports.default = TypeScriptQuickFixProvider;
-
-
- /***/ }),
- /* 99 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- const coc_nvim_1 = __webpack_require__(1);
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- const helper_1 = __webpack_require__(100);
- class ImportFixProvider {
- constructor(bufferSyncSupport) {
- this.bufferSyncSupport = bufferSyncSupport;
- }
- provideCodeActions(document, _range, context, _token) {
- return __awaiter(this, void 0, void 0, function* () {
- if (this.bufferSyncSupport.hasPendingDiagnostics(document.uri)) {
- return [];
- }
- let diagnostics = context.diagnostics.filter(d => d.code == 2304);
- if (!diagnostics.length)
- return [];
- let edits = [];
- let names = [];
- let doc = coc_nvim_1.workspace.getDocument(document.uri);
- let command;
- for (const diagnostic of diagnostics) {
- let { range } = diagnostic;
- let line = doc.getline(range.start.line);
- let name = line.slice(range.start.character, range.end.character);
- if (names.indexOf(name) !== -1)
- continue;
- if (helper_1.nodeModules.indexOf(name) !== -1) {
- names.push(name);
- edits.push({
- range: vscode_languageserver_protocol_1.Range.create(0, 0, 0, 0),
- newText: `import ${name} from '${name}'\n`
- });
- command = 'tsserver.organizeImports';
- }
- }
- let edit = {
- changes: {
- [document.uri]: edits
- }
- };
- let cmd = null;
- if (command)
- cmd = {
- title: `fix import`,
- command: 'tsserver.organizeImports'
- };
- return [{
- title: `Add import ${names.join(', ')}`,
- edit,
- command: cmd
- }];
- });
- }
- }
- exports.default = ImportFixProvider;
-
-
- /***/ }),
- /* 100 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.nodeModules = void 0;
- exports.nodeModules = [
- 'assert',
- 'cluster',
- 'crypto',
- 'dns',
- 'domain',
- 'events',
- 'fs',
- 'http',
- 'http2',
- 'https',
- 'inspector',
- 'net',
- 'os',
- 'path',
- 'punycode',
- 'querystring',
- 'readline',
- 'repl',
- 'stream',
- 'string_decoder',
- 'tls',
- 'tty',
- 'url',
- 'util',
- 'v8',
- 'vm',
- 'zlib',
- 'perf_hooks'
- ];
-
-
- /***/ }),
- /* 101 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- const coc_nvim_1 = __webpack_require__(1);
- const typeConverters = __importStar(__webpack_require__(37));
- class ApplyRefactoringCommand {
- constructor(client) {
- this.client = client;
- this.id = ApplyRefactoringCommand.ID;
- }
- execute(document, file, refactor, action, range) {
- return __awaiter(this, void 0, void 0, function* () {
- const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, range)), { refactor,
- action });
- const response = yield this.client.execute('getEditsForRefactor', args, vscode_languageserver_protocol_1.CancellationToken.None);
- const body = response && response.body;
- if (!body || !body.edits.length) {
- return false;
- }
- const workspaceEdit = yield this.toWorkspaceEdit(body);
- if (!(yield coc_nvim_1.workspace.applyEdit(workspaceEdit))) {
- return false;
- }
- const renameLocation = body.renameLocation;
- if (renameLocation) {
- coc_nvim_1.commands.executeCommand('editor.action.rename', document.uri, typeConverters.Position.fromLocation(renameLocation));
- }
- return true;
- });
- }
- toWorkspaceEdit(body) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const edit of body.edits) {
- yield coc_nvim_1.workspace.createFile(edit.fileName, { ignoreIfExists: true });
- }
- let workspaceEdit = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, body.edits);
- return workspaceEdit;
- });
- }
- }
- ApplyRefactoringCommand.ID = '_typescript.applyRefactoring';
- class SelectRefactorCommand {
- constructor(doRefactoring) {
- this.doRefactoring = doRefactoring;
- this.id = SelectRefactorCommand.ID;
- }
- execute(document, file, info, range) {
- return __awaiter(this, void 0, void 0, function* () {
- let { actions } = info;
- const idx = actions.length == 1 ? 0 : yield coc_nvim_1.workspace.showQuickpick(actions.map(action => action.description || action.name));
- if (idx == -1)
- return false;
- let label = info.actions[idx].name;
- if (!label)
- return false;
- return this.doRefactoring.execute(document, file, info.name, label, range);
- });
- }
- }
- SelectRefactorCommand.ID = '_typescript.selectRefactoring';
- class TypeScriptRefactorProvider {
- constructor(client, formattingOptionsManager) {
- this.client = client;
- this.formattingOptionsManager = formattingOptionsManager;
- const doRefactoringCommand = coc_nvim_1.commands.register(new ApplyRefactoringCommand(this.client));
- coc_nvim_1.commands.register(new SelectRefactorCommand(doRefactoringCommand));
- }
- provideCodeActions(document, range, context, token) {
- return __awaiter(this, void 0, void 0, function* () {
- if (!this.shouldTrigger(context)) {
- return undefined;
- }
- const file = this.client.toPath(document.uri);
- if (!file)
- return undefined;
- yield this.formattingOptionsManager.ensureConfigurationForDocument(document);
- const args = typeConverters.Range.toFileRangeRequestArgs(file, range);
- let response;
- try {
- response = yield this.client.interruptGetErr(() => {
- return this.client.execute('getApplicableRefactors', args, token);
- });
- if (!response || !response.body) {
- return undefined;
- }
- }
- catch (_a) {
- return undefined;
- }
- return this.convertApplicableRefactors(response.body, document, file, range);
- });
- }
- convertApplicableRefactors(body, document, file, rangeOrSelection) {
- const actions = [];
- for (const info of body) {
- if (!info.inlineable) {
- const codeAction = {
- title: info.description,
- kind: vscode_languageserver_protocol_1.CodeActionKind.Refactor
- };
- codeAction.command = {
- title: info.description,
- command: SelectRefactorCommand.ID,
- arguments: [document, file, info, rangeOrSelection]
- };
- actions.push(codeAction);
- }
- else {
- for (const action of info.actions) {
- actions.push(this.refactorActionToCodeAction(action, document, file, info, rangeOrSelection));
- }
- }
- }
- return actions;
- }
- refactorActionToCodeAction(action, document, file, info, rangeOrSelection) {
- const codeAction = {
- title: action.description,
- kind: TypeScriptRefactorProvider.getKind(action)
- };
- codeAction.command = {
- title: action.description,
- command: ApplyRefactoringCommand.ID,
- arguments: [document, file, info.name, action.name, rangeOrSelection]
- };
- return codeAction;
- }
- shouldTrigger(context) {
- if (context.only &&
- context.only.indexOf(vscode_languageserver_protocol_1.CodeActionKind.Refactor) == -1) {
- return false;
- }
- return true;
- }
- static getKind(refactor) {
- if (refactor.name.startsWith('function_')) {
- return TypeScriptRefactorProvider.extractFunctionKind;
- }
- else if (refactor.name.startsWith('constant_')) {
- return TypeScriptRefactorProvider.extractConstantKind;
- }
- else if (refactor.name.startsWith('Move')) {
- return TypeScriptRefactorProvider.moveKind;
- }
- return vscode_languageserver_protocol_1.CodeActionKind.Refactor;
- }
- }
- exports.default = TypeScriptRefactorProvider;
- TypeScriptRefactorProvider.extractFunctionKind = vscode_languageserver_protocol_1.CodeActionKind.RefactorExtract + '.function';
- TypeScriptRefactorProvider.extractConstantKind = vscode_languageserver_protocol_1.CodeActionKind.RefactorExtract + '.constant';
- TypeScriptRefactorProvider.moveKind = vscode_languageserver_protocol_1.CodeActionKind.Refactor + '.move';
- TypeScriptRefactorProvider.metadata = {
- providedCodeActionKinds: [vscode_languageserver_protocol_1.CodeActionKind.Refactor]
- };
-
-
- /***/ }),
- /* 102 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- const typeConverters = __importStar(__webpack_require__(37));
- class TypeScriptReferences {
- constructor(client) {
- this.client = client;
- }
- provideReferences(document, position, context, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const filepath = this.client.toPath(document.uri);
- if (!filepath)
- return [];
- const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
- try {
- const msg = yield this.client.execute('references', args, token);
- if (!msg || msg.type != 'response' || !msg.body) {
- return [];
- }
- const result = [];
- for (const ref of msg.body.refs) {
- if (!context.includeDeclaration && ref.isDefinition) {
- continue;
- }
- const url = this.client.toResource(ref.file);
- const location = typeConverters.Location.fromTextSpan(url, ref);
- result.push(location);
- }
- return result;
- }
- catch (_a) {
- return [];
- }
- });
- }
- }
- exports.default = TypeScriptReferences;
-
-
- /***/ }),
- /* 103 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- const PConst = __importStar(__webpack_require__(39));
- const typeConverters = __importStar(__webpack_require__(37));
- const baseCodeLensProvider_1 = __webpack_require__(35);
- class TypeScriptReferencesCodeLensProvider extends baseCodeLensProvider_1.TypeScriptBaseCodeLensProvider {
- resolveCodeLens(codeLens, token) {
- let { uri } = codeLens.data;
- let filepath = this.client.toPath(uri);
- const args = typeConverters.Position.toFileLocationRequestArgs(filepath, codeLens.range.start);
- return this.client
- .execute('references', args, token, true)
- .then(response => {
- if (!response || response.type != 'response' || !response.body) {
- throw codeLens;
- }
- const locations = response.body.refs
- .map(reference => typeConverters.Location.fromTextSpan(this.client.toResource(reference.file), reference))
- .filter(location =>
- // Exclude original definition from references
- !(location.uri.toString() === uri &&
- location.range.start.line === codeLens.range.start.line &&
- location.range.start.character ===
- codeLens.range.start.character));
- codeLens.command = {
- title: locations.length === 1 ? '1 reference' : `${locations.length} references`,
- command: locations.length ? 'editor.action.showReferences' : '',
- arguments: [uri, codeLens.range.start, locations]
- };
- return codeLens;
- })
- .catch(() => {
- codeLens.command = {
- title: '0 references',
- command: ''
- };
- return codeLens;
- });
- }
- extractSymbol(document, item, parent) {
- if (parent && parent.kind === PConst.Kind.enum) {
- return super.getSymbolRange(document, item);
- }
- switch (item.kind) {
- case PConst.Kind.const:
- case PConst.Kind.let:
- case PConst.Kind.variable:
- case PConst.Kind.function:
- // Only show references for exported variables
- if (!item.kindModifiers.match(/\bexport\b/)) {
- break;
- }
- // fallthrough
- case PConst.Kind.class:
- if (item.text === '<class>') {
- break;
- }
- // fallthrough
- case PConst.Kind.method:
- case PConst.Kind.memberVariable:
- case PConst.Kind.memberGetAccessor:
- case PConst.Kind.memberSetAccessor:
- case PConst.Kind.constructorImplementation:
- case PConst.Kind.interface:
- case PConst.Kind.type:
- case PConst.Kind.enum:
- return super.getSymbolRange(document, item);
- }
- return null;
- }
- }
- exports.default = TypeScriptReferencesCodeLensProvider;
-
-
- /***/ }),
- /* 104 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const coc_nvim_1 = __webpack_require__(1);
- const path_1 = __importDefault(__webpack_require__(13));
- const api_1 = __importDefault(__webpack_require__(40));
- const typeConverters = __importStar(__webpack_require__(37));
- class TypeScriptRenameProvider {
- constructor(client) {
- this.client = client;
- }
- prepareRename(document, position, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const response = yield this.execRename(document, position, token);
- if (!response || response.type !== 'response' || !response.body) {
- return null;
- }
- const renameInfo = response.body.info;
- if (!renameInfo.canRename) {
- return Promise.reject(new Error('Invalid location for rename.'));
- }
- if (this.client.apiVersion.gte(api_1.default.v310)) {
- const triggerSpan = renameInfo.triggerSpan;
- if (triggerSpan) {
- const range = typeConverters.Range.fromTextSpan(triggerSpan);
- return range;
- }
- }
- return null;
- });
- }
- provideRenameEdits(document, position, newName, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const response = yield this.execRename(document, position, token);
- if (!response || response.type !== 'response' || !response.body) {
- return null;
- }
- const renameInfo = response.body.info;
- if (!renameInfo.canRename) {
- return Promise.reject(new Error('Invalid location for rename.'));
- }
- if (this.client.apiVersion.gte(api_1.default.v310)) {
- if (renameInfo.fileToRename) {
- const edits = yield this.renameFile(renameInfo.fileToRename, newName, token);
- if (edits) {
- return edits;
- }
- else {
- return Promise.reject(new Error('An error occurred while renaming file'));
- }
- }
- }
- return this.toWorkspaceEdit(response.body.locs, newName);
- });
- }
- execRename(document, position, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const file = this.client.toPath(document.uri);
- if (!file)
- return undefined;
- const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { findInStrings: false, findInComments: false });
- return this.client.interruptGetErr(() => {
- return this.client.execute('rename', args, token);
- });
- });
- }
- toWorkspaceEdit(locations, newName) {
- let changes = {};
- for (const spanGroup of locations) {
- const uri = this.client.toResource(spanGroup.file);
- if (uri) {
- changes[uri] = [];
- for (const textSpan of spanGroup.locs) {
- changes[uri].push({
- range: typeConverters.Range.fromTextSpan(textSpan),
- newText: (textSpan.prefixText || '') + newName + (textSpan.suffixText || '')
- });
- }
- }
- }
- return { changes };
- }
- renameFile(fileToRename, newName, token) {
- return __awaiter(this, void 0, void 0, function* () {
- // Make sure we preserve file exension if none provided
- if (!path_1.default.extname(newName)) {
- newName += path_1.default.extname(fileToRename);
- }
- const dirname = path_1.default.dirname(fileToRename);
- const newFilePath = path_1.default.join(dirname, newName);
- const args = {
- file: fileToRename,
- oldFilePath: fileToRename,
- newFilePath
- };
- const response = yield this.client.execute('getEditsForFileRename', args, token);
- if (response.type !== 'response' || !response.body) {
- return undefined;
- }
- const edits = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, response.body);
- edits.documentChanges = edits.documentChanges || [];
- edits.documentChanges.push({
- kind: 'rename',
- oldUri: coc_nvim_1.Uri.file(fileToRename).toString(),
- newUri: coc_nvim_1.Uri.file(newFilePath).toString(),
- options: {
- overwrite: false,
- ignoreIfExists: true
- }
- });
- return edits;
- });
- }
- }
- exports.default = TypeScriptRenameProvider;
-
-
- /***/ }),
- /* 105 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- const Previewer = __importStar(__webpack_require__(86));
- const typeConverters = __importStar(__webpack_require__(37));
- class TypeScriptSignatureHelpProvider {
- constructor(client) {
- this.client = client;
- }
- provideSignatureHelp(document, position, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const filepath = this.client.toPath(document.uri);
- if (!filepath) {
- return undefined;
- }
- const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
- let response;
- try {
- response = yield this.client.interruptGetErr(() => this.client.execute('signatureHelp', args, token));
- }
- catch (e) {
- return undefined;
- }
- if (response.type !== 'response' || !response.body) {
- return undefined;
- }
- let info = response.body;
- const result = {
- activeSignature: info.selectedItemIndex,
- activeParameter: this.getActiveParmeter(info),
- signatures: info.items.map(signature => {
- return this.convertSignature(signature);
- })
- };
- return result;
- });
- }
- getActiveParmeter(info) {
- const activeSignature = info.items[info.selectedItemIndex];
- if (activeSignature && activeSignature.isVariadic) {
- return Math.min(info.argumentIndex, activeSignature.parameters.length - 1);
- }
- return info.argumentIndex;
- }
- convertSignature(item) {
- let parameters = item.parameters.map(p => {
- return {
- label: Previewer.plain(p.displayParts),
- documentation: Previewer.markdownDocumentation(p.documentation, [])
- };
- });
- let label = Previewer.plain(item.prefixDisplayParts);
- label += parameters.map(parameter => parameter.label).join(Previewer.plain(item.separatorDisplayParts));
- label += Previewer.plain(item.suffixDisplayParts);
- return {
- label,
- documentation: Previewer.markdownDocumentation(item.documentation, item.tags.filter(x => x.name !== 'param')),
- parameters
- };
- }
- }
- exports.default = TypeScriptSignatureHelpProvider;
- TypeScriptSignatureHelpProvider.triggerCharacters = ['(', ',', '<'];
-
-
- /***/ }),
- /* 106 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- const coc_nvim_1 = __webpack_require__(1);
- const typeConverters = __importStar(__webpack_require__(37));
- const mutex_1 = __webpack_require__(107);
- function wait(ms) {
- return new Promise(resolve => {
- setTimeout(() => {
- resolve();
- }, ms);
- });
- }
- class UpdateImportsOnFileRenameHandler {
- constructor(client, fileConfigurationManager, languageId) {
- this.client = client;
- this.fileConfigurationManager = fileConfigurationManager;
- this.disposables = [];
- let glob = languageId == 'typescript' ? '**/*.{ts,tsx}' : '**/*.{js,jsx}';
- const watcher = coc_nvim_1.workspace.createFileSystemWatcher(glob);
- this.disposables.push(watcher);
- let mutex = new mutex_1.Mutex();
- watcher.onDidRename((e) => __awaiter(this, void 0, void 0, function* () {
- let release = yield mutex.acquire();
- try {
- yield this.doRename(e.oldUri, e.newUri);
- release();
- }
- catch (e) {
- this.client.logger.error('Error on rename:', e);
- release();
- }
- }), null, this.disposables);
- }
- dispose() {
- coc_nvim_1.disposeAll(this.disposables);
- }
- doRename(oldResource, newResource) {
- return __awaiter(this, void 0, void 0, function* () {
- if (oldResource.scheme !== 'file' || newResource.scheme !== 'file') {
- return;
- }
- const targetFile = newResource.fsPath;
- const oldFile = oldResource.fsPath;
- const newUri = newResource.toString();
- let oldDocument = coc_nvim_1.workspace.getDocument(oldResource.toString());
- if (oldDocument) {
- yield coc_nvim_1.workspace.nvim.command(`silent ${oldDocument.bufnr}bwipeout!`);
- }
- let document = coc_nvim_1.workspace.getDocument(newUri);
- if (document) {
- yield coc_nvim_1.workspace.nvim.command(`silent ${document.bufnr}bwipeout!`);
- yield wait(30);
- }
- document = yield coc_nvim_1.workspace.loadFile(newUri);
- if (!document)
- return;
- yield wait(50);
- const edits = yield this.getEditsForFileRename(document.textDocument, oldFile, targetFile);
- if (!edits)
- return;
- if (yield this.promptUser(newResource)) {
- yield coc_nvim_1.workspace.applyEdit(edits);
- }
- });
- }
- promptUser(newResource) {
- return __awaiter(this, void 0, void 0, function* () {
- return yield coc_nvim_1.workspace.showPrompt(`Update imports for moved file: ${newResource.fsPath}?`);
- });
- }
- getEditsForFileRename(document, oldFile, newFile) {
- return __awaiter(this, void 0, void 0, function* () {
- yield this.fileConfigurationManager.ensureConfigurationForDocument(document);
- const response = yield this.client.interruptGetErr(() => {
- const args = {
- oldFilePath: oldFile,
- newFilePath: newFile,
- };
- return this.client.execute('getEditsForFileRename', args, vscode_languageserver_protocol_1.CancellationToken.None);
- });
- if (!response || response.type != 'response' || !response.body) {
- return;
- }
- const edits = [];
- for (const edit of response.body) {
- // Workaround for https://github.com/Microsoft/vscode/issues/52675
- if (edit.fileName.match(/[\/\\]node_modules[\/\\]/gi)) {
- continue;
- }
- for (const change of edit.textChanges) {
- if (change.newText.match(/\/node_modules\//gi)) {
- continue;
- }
- }
- edits.push(edit);
- }
- return typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, edits);
- });
- }
- }
- exports.default = UpdateImportsOnFileRenameHandler;
-
-
- /***/ }),
- /* 107 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.Mutex = void 0;
- class Mutex {
- constructor() {
- this.tasks = [];
- this.count = 1;
- }
- sched() {
- if (this.count > 0 && this.tasks.length > 0) {
- this.count--;
- let next = this.tasks.shift();
- next();
- }
- }
- get busy() {
- return this.count == 0;
- }
- // tslint:disable-next-line: typedef
- acquire() {
- return new Promise(res => {
- let task = () => {
- let released = false;
- res(() => {
- if (!released) {
- released = true;
- this.count++;
- this.sched();
- }
- });
- };
- this.tasks.push(task);
- process.nextTick(this.sched.bind(this));
- });
- }
- use(f) {
- return this.acquire()
- .then(release => {
- return f()
- .then(res => {
- release();
- return res;
- })
- .catch(err => {
- release();
- throw err;
- });
- });
- }
- }
- exports.Mutex = Mutex;
-
-
- /***/ }),
- /* 108 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- const coc_nvim_1 = __webpack_require__(1);
- const path_1 = __importDefault(__webpack_require__(13));
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- const countRegex = /Found\s+(\d+)\s+error/;
- const errorRegex = /^(.+)\((\d+),(\d+)\):\s(\w+)\sTS(\d+):\s*(.+)$/;
- var TscStatus;
- (function (TscStatus) {
- TscStatus[TscStatus["INIT"] = 0] = "INIT";
- TscStatus[TscStatus["COMPILING"] = 1] = "COMPILING";
- TscStatus[TscStatus["RUNNING"] = 2] = "RUNNING";
- TscStatus[TscStatus["ERROR"] = 3] = "ERROR";
- })(TscStatus || (TscStatus = {}));
- class WatchProject {
- constructor(commandManager, client) {
- this.client = client;
- this.disposables = [];
- this.statusItem = coc_nvim_1.workspace.createStatusBarItem(1, { progress: true });
- let task = this.task = coc_nvim_1.workspace.createTask('TSC');
- this.disposables.push(commandManager.registerCommand(WatchProject.id, () => __awaiter(this, void 0, void 0, function* () {
- let opts = this.options = yield this.getOptions();
- yield this.start(opts);
- })));
- task.onExit(code => {
- if (code != 0) {
- coc_nvim_1.workspace.showMessage(`TSC exit with code ${code}`, 'warning');
- }
- this.onStop();
- });
- task.onStdout(lines => {
- for (let line of lines) {
- this.onLine(line);
- }
- });
- task.onStderr(lines => {
- coc_nvim_1.workspace.showMessage(`TSC error: ` + lines.join('\n'), 'error');
- });
- this.disposables.push(vscode_languageserver_protocol_1.Disposable.create(() => {
- task.dispose();
- }));
- this.check().catch(_e => {
- // noop
- });
- }
- check() {
- return __awaiter(this, void 0, void 0, function* () {
- let running = yield this.task.running;
- if (running) {
- this.options = yield this.getOptions();
- this.statusItem.isProgress = false;
- this.statusItem.text = '?';
- this.statusItem.show();
- }
- else {
- this.onStop();
- }
- });
- }
- start(options) {
- return __awaiter(this, void 0, void 0, function* () {
- yield this.task.start(options);
- });
- }
- onStop() {
- this.statusItem.hide();
- }
- onStart() {
- this.statusItem.text = 'compiling';
- this.statusItem.isProgress = true;
- this.statusItem.show();
- coc_nvim_1.workspace.nvim.call('setqflist', [[]], true);
- }
- onLine(line) {
- if (countRegex.test(line)) {
- let ms = line.match(countRegex);
- this.statusItem.text = ms[1] == '0' ? '✓' : '✗';
- this.statusItem.isProgress = false;
- }
- else if (WatchProject.startTexts.findIndex(s => line.indexOf(s) !== -1) != -1) {
- this.onStart();
- }
- else {
- let ms = line.match(errorRegex);
- if (!ms)
- return;
- let fullpath = path_1.default.join(this.options.cwd, ms[1]);
- let uri = coc_nvim_1.Uri.file(fullpath).toString();
- let doc = coc_nvim_1.workspace.getDocument(uri);
- let bufnr = doc ? doc.bufnr : null;
- let item = {
- filename: fullpath,
- lnum: Number(ms[2]),
- col: Number(ms[3]),
- text: `[tsc ${ms[5]}] ${ms[6]}`,
- type: /error/i.test(ms[4]) ? 'E' : 'W'
- };
- if (bufnr)
- item.bufnr = bufnr;
- coc_nvim_1.workspace.nvim.call('setqflist', [[item], 'a']);
- }
- }
- getOptions() {
- return __awaiter(this, void 0, void 0, function* () {
- let { tscPath } = this.client;
- if (!tscPath) {
- coc_nvim_1.workspace.showMessage(`Local & global tsc not found`, 'error');
- return;
- }
- let find = yield coc_nvim_1.workspace.findUp(['tsconfig.json']);
- if (!find) {
- coc_nvim_1.workspace.showMessage('tsconfig.json not found!', 'error');
- return;
- }
- let root = path_1.default.dirname(find);
- return {
- cmd: tscPath,
- args: ['-p', 'tsconfig.json', '--watch', 'true', '--pretty', 'false'],
- cwd: root
- };
- });
- }
- dispose() {
- coc_nvim_1.disposeAll(this.disposables);
- }
- }
- exports.default = WatchProject;
- WatchProject.id = 'tsserver.watchBuild';
- WatchProject.startTexts = ['Starting compilation in watch mode', 'Starting incremental compilation'];
-
-
- /***/ }),
- /* 109 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- const coc_nvim_1 = __webpack_require__(1);
- const typeConverters = __importStar(__webpack_require__(37));
- const api_1 = __importDefault(__webpack_require__(40));
- function getSymbolKind(item) {
- switch (item.kind) {
- case 'method':
- return vscode_languageserver_protocol_1.SymbolKind.Method;
- case 'enum':
- return vscode_languageserver_protocol_1.SymbolKind.Enum;
- case 'function':
- return vscode_languageserver_protocol_1.SymbolKind.Function;
- case 'class':
- return vscode_languageserver_protocol_1.SymbolKind.Class;
- case 'interface':
- return vscode_languageserver_protocol_1.SymbolKind.Interface;
- case 'var':
- return vscode_languageserver_protocol_1.SymbolKind.Variable;
- default:
- return vscode_languageserver_protocol_1.SymbolKind.Variable;
- }
- }
- class TypeScriptWorkspaceSymbolProvider {
- constructor(client, languageIds) {
- this.client = client;
- this.languageIds = languageIds;
- }
- provideWorkspaceSymbols(search, token) {
- return __awaiter(this, void 0, void 0, function* () {
- let filepath;
- if (this.searchAllOpenProjects) {
- filepath = undefined;
- }
- else {
- let uri = this.getUri();
- filepath = uri ? this.client.toPath(uri) : undefined;
- if (!filepath && this.client.apiVersion.lt(api_1.default.v390)) {
- return [];
- }
- }
- const args = {
- file: filepath,
- searchValue: search,
- maxResultCount: 256,
- };
- const response = yield this.client.execute('navto', args, token);
- if (response.type !== 'response' || response.body == null)
- return [];
- const result = [];
- for (const item of response.body) {
- if (!item.containerName && item.kind === 'alias') {
- continue;
- }
- const label = TypeScriptWorkspaceSymbolProvider.getLabel(item);
- const range = {
- start: typeConverters.Position.fromLocation(item.start),
- end: typeConverters.Position.fromLocation(item.end),
- };
- const symbolInfo = vscode_languageserver_protocol_1.SymbolInformation.create(label, getSymbolKind(item), range, this.client.toResource(item.file));
- result.push(symbolInfo);
- }
- return result;
- });
- }
- static getLabel(item) {
- let label = item.name;
- if (item.kind === 'method' || item.kind === 'function') {
- label += '()';
- }
- return label;
- }
- getUri() {
- // typescript wants to have a resource even when asking
- // general questions so we check the active editor. If this
- // doesn't match we take the first TS document.
- const documents = coc_nvim_1.workspace.textDocuments;
- for (const document of documents) {
- if (this.languageIds.indexOf(document.languageId) >= 0) {
- return document.uri;
- }
- }
- return undefined;
- }
- get searchAllOpenProjects() {
- return this.client.apiVersion.gte(api_1.default.v390)
- && coc_nvim_1.workspace.getConfiguration('typescript').get('workspaceSymbols.scope', 'allOpenProjects') === 'allOpenProjects';
- }
- }
- exports.default = TypeScriptWorkspaceSymbolProvider;
-
-
- /***/ }),
- /* 110 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- const typeConverters = __importStar(__webpack_require__(37));
- class SmartSelection {
- constructor(client) {
- this.client = client;
- }
- provideSelectionRanges(document, positions, token) {
- return __awaiter(this, void 0, void 0, function* () {
- const file = this.client.toPath(document.uri);
- if (!file) {
- return undefined;
- }
- const args = {
- file,
- locations: positions.map(typeConverters.Position.toLocation)
- };
- const response = yield this.client.execute('selectionRange', args, token);
- if (response.type !== 'response' || !response.body) {
- return undefined;
- }
- return response.body.map(SmartSelection.convertSelectionRange);
- });
- }
- static convertSelectionRange(selectionRange) {
- return {
- range: typeConverters.Range.fromTextSpan(selectionRange.textSpan),
- parent: selectionRange.parent ? SmartSelection.convertSelectionRange(selectionRange.parent) : undefined,
- };
- }
- }
- exports.default = SmartSelection;
-
-
- /***/ }),
- /* 111 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- const coc_nvim_1 = __webpack_require__(1);
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- const modules_1 = __webpack_require__(112);
- class InstallModuleCommand {
- constructor() {
- this.id = InstallModuleCommand.ID;
- }
- execute(uri, name) {
- return __awaiter(this, void 0, void 0, function* () {
- yield modules_1.installModules(uri, [name]);
- });
- }
- }
- InstallModuleCommand.ID = '_tsserver.installModule';
- class InstallModuleProvider {
- constructor(client) {
- this.client = client;
- coc_nvim_1.commands.register(new InstallModuleCommand(), true);
- }
- provideCodeActions(document, _range, context, _token) {
- return __awaiter(this, void 0, void 0, function* () {
- const uri = coc_nvim_1.Uri.parse(document.uri);
- if (uri.scheme != 'file')
- return null;
- let { diagnostics } = context;
- let diags = diagnostics.filter(s => s.code == 2307);
- let names = diags.map(o => {
- let ms = o.message.match(/module\s'(.+)'\./);
- return ms ? ms[1] : null;
- });
- names = names.filter(s => s != null);
- if (!names.length)
- return null;
- let actions = [];
- for (let name of names) {
- let title = `install ${name}`;
- let command = {
- title: `install ${name}`,
- command: InstallModuleCommand.ID,
- arguments: [document.uri, name]
- };
- let codeAction = vscode_languageserver_protocol_1.CodeAction.create(title, command);
- actions.push(codeAction);
- }
- return actions;
- });
- }
- }
- exports.default = InstallModuleProvider;
-
-
- /***/ }),
- /* 112 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.installModules = exports.distinct = exports.moduleExists = exports.runCommand = void 0;
- const child_process_1 = __webpack_require__(113);
- const path_1 = __importDefault(__webpack_require__(13));
- const coc_nvim_1 = __webpack_require__(1);
- function runCommand(cmd, cwd, timeout) {
- return new Promise((resolve, reject) => {
- let timer;
- if (timeout) {
- timer = setTimeout(() => {
- reject(new Error(`timeout after ${timeout}s`));
- }, timeout * 1000);
- }
- child_process_1.exec(cmd, { cwd }, (err, stdout) => {
- if (timer)
- clearTimeout(timer);
- if (err) {
- reject(new Error(`exited with ${err.code}`));
- return;
- }
- resolve(stdout);
- });
- });
- }
- exports.runCommand = runCommand;
- function getManager() {
- return __awaiter(this, void 0, void 0, function* () {
- let res = yield coc_nvim_1.workspace.findUp(['yarn.lock', 'package-lock.json']);
- if (!res)
- return 'yarn';
- return res.endsWith('yarn.lock') ? 'yarn' : 'npm';
- });
- }
- function getRoot() {
- return __awaiter(this, void 0, void 0, function* () {
- let res = yield coc_nvim_1.workspace.findUp(['package.json']);
- if (!res)
- return null;
- return path_1.default.dirname(res);
- });
- }
- function moduleExists(name) {
- return __awaiter(this, void 0, void 0, function* () {
- try {
- let content = yield runCommand(`npm info ${name} --json`, process.cwd());
- if (!content)
- return false;
- let obj = JSON.parse(content);
- if (obj.error != null)
- return false;
- return true;
- }
- catch (e) {
- return false;
- }
- return false;
- });
- }
- exports.moduleExists = moduleExists;
- /**
- * Removes duplicates from the given array. The optional keyFn allows to specify
- * how elements are checked for equalness by returning a unique string for each.
- */
- function distinct(array, keyFn) {
- if (!keyFn) {
- return array.filter((element, position) => {
- return array.indexOf(element) === position;
- });
- }
- const seen = Object.create(null);
- return array.filter(elem => {
- const key = keyFn(elem);
- if (seen[key]) {
- return false;
- }
- seen[key] = true;
- return true;
- });
- }
- exports.distinct = distinct;
- function installModules(uri, names) {
- return __awaiter(this, void 0, void 0, function* () {
- names = distinct(names);
- let root = yield getRoot();
- if (!root) {
- coc_nvim_1.workspace.showMessage(`package.json not found from cwd: ${coc_nvim_1.workspace.cwd}`, 'error');
- return;
- }
- let arr = names.concat(names.map(s => `@types/${s}`));
- let statusItem = coc_nvim_1.workspace.createStatusBarItem(99, { progress: true });
- statusItem.text = `Checking module ${arr.join(' ')}`;
- statusItem.show();
- let exists = yield Promise.all(arr.map(name => {
- return moduleExists(name).then(exists => {
- return exists ? name : null;
- });
- }));
- let manager = yield getManager();
- exists = exists.filter(s => s != null);
- if (!exists.length)
- return;
- let devs = exists.filter(s => s.startsWith('@types'));
- let deps = exists.filter(s => devs.indexOf(s) == -1);
- statusItem.text = `Installing ${exists.join(' ')}`;
- try {
- yield Promise.all([deps, devs].map((names, i) => {
- let cmd = manager == 'npm' ? `npm i ${names.join(' ')}` : `yarn add ${names.join(' ')} --ignore-scripts --no-default-rc`;
- if (i == 1)
- cmd = cmd + ' --dev';
- return runCommand(cmd, root);
- }));
- }
- catch (e) {
- statusItem.dispose();
- coc_nvim_1.workspace.showMessage(`Install error ${e.message}`, 'error');
- return;
- }
- statusItem.dispose();
- coc_nvim_1.workspace.showMessage(`Installed: ${exists.join(' ')}`, 'more');
- });
- }
- exports.installModules = installModules;
-
-
- /***/ }),
- /* 113 */
- /***/ (function(module, exports) {
-
- module.exports = require("child_process");
-
- /***/ }),
- /* 114 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.OrganizeImportsCodeActionProvider = exports.OrganizeImportsCommand = void 0;
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const coc_nvim_1 = __webpack_require__(1);
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- const languageDescription_1 = __webpack_require__(115);
- const languageModeIds_1 = __webpack_require__(116);
- const typeconverts = __importStar(__webpack_require__(37));
- class OrganizeImportsCommand {
- constructor(client) {
- this.client = client;
- this.id = 'tsserver.organizeImports';
- }
- getTextEdits(document) {
- return __awaiter(this, void 0, void 0, function* () {
- let client = this.client;
- let file = client.toPath(document.uri);
- const args = {
- scope: {
- type: 'file',
- args: {
- file
- }
- }
- };
- const response = yield this.client.interruptGetErr(() => this.client.execute('organizeImports', args, vscode_languageserver_protocol_1.CancellationToken.None));
- if (!response || response.type != 'response' || !response.success) {
- return;
- }
- const edit = typeconverts.WorkspaceEdit.fromFileCodeEdits(client, response.body);
- let desc = languageDescription_1.standardLanguageDescriptions.find(o => o.modeIds.indexOf(document.languageId) !== -1);
- if (!desc)
- return null;
- return edit;
- });
- }
- execute(document) {
- return __awaiter(this, void 0, void 0, function* () {
- if (!document) {
- let doc = yield coc_nvim_1.workspace.document;
- if (languageModeIds_1.languageIds.indexOf(doc.filetype) == -1)
- return;
- document = doc.textDocument;
- }
- let edit = yield this.getTextEdits(document);
- if (edit)
- yield coc_nvim_1.workspace.applyEdit(edit);
- return;
- });
- }
- }
- exports.OrganizeImportsCommand = OrganizeImportsCommand;
- class OrganizeImportsCodeActionProvider {
- // public static readonly minVersion = API.v280
- constructor(client, fileConfigManager) {
- this.client = client;
- this.fileConfigManager = fileConfigManager;
- this.metadata = {
- providedCodeActionKinds: [vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports]
- };
- }
- provideCodeActions(document, _range, context, _token) {
- if (languageModeIds_1.languageIds.indexOf(document.languageId) == -1)
- return;
- if (!context.only || !context.only.includes(vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports)) {
- return [];
- }
- const action = vscode_languageserver_protocol_1.CodeAction.create('Organize Imports', {
- title: '',
- command: 'tsserver.organizeImports',
- arguments: [document]
- }, vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports);
- return [action];
- }
- }
- exports.OrganizeImportsCodeActionProvider = OrganizeImportsCodeActionProvider;
-
-
- /***/ }),
- /* 115 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.standardLanguageDescriptions = void 0;
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const languageModeIds = __importStar(__webpack_require__(116));
- exports.standardLanguageDescriptions = [
- {
- id: 'typescript',
- diagnosticSource: 'ts',
- diagnosticOwner: 'typescript',
- modeIds: [languageModeIds.typescript, languageModeIds.typescriptreact,
- languageModeIds.typescripttsx, languageModeIds.typescriptjsx],
- diagnosticLanguage: 1 /* TypeScript */,
- configFile: 'tsconfig.json'
- },
- {
- id: 'javascript',
- diagnosticSource: 'ts',
- diagnosticOwner: 'typescript',
- modeIds: [languageModeIds.javascript, languageModeIds.javascriptreact],
- diagnosticLanguage: 0 /* JavaScript */,
- configFile: 'jsconfig.json'
- }
- ];
-
-
- /***/ }),
- /* 116 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.languageIds = exports.jsxTags = exports.javascriptjsx = exports.javascriptreact = exports.javascript = exports.typescriptjsx = exports.typescripttsx = exports.typescriptreact = exports.typescript = void 0;
- exports.typescript = 'typescript';
- exports.typescriptreact = 'typescriptreact';
- exports.typescripttsx = 'typescript.tsx';
- exports.typescriptjsx = 'typescript.jsx';
- exports.javascript = 'javascript';
- exports.javascriptreact = 'javascriptreact';
- exports.javascriptjsx = 'javascript.jsx';
- exports.jsxTags = 'jsx-tags';
- exports.languageIds = [exports.typescript, exports.typescriptreact, exports.javascript, exports.javascriptreact, exports.javascriptjsx, exports.typescripttsx, exports.jsxTags];
-
-
- /***/ }),
- /* 117 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- const fs_1 = __importDefault(__webpack_require__(118));
- const os_1 = __importDefault(__webpack_require__(14));
- const path_1 = __importDefault(__webpack_require__(13));
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- const which_1 = __importDefault(__webpack_require__(119));
- const coc_nvim_1 = __webpack_require__(1);
- const fileConfigurationManager_1 = __importDefault(__webpack_require__(93));
- const typescriptService_1 = __webpack_require__(123);
- const api_1 = __importDefault(__webpack_require__(40));
- const configuration_1 = __webpack_require__(124);
- const logger_1 = __importDefault(__webpack_require__(125));
- const process_1 = __webpack_require__(127);
- const tracer_1 = __importDefault(__webpack_require__(128));
- const tsconfig_1 = __webpack_require__(129);
- const versionProvider_1 = __webpack_require__(130);
- const versionStatus_1 = __importDefault(__webpack_require__(131));
- const wireProtocol_1 = __webpack_require__(132);
- const callbackMap_1 = __webpack_require__(133);
- const requestQueue_1 = __webpack_require__(134);
- const bufferSyncSupport_1 = __importDefault(__webpack_require__(135));
- const diagnostics_1 = __webpack_require__(137);
- class ForkedTsServerProcess {
- constructor(childProcess) {
- this.childProcess = childProcess;
- }
- onError(cb) {
- this.childProcess.on('error', cb);
- }
- onExit(cb) {
- this.childProcess.on('exit', cb);
- }
- write(serverRequest) {
- this.childProcess.stdin.write(JSON.stringify(serverRequest) + '\r\n', 'utf8');
- }
- createReader(callback, onError) {
- // tslint:disable-next-line:no-unused-expression
- new wireProtocol_1.Reader(this.childProcess.stdout, callback, onError);
- }
- kill() {
- this.childProcess.kill();
- }
- }
- class TypeScriptServiceClient {
- constructor(pluginManager) {
- this.pluginManager = pluginManager;
- this.state = coc_nvim_1.ServiceStat.Initial;
- this.logger = new logger_1.default();
- this.tsServerLogFile = null;
- this.cancellationPipeName = null;
- this._callbacks = new callbackMap_1.CallbackMap();
- this._requestQueue = new requestQueue_1.RequestQueue();
- this._pendingResponses = new Set();
- this._onTsServerStarted = new vscode_languageserver_protocol_1.Emitter();
- this._onProjectLanguageServiceStateChanged = new vscode_languageserver_protocol_1.Emitter();
- this._onDidBeginInstallTypings = new vscode_languageserver_protocol_1.Emitter();
- this._onDidEndInstallTypings = new vscode_languageserver_protocol_1.Emitter();
- this._onTypesInstallerInitializationFailed = new vscode_languageserver_protocol_1.Emitter();
- this.disposables = [];
- this.isRestarting = false;
- this._onDiagnosticsReceived = new vscode_languageserver_protocol_1.Emitter();
- this._onConfigDiagnosticsReceived = new vscode_languageserver_protocol_1.Emitter();
- this._onResendModelsRequested = new vscode_languageserver_protocol_1.Emitter();
- this.pathSeparator = path_1.default.sep;
- this.lastStart = Date.now();
- this.servicePromise = null;
- this.lastError = null;
- this.numberRestarts = 0;
- this.fileConfigurationManager = new fileConfigurationManager_1.default(this);
- this._configuration = configuration_1.TypeScriptServiceConfiguration.loadFromWorkspace();
- this.versionProvider = new versionProvider_1.TypeScriptVersionProvider(this._configuration);
- this._apiVersion = api_1.default.defaultVersion;
- this.tracer = new tracer_1.default(this.logger);
- this.versionStatus = new versionStatus_1.default(this.normalizePath.bind(this), this.fileConfigurationManager.enableJavascript());
- pluginManager.onDidUpdateConfig(update => {
- this.configurePlugin(update.pluginId, update.config);
- }, null, this.disposables);
- pluginManager.onDidChangePlugins(() => {
- this.restartTsServer();
- }, null, this.disposables);
- this.bufferSyncSupport = new bufferSyncSupport_1.default(this);
- this.onTsServerStarted(() => {
- this.bufferSyncSupport.listen();
- });
- this.diagnosticsManager = new diagnostics_1.DiagnosticsManager();
- this.bufferSyncSupport.onDelete(resource => {
- this.diagnosticsManager.delete(resource);
- }, null, this.disposables);
- }
- get onDiagnosticsReceived() {
- return this._onDiagnosticsReceived.event;
- }
- get onConfigDiagnosticsReceived() {
- return this._onConfigDiagnosticsReceived.event;
- }
- get onResendModelsRequested() {
- return this._onResendModelsRequested.event;
- }
- get configuration() {
- return this._configuration;
- }
- dispose() {
- if (this.servicePromise) {
- this.servicePromise
- .then(childProcess => {
- childProcess.kill();
- })
- .then(undefined, () => void 0);
- }
- this.bufferSyncSupport.dispose();
- coc_nvim_1.disposeAll(this.disposables);
- this.logger.dispose();
- this._onTsServerStarted.dispose();
- this._onResendModelsRequested.dispose();
- this.versionStatus.dispose();
- }
- info(message, data) {
- this.logger.info(message, data);
- }
- error(message, data) {
- this.logger.error(message, data);
- }
- restartTsServer() {
- const start = () => {
- this.servicePromise = this.startService(true);
- return this.servicePromise;
- };
- if (this.servicePromise) {
- return Promise.resolve(this.servicePromise.then(childProcess => {
- this.state = coc_nvim_1.ServiceStat.Stopping;
- this.info('Killing TS Server');
- this.isRestarting = true;
- childProcess.kill();
- this.servicePromise = null;
- }).then(start));
- }
- else {
- return Promise.resolve(start());
- }
- }
- stop() {
- if (!this.servicePromise)
- return;
- return new Promise((resolve, reject) => {
- this.servicePromise.then(childProcess => {
- if (this.state == coc_nvim_1.ServiceStat.Running) {
- this.info('Killing TS Server');
- childProcess.onExit(() => {
- resolve();
- });
- childProcess.kill();
- this.servicePromise = null;
- }
- else {
- resolve();
- }
- }, reject);
- });
- }
- get onTsServerStarted() {
- return this._onTsServerStarted.event;
- }
- get onProjectLanguageServiceStateChanged() {
- return this._onProjectLanguageServiceStateChanged.event;
- }
- get onDidBeginInstallTypings() {
- return this._onDidBeginInstallTypings.event;
- }
- get onDidEndInstallTypings() {
- return this._onDidEndInstallTypings.event;
- }
- get onTypesInstallerInitializationFailed() {
- return this._onTypesInstallerInitializationFailed.event;
- }
- get apiVersion() {
- return this._apiVersion;
- }
- get tscPath() {
- return this._tscPath;
- }
- service() {
- if (this.servicePromise) {
- return this.servicePromise;
- }
- if (this.lastError) {
- return Promise.reject(this.lastError);
- }
- return this.startService().then(() => {
- if (this.servicePromise) {
- return this.servicePromise;
- }
- });
- }
- ensureServiceStarted() {
- if (!this.servicePromise) {
- this.startService().catch(err => {
- coc_nvim_1.workspace.showMessage(`TSServer start failed: ${err.message}`, 'error');
- this.error(`Service start failed: ${err.stack}`);
- });
- }
- }
- startService(resendModels = false) {
- return __awaiter(this, void 0, void 0, function* () {
- const { ignoreLocalTsserver } = this.configuration;
- let currentVersion;
- if (!ignoreLocalTsserver)
- currentVersion = this.versionProvider.getLocalVersion();
- if (!currentVersion || !fs_1.default.existsSync(currentVersion.tsServerPath)) {
- currentVersion = this.versionProvider.getDefaultVersion();
- }
- if (!currentVersion || !currentVersion.isValid) {
- if (this.configuration.globalTsdk) {
- coc_nvim_1.workspace.showMessage(`Can not find typescript module, in 'tsserver.tsdk': ${this.configuration.globalTsdk}`, 'error');
- }
- else {
- coc_nvim_1.workspace.showMessage(`Can not find typescript module, run ':CocInstall coc-tsserver' to fix it!`, 'error');
- }
- return;
- }
- this._apiVersion = currentVersion.version;
- this._tscPath = currentVersion.tscPath;
- this.versionStatus.onDidChangeTypeScriptVersion(currentVersion);
- this.lastError = null;
- const tsServerForkArgs = yield this.getTsServerArgs();
- const debugPort = this._configuration.debugPort;
- const maxTsServerMemory = this._configuration.maxTsServerMemory;
- const options = {
- execArgv: [
- ...(debugPort ? [`--inspect=${debugPort}`] : []),
- ...(maxTsServerMemory ? [`--max-old-space-size=${maxTsServerMemory}`] : []),
- ],
- cwd: coc_nvim_1.workspace.root
- };
- this.servicePromise = this.startProcess(currentVersion, tsServerForkArgs, options, resendModels);
- return this.servicePromise;
- });
- }
- startProcess(currentVersion, args, options, resendModels) {
- this.state = coc_nvim_1.ServiceStat.Starting;
- return new Promise((resolve, reject) => {
- try {
- process_1.fork(currentVersion.tsServerPath, args, options, this.logger, (err, childProcess) => {
- if (err || !childProcess) {
- this.state = coc_nvim_1.ServiceStat.StartFailed;
- this.lastError = err;
- this.error('Starting TSServer failed with error.', err.stack);
- return;
- }
- this.state = coc_nvim_1.ServiceStat.Running;
- this.info('Started TSServer', JSON.stringify(currentVersion, null, 2));
- const handle = new ForkedTsServerProcess(childProcess);
- this.lastStart = Date.now();
- handle.onError((err) => {
- this.lastError = err;
- this.error('TSServer errored with error.', err);
- this.error(`TSServer log file: ${this.tsServerLogFile || ''}`);
- coc_nvim_1.workspace.showMessage(`TSServer errored with error. ${err.message}`, 'error');
- this.serviceExited(false);
- });
- handle.onExit((code) => {
- if (code == null) {
- this.info('TSServer normal exit');
- }
- else {
- this.error(`TSServer exited with code: ${code}`);
- }
- this.info(`TSServer log file: ${this.tsServerLogFile || ''}`);
- this.serviceExited(!this.isRestarting);
- this.isRestarting = false;
- });
- handle.createReader(msg => {
- this.dispatchMessage(msg);
- }, error => {
- this.error('ReaderError', error);
- });
- resolve(handle);
- this.serviceStarted(resendModels);
- this._onTsServerStarted.fire(currentVersion.version);
- });
- }
- catch (e) {
- reject(e);
- }
- });
- }
- openTsServerLogFile() {
- return __awaiter(this, void 0, void 0, function* () {
- const isRoot = process.getuid && process.getuid() == 0;
- let echoErr = (msg) => {
- coc_nvim_1.workspace.showMessage(msg, 'error');
- };
- if (isRoot) {
- echoErr('Log disabled for root user.');
- return false;
- }
- if (!this.apiVersion.gte(api_1.default.v222)) {
- echoErr('TS Server logging requires TS 2.2.2+');
- return false;
- }
- if (this._configuration.tsServerLogLevel === configuration_1.TsServerLogLevel.Off) {
- echoErr(`TS Server logging is off. Change 'tsserver.log' in 'coc-settings.json' to enable`);
- return false;
- }
- if (!this.tsServerLogFile) {
- echoErr('TS Server has not started logging.');
- return false;
- }
- try {
- yield coc_nvim_1.workspace.nvim.command(`edit ${this.tsServerLogFile}`);
- return true;
- }
- catch (_a) {
- echoErr('Could not open TS Server log file');
- return false;
- }
- });
- }
- serviceStarted(resendModels) {
- const watchOptions = this.apiVersion.gte(api_1.default.v380)
- ? this.configuration.watchOptions
- : undefined;
- const configureOptions = {
- hostInfo: 'coc-nvim',
- preferences: {
- providePrefixAndSuffixTextForRename: true,
- allowRenameOfImportPath: true,
- },
- watchOptions
- };
- this.executeWithoutWaitingForResponse('configure', configureOptions); // tslint:disable-line
- this.setCompilerOptionsForInferredProjects(this._configuration);
- if (resendModels) {
- this._onResendModelsRequested.fire(void 0);
- this.diagnosticsManager.reInitialize();
- this.bufferSyncSupport.reinitialize();
- }
- // Reconfigure any plugins
- for (const [config, pluginName] of this.pluginManager.configurations()) {
- this.configurePlugin(config, pluginName);
- }
- }
- setCompilerOptionsForInferredProjects(configuration) {
- if (!this.apiVersion.gte(api_1.default.v206))
- return;
- const args = {
- options: this.getCompilerOptionsForInferredProjects(configuration)
- };
- this.executeWithoutWaitingForResponse('compilerOptionsForInferredProjects', args); // tslint:disable-line
- }
- getCompilerOptionsForInferredProjects(configuration) {
- return Object.assign(Object.assign({}, tsconfig_1.inferredProjectConfig(configuration)), { allowJs: true, allowSyntheticDefaultImports: true, allowNonTsExtensions: true });
- }
- serviceExited(restart) {
- this.state = coc_nvim_1.ServiceStat.Stopped;
- this.servicePromise = null;
- this.tsServerLogFile = null;
- this._callbacks.destroy('Service died.');
- this._callbacks = new callbackMap_1.CallbackMap();
- this._requestQueue = new requestQueue_1.RequestQueue();
- this._pendingResponses = new Set();
- if (restart) {
- const diff = Date.now() - this.lastStart;
- this.numberRestarts++;
- let startService = true;
- if (this.numberRestarts > 5) {
- this.numberRestarts = 0;
- if (diff < 10 * 1000 /* 10 seconds */) {
- this.lastStart = Date.now();
- startService = false;
- coc_nvim_1.workspace.showMessage('The TypeScript language service died 5 times right after it got started.', 'error'); // tslint:disable-line
- }
- else if (diff < 60 * 1000 /* 1 Minutes */) {
- this.lastStart = Date.now();
- coc_nvim_1.workspace.showMessage('The TypeScript language service died unexpectedly 5 times in the last 5 Minutes.', 'error'); // tslint:disable-line
- }
- }
- if (startService) {
- this.startService(true); // tslint:disable-line
- }
- }
- }
- toPath(uri) {
- return this.normalizePath(coc_nvim_1.Uri.parse(uri));
- }
- toResource(filepath) {
- if (this._apiVersion.gte(api_1.default.v213)) {
- if (filepath.startsWith('untitled:')) {
- let resource = coc_nvim_1.Uri.parse(filepath);
- if (this.inMemoryResourcePrefix) {
- const dirName = path_1.default.dirname(resource.path);
- const fileName = path_1.default.basename(resource.path);
- if (fileName.startsWith(this.inMemoryResourcePrefix)) {
- resource = resource.with({ path: path_1.default.posix.join(dirName, fileName.slice(this.inMemoryResourcePrefix.length)) });
- }
- }
- return resource.toString();
- }
- }
- return coc_nvim_1.Uri.file(filepath).toString();
- }
- normalizePath(resource) {
- if (this._apiVersion.gte(api_1.default.v213)) {
- if (resource.scheme == 'untitled') {
- const dirName = path_1.default.dirname(resource.path);
- const fileName = this.inMemoryResourcePrefix + path_1.default.basename(resource.path);
- return resource
- .with({ path: path_1.default.posix.join(dirName, fileName) })
- .toString(true);
- }
- }
- const result = resource.fsPath;
- if (!result)
- return null;
- // Both \ and / must be escaped in regular expressions
- return result.replace(new RegExp('\\' + this.pathSeparator, 'g'), '/');
- }
- get inMemoryResourcePrefix() {
- return this._apiVersion.gte(api_1.default.v270) ? '^' : '';
- }
- asUrl(filepath) {
- if (this._apiVersion.gte(api_1.default.v213)) {
- if (filepath.startsWith('untitled:')) {
- let resource = coc_nvim_1.Uri.parse(filepath);
- if (this.inMemoryResourcePrefix) {
- const dirName = path_1.default.dirname(resource.path);
- const fileName = path_1.default.basename(resource.path);
- if (fileName.startsWith(this.inMemoryResourcePrefix)) {
- resource = resource.with({
- path: path_1.default.posix.join(dirName, fileName.slice(this.inMemoryResourcePrefix.length))
- });
- }
- }
- return resource;
- }
- }
- return coc_nvim_1.Uri.file(filepath);
- }
- execute(command, args, token, lowPriority) {
- return this.executeImpl(command, args, {
- isAsync: false,
- token,
- expectsResult: true,
- lowPriority
- });
- }
- executeAsync(command, args, token) {
- return this.executeImpl(command, args, {
- isAsync: true,
- token,
- expectsResult: true
- });
- }
- executeWithoutWaitingForResponse(command, args) {
- this.executeImpl(command, args, {
- isAsync: false,
- token: undefined,
- expectsResult: false
- });
- }
- executeImpl(command, args, executeInfo) {
- if (this.servicePromise == null) {
- return Promise.resolve(undefined);
- }
- this.bufferSyncSupport.beforeCommand(command);
- const request = this._requestQueue.createRequest(command, args);
- const requestInfo = {
- request,
- expectsResponse: executeInfo.expectsResult,
- isAsync: executeInfo.isAsync,
- queueingType: getQueueingType(command, executeInfo.lowPriority)
- };
- let result;
- if (executeInfo.expectsResult) {
- result = new Promise((resolve, reject) => {
- this._callbacks.add(request.seq, { onSuccess: resolve, onError: reject, startTime: Date.now(), isAsync: executeInfo.isAsync }, executeInfo.isAsync);
- if (executeInfo.token) {
- executeInfo.token.onCancellationRequested(() => {
- this.tryCancelRequest(request.seq, command);
- });
- }
- }).catch((err) => {
- throw err;
- });
- }
- this._requestQueue.enqueue(requestInfo);
- this.sendNextRequests();
- return result;
- }
- sendNextRequests() {
- while (this._pendingResponses.size === 0 && this._requestQueue.length > 0) {
- const item = this._requestQueue.dequeue();
- if (item) {
- this.sendRequest(item);
- }
- }
- }
- sendRequest(requestItem) {
- const serverRequest = requestItem.request;
- this.tracer.traceRequest(serverRequest, requestItem.expectsResponse, this._requestQueue.length);
- if (requestItem.expectsResponse && !requestItem.isAsync) {
- this._pendingResponses.add(requestItem.request.seq);
- }
- this.service().then(childProcess => {
- try {
- childProcess.write(serverRequest);
- }
- catch (err) {
- const callback = this.fetchCallback(serverRequest.seq);
- if (callback) {
- callback.onError(err);
- }
- }
- });
- }
- tryCancelRequest(seq, command) {
- try {
- if (this._requestQueue.tryDeletePendingRequest(seq)) {
- this.tracer.logTrace(`TypeScript Server: canceled request with sequence number ${seq}`);
- return true;
- }
- if (this.cancellationPipeName) {
- this.tracer.logTrace(`TypeScript Server: trying to cancel ongoing request with sequence number ${seq}`);
- try {
- fs_1.default.writeFileSync(this.cancellationPipeName + seq, '');
- }
- catch (_a) {
- // noop
- }
- return true;
- }
- this.tracer.logTrace(`TypeScript Server: tried to cancel request with sequence number ${seq}. But request got already delivered.`);
- return false;
- }
- finally {
- const callback = this.fetchCallback(seq);
- if (callback) {
- callback.onSuccess(new typescriptService_1.ServerResponse.Cancelled(`Cancelled request ${seq} - ${command}`));
- }
- }
- }
- fetchCallback(seq) {
- const callback = this._callbacks.fetch(seq);
- if (!callback) {
- return undefined;
- }
- this._pendingResponses.delete(seq);
- return callback;
- }
- dispatchMessage(message) {
- try {
- switch (message.type) {
- case 'response':
- this.dispatchResponse(message);
- break;
- case 'event':
- const event = message;
- if (event.event === 'requestCompleted') {
- const seq = event.body.request_seq;
- const p = this._callbacks.fetch(seq);
- if (p) {
- this.tracer.traceRequestCompleted('requestCompleted', seq, p.startTime);
- p.onSuccess(undefined);
- }
- }
- else {
- this.tracer.traceEvent(event);
- this.dispatchEvent(event);
- }
- break;
- default:
- throw new Error(`Unknown message type ${message.type} received`);
- }
- }
- finally {
- this.sendNextRequests();
- }
- }
- dispatchResponse(response) {
- const callback = this.fetchCallback(response.request_seq);
- if (!callback) {
- return;
- }
- this.tracer.traceResponse(response, callback.startTime);
- if (response.success) {
- callback.onSuccess(response);
- }
- else if (response.message === 'No content available.') {
- // Special case where response itself is successful but there is not any data to return.
- callback.onSuccess(typescriptService_1.ServerResponse.NoContent);
- }
- else {
- callback.onError(new Error(response.message));
- }
- }
- dispatchEvent(event) {
- switch (event.event) {
- case 'syntaxDiag':
- case 'semanticDiag':
- case 'suggestionDiag':
- const diagnosticEvent = event;
- if (diagnosticEvent.body && diagnosticEvent.body.diagnostics) {
- this._onDiagnosticsReceived.fire({
- kind: getDiagnosticsKind(event),
- resource: this.asUrl(diagnosticEvent.body.file),
- diagnostics: diagnosticEvent.body.diagnostics
- });
- }
- break;
- case 'configFileDiag':
- this._onConfigDiagnosticsReceived.fire(event);
- break;
- case 'projectLanguageServiceState':
- if (event.body) {
- this._onProjectLanguageServiceStateChanged.fire(event.body);
- }
- break;
- case 'beginInstallTypes':
- if (event.body) {
- this._onDidBeginInstallTypings.fire(event.body);
- }
- break;
- case 'endInstallTypes':
- if (event.body) {
- this._onDidEndInstallTypings.fire(event.body);
- }
- break;
- case 'projectsUpdatedInBackground':
- const body = event.body;
- const resources = body.openFiles.map(coc_nvim_1.Uri.file);
- this.bufferSyncSupport.getErr(resources);
- break;
- case 'typesInstallerInitializationFailed':
- if (event.body) {
- this._onTypesInstallerInitializationFailed.fire(event.body);
- }
- break;
- case 'projectLoadingStart':
- this.versionStatus.loading = true;
- break;
- case 'projectLoadingFinish':
- this.versionStatus.loading = false;
- break;
- }
- }
- getTsServerArgs() {
- return __awaiter(this, void 0, void 0, function* () {
- const args = [];
- args.push('--allowLocalPluginLoads');
- if (this.apiVersion.gte(api_1.default.v250)) {
- args.push('--useInferredProjectPerProjectRoot');
- }
- else {
- args.push('--useSingleInferredProject');
- }
- if (this.apiVersion.gte(api_1.default.v206) && this._configuration.disableAutomaticTypeAcquisition) {
- args.push('--disableAutomaticTypingAcquisition');
- }
- if (this.apiVersion.gte(api_1.default.v222)) {
- this.cancellationPipeName = process_1.getTempFile(`tscancellation-${process_1.makeRandomHexString(20)}`);
- args.push('--cancellationPipeName', this.cancellationPipeName + '*');
- }
- if (this.apiVersion.gte(api_1.default.v222)) {
- const isRoot = process.getuid && process.getuid() == 0;
- if (this._configuration.tsServerLogLevel !== configuration_1.TsServerLogLevel.Off && !isRoot) {
- const logDir = process_1.getTempDirectory();
- if (logDir) {
- this.tsServerLogFile = path_1.default.join(logDir, `tsserver.log`);
- this.info('TSServer log file :', this.tsServerLogFile);
- }
- else {
- this.tsServerLogFile = null;
- this.error('Could not create TSServer log directory');
- }
- if (this.tsServerLogFile) {
- args.push('--logVerbosity', configuration_1.TsServerLogLevel.toString(this._configuration.tsServerLogLevel));
- args.push('--logFile', this.tsServerLogFile);
- }
- }
- }
- if (this.apiVersion.gte(api_1.default.v230)) {
- const pluginNames = this.pluginManager.plugins.map(x => x.name);
- const pluginRoot = this._configuration.tsServerPluginRoot;
- const pluginPaths = pluginRoot ? [pluginRoot] : [];
- if (pluginNames.length) {
- args.push('--globalPlugins', pluginNames.join(','));
- for (const plugin of this.pluginManager.plugins) {
- pluginPaths.push(plugin.path);
- }
- }
- if (pluginPaths.length) {
- args.push('--pluginProbeLocations', pluginPaths.join(','));
- }
- }
- if (this._configuration.typingsCacheLocation) {
- args.push('--globalTypingsCacheLocation', `"${this._configuration.typingsCacheLocation}"`);
- }
- if (this.apiVersion.gte(api_1.default.v234)) {
- if (this._configuration.npmLocation) {
- args.push('--npmLocation', `"${this._configuration.npmLocation}"`);
- }
- else {
- try {
- args.push('--npmLocation', `"${which_1.default.sync('npm')}"`);
- }
- catch (e) { } // tslint:disable-line
- }
- }
- if (this.apiVersion.gte(api_1.default.v291)) {
- args.push('--noGetErrOnBackgroundUpdate');
- }
- if (this.apiVersion.gte(api_1.default.v345)) {
- args.push('--validateDefaultNpmLocation');
- }
- return args;
- });
- }
- getProjectRootPath(uri) {
- let root = coc_nvim_1.workspace.cwd;
- let u = coc_nvim_1.Uri.parse(uri);
- if (u.scheme == 'file') {
- let folder = coc_nvim_1.workspace.getWorkspaceFolder(uri);
- if (folder) {
- root = coc_nvim_1.Uri.parse(folder.uri).fsPath;
- }
- else {
- let filepath = coc_nvim_1.Uri.parse(uri).fsPath;
- if (!filepath.startsWith(root)) {
- root = path_1.default.dirname(filepath);
- }
- }
- }
- if (root == os_1.default.homedir())
- return null;
- return root;
- }
- configurePlugin(pluginName, configuration) {
- if (this.apiVersion.gte(api_1.default.v314)) {
- if (!this.servicePromise)
- return;
- this.servicePromise.then(() => {
- // tslint:disable-next-line: no-floating-promises
- this.executeWithoutWaitingForResponse('configurePlugin', { pluginName, configuration });
- });
- }
- }
- interruptGetErr(f) {
- return this.bufferSyncSupport.interuptGetErr(f);
- }
- }
- exports.default = TypeScriptServiceClient;
- function getDiagnosticsKind(event) {
- switch (event.event) {
- case 'syntaxDiag':
- return diagnostics_1.DiagnosticKind.Syntax;
- case 'semanticDiag':
- return diagnostics_1.DiagnosticKind.Semantic;
- case 'suggestionDiag':
- return diagnostics_1.DiagnosticKind.Suggestion;
- }
- throw new Error('Unknown dignostics kind');
- }
- const fenceCommands = new Set(['change', 'close', 'open']);
- function getQueueingType(command, lowPriority) {
- if (fenceCommands.has(command)) {
- return requestQueue_1.RequestQueueingType.Fence;
- }
- return lowPriority ? requestQueue_1.RequestQueueingType.LowPriority : requestQueue_1.RequestQueueingType.Normal;
- }
-
-
- /***/ }),
- /* 118 */
- /***/ (function(module, exports) {
-
- module.exports = require("fs");
-
- /***/ }),
- /* 119 */
- /***/ (function(module, exports, __webpack_require__) {
-
- const isWindows = process.platform === 'win32' ||
- process.env.OSTYPE === 'cygwin' ||
- process.env.OSTYPE === 'msys'
-
- const path = __webpack_require__(13)
- const COLON = isWindows ? ';' : ':'
- const isexe = __webpack_require__(120)
-
- const getNotFoundError = (cmd) =>
- Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })
-
- const getPathInfo = (cmd, opt) => {
- const colon = opt.colon || COLON
-
- // If it has a slash, then we don't bother searching the pathenv.
- // just check the file itself, and that's it.
- const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? ['']
- : (
- [
- // windows always checks the cwd first
- ...(isWindows ? [process.cwd()] : []),
- ...(opt.path || process.env.PATH ||
- /* istanbul ignore next: very unusual */ '').split(colon),
- ]
- )
- const pathExtExe = isWindows
- ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'
- : ''
- const pathExt = isWindows ? pathExtExe.split(colon) : ['']
-
- if (isWindows) {
- if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')
- pathExt.unshift('')
- }
-
- return {
- pathEnv,
- pathExt,
- pathExtExe,
- }
- }
-
- const which = (cmd, opt, cb) => {
- if (typeof opt === 'function') {
- cb = opt
- opt = {}
- }
- if (!opt)
- opt = {}
-
- const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)
- const found = []
-
- const step = i => new Promise((resolve, reject) => {
- if (i === pathEnv.length)
- return opt.all && found.length ? resolve(found)
- : reject(getNotFoundError(cmd))
-
- const ppRaw = pathEnv[i]
- const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw
-
- const pCmd = path.join(pathPart, cmd)
- const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
- : pCmd
-
- resolve(subStep(p, i, 0))
- })
-
- const subStep = (p, i, ii) => new Promise((resolve, reject) => {
- if (ii === pathExt.length)
- return resolve(step(i + 1))
- const ext = pathExt[ii]
- isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
- if (!er && is) {
- if (opt.all)
- found.push(p + ext)
- else
- return resolve(p + ext)
- }
- return resolve(subStep(p, i, ii + 1))
- })
- })
-
- return cb ? step(0).then(res => cb(null, res), cb) : step(0)
- }
-
- const whichSync = (cmd, opt) => {
- opt = opt || {}
-
- const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)
- const found = []
-
- for (let i = 0; i < pathEnv.length; i ++) {
- const ppRaw = pathEnv[i]
- const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw
-
- const pCmd = path.join(pathPart, cmd)
- const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
- : pCmd
-
- for (let j = 0; j < pathExt.length; j ++) {
- const cur = p + pathExt[j]
- try {
- const is = isexe.sync(cur, { pathExt: pathExtExe })
- if (is) {
- if (opt.all)
- found.push(cur)
- else
- return cur
- }
- } catch (ex) {}
- }
- }
-
- if (opt.all && found.length)
- return found
-
- if (opt.nothrow)
- return null
-
- throw getNotFoundError(cmd)
- }
-
- module.exports = which
- which.sync = whichSync
-
-
- /***/ }),
- /* 120 */
- /***/ (function(module, exports, __webpack_require__) {
-
- var fs = __webpack_require__(118)
- var core
- if (process.platform === 'win32' || global.TESTING_WINDOWS) {
- core = __webpack_require__(121)
- } else {
- core = __webpack_require__(122)
- }
-
- module.exports = isexe
- isexe.sync = sync
-
- function isexe (path, options, cb) {
- if (typeof options === 'function') {
- cb = options
- options = {}
- }
-
- if (!cb) {
- if (typeof Promise !== 'function') {
- throw new TypeError('callback not provided')
- }
-
- return new Promise(function (resolve, reject) {
- isexe(path, options || {}, function (er, is) {
- if (er) {
- reject(er)
- } else {
- resolve(is)
- }
- })
- })
- }
-
- core(path, options || {}, function (er, is) {
- // ignore EACCES because that just means we aren't allowed to run it
- if (er) {
- if (er.code === 'EACCES' || options && options.ignoreErrors) {
- er = null
- is = false
- }
- }
- cb(er, is)
- })
- }
-
- function sync (path, options) {
- // my kingdom for a filtered catch
- try {
- return core.sync(path, options || {})
- } catch (er) {
- if (options && options.ignoreErrors || er.code === 'EACCES') {
- return false
- } else {
- throw er
- }
- }
- }
-
-
- /***/ }),
- /* 121 */
- /***/ (function(module, exports, __webpack_require__) {
-
- module.exports = isexe
- isexe.sync = sync
-
- var fs = __webpack_require__(118)
-
- function checkPathExt (path, options) {
- var pathext = options.pathExt !== undefined ?
- options.pathExt : process.env.PATHEXT
-
- if (!pathext) {
- return true
- }
-
- pathext = pathext.split(';')
- if (pathext.indexOf('') !== -1) {
- return true
- }
- for (var i = 0; i < pathext.length; i++) {
- var p = pathext[i].toLowerCase()
- if (p && path.substr(-p.length).toLowerCase() === p) {
- return true
- }
- }
- return false
- }
-
- function checkStat (stat, path, options) {
- if (!stat.isSymbolicLink() && !stat.isFile()) {
- return false
- }
- return checkPathExt(path, options)
- }
-
- function isexe (path, options, cb) {
- fs.stat(path, function (er, stat) {
- cb(er, er ? false : checkStat(stat, path, options))
- })
- }
-
- function sync (path, options) {
- return checkStat(fs.statSync(path), path, options)
- }
-
-
- /***/ }),
- /* 122 */
- /***/ (function(module, exports, __webpack_require__) {
-
- module.exports = isexe
- isexe.sync = sync
-
- var fs = __webpack_require__(118)
-
- function isexe (path, options, cb) {
- fs.stat(path, function (er, stat) {
- cb(er, er ? false : checkStat(stat, options))
- })
- }
-
- function sync (path, options) {
- return checkStat(fs.statSync(path), options)
- }
-
- function checkStat (stat, options) {
- return stat.isFile() && checkMode(stat, options)
- }
-
- function checkMode (stat, options) {
- var mod = stat.mode
- var uid = stat.uid
- var gid = stat.gid
-
- var myUid = options.uid !== undefined ?
- options.uid : process.getuid && process.getuid()
- var myGid = options.gid !== undefined ?
- options.gid : process.getgid && process.getgid()
-
- var u = parseInt('100', 8)
- var g = parseInt('010', 8)
- var o = parseInt('001', 8)
- var ug = u | g
-
- var ret = (mod & o) ||
- (mod & g) && gid === myGid ||
- (mod & u) && uid === myUid ||
- (mod & ug) && myUid === 0
-
- return ret
- }
-
-
- /***/ }),
- /* 123 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ServerResponse = void 0;
- var ServerResponse;
- (function (ServerResponse) {
- class Cancelled {
- constructor(reason) {
- this.reason = reason;
- this.type = 'cancelled';
- }
- }
- ServerResponse.Cancelled = Cancelled;
- // tslint:disable-next-line: new-parens
- ServerResponse.NoContent = new class {
- constructor() {
- this.type = 'noContent';
- }
- };
- })(ServerResponse = exports.ServerResponse || (exports.ServerResponse = {}));
-
-
- /***/ }),
- /* 124 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.TypeScriptServiceConfiguration = exports.TsServerLogLevel = void 0;
- const coc_nvim_1 = __webpack_require__(1);
- const which_1 = __importDefault(__webpack_require__(119));
- var TsServerLogLevel;
- (function (TsServerLogLevel) {
- TsServerLogLevel[TsServerLogLevel["Off"] = 0] = "Off";
- TsServerLogLevel[TsServerLogLevel["Normal"] = 1] = "Normal";
- TsServerLogLevel[TsServerLogLevel["Terse"] = 2] = "Terse";
- TsServerLogLevel[TsServerLogLevel["Verbose"] = 3] = "Verbose";
- })(TsServerLogLevel = exports.TsServerLogLevel || (exports.TsServerLogLevel = {}));
- (function (TsServerLogLevel) {
- function fromString(value) {
- switch (value && value.toLowerCase()) {
- case 'normal':
- return TsServerLogLevel.Normal;
- case 'terse':
- return TsServerLogLevel.Terse;
- case 'verbose':
- return TsServerLogLevel.Verbose;
- case 'off':
- default:
- return TsServerLogLevel.Off;
- }
- }
- TsServerLogLevel.fromString = fromString;
- function toString(value) {
- switch (value) {
- case TsServerLogLevel.Normal:
- return 'normal';
- case TsServerLogLevel.Terse:
- return 'terse';
- case TsServerLogLevel.Verbose:
- return 'verbose';
- case TsServerLogLevel.Off:
- default:
- return 'off';
- }
- }
- TsServerLogLevel.toString = toString;
- })(TsServerLogLevel = exports.TsServerLogLevel || (exports.TsServerLogLevel = {}));
- class TypeScriptServiceConfiguration {
- constructor() {
- this._configuration = coc_nvim_1.workspace.getConfiguration('tsserver');
- coc_nvim_1.workspace.onDidChangeConfiguration(() => {
- this._configuration = coc_nvim_1.workspace.getConfiguration('tsserver');
- });
- }
- get locale() {
- return this._configuration.get('locale', null);
- }
- get globalTsdk() {
- return this._configuration.get('tsdk', null);
- }
- get ignoreLocalTsserver() {
- return this._configuration.get('ignoreLocalTsserver', false);
- }
- get tsServerLogLevel() {
- return TsServerLogLevel.fromString(this._configuration.get('log', null));
- }
- // public readonly watchOptions: protocol.WatchOptions | undefined;
- get watchOptions() {
- return this._configuration.get('watchOptions');
- }
- get typingsCacheLocation() {
- return this._configuration.get('typingsCacheLocation', '');
- }
- get tsServerPluginRoot() {
- return this._configuration.get('tsServerPluginRoot', null);
- }
- get checkJs() {
- return this._configuration.get('implicitProjectConfig.checkJs', false);
- }
- get experimentalDecorators() {
- return this._configuration.get('implicitProjectConfig.experimentalDecorators', false);
- }
- get disableAutomaticTypeAcquisition() {
- return this._configuration.get('disableAutomaticTypeAcquisition', false);
- }
- get formatOnType() {
- return this._configuration.get('formatOnType', false);
- }
- get maxTsServerMemory() {
- return this._configuration.get('maxTsServerMemory', 0);
- }
- get debugPort() {
- return this._configuration.get('debugPort', parseInt(process.env['TSS_DEBUG'], 10));
- }
- get npmLocation() {
- let path = this._configuration.get('npm', '');
- if (path)
- return path;
- try {
- path = which_1.default.sync('npm');
- }
- catch (e) {
- return null;
- }
- return path;
- }
- static loadFromWorkspace() {
- return new TypeScriptServiceConfiguration();
- }
- }
- exports.TypeScriptServiceConfiguration = TypeScriptServiceConfiguration;
-
-
- /***/ }),
- /* 125 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- const coc_nvim_1 = __webpack_require__(1);
- const is = __importStar(__webpack_require__(126));
- class Logger {
- get output() {
- if (this._channel) {
- return this._channel;
- }
- this._channel = coc_nvim_1.workspace.createOutputChannel('tsserver');
- return this._channel;
- }
- dispose() {
- if (this._channel) {
- this._channel.dispose();
- }
- }
- data2String(data) {
- if (data instanceof Error) {
- if (is.string(data.stack)) {
- return data.stack;
- }
- return data.message;
- }
- if (is.boolean(data.success) && !data.success && is.string(data.message)) {
- return data.message;
- }
- if (is.string(data)) {
- return data;
- }
- return data.toString();
- }
- info(message, data) {
- this.logLevel('Info', message, data);
- }
- warn(message, data) {
- this.logLevel('Warn', message, data);
- }
- error(message, data) {
- // See https://github.com/Microsoft/TypeScript/issues/10496
- if (data && data.message === 'No content available.') {
- return;
- }
- this.logLevel('Error', message, data);
- }
- logLevel(level, message, data) {
- this.output.appendLine(`[${level} - ${new Date().toLocaleTimeString()}] ${message}`);
- if (data) {
- this.output.appendLine(this.data2String(data));
- }
- }
- }
- exports.default = Logger;
-
-
- /***/ }),
- /* 126 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.string = exports.boolean = exports.defined = void 0;
- const toString = Object.prototype.toString;
- function defined(value) {
- return typeof value !== 'undefined';
- }
- exports.defined = defined;
- function boolean(value) {
- return value === true || value === false;
- }
- exports.boolean = boolean;
- function string(value) {
- return toString.call(value) === '[object String]';
- }
- exports.string = string;
-
-
- /***/ }),
- /* 127 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.fork = exports.getTempFile = exports.getTempDirectory = exports.makeRandomHexString = void 0;
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const child_process_1 = __importDefault(__webpack_require__(113));
- const net_1 = __importDefault(__webpack_require__(16));
- const os_1 = __importDefault(__webpack_require__(14));
- const path_1 = __importDefault(__webpack_require__(13));
- const fs_1 = __importDefault(__webpack_require__(118));
- function makeRandomHexString(length) {
- let chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
- let result = '';
- for (let i = 0; i < length; i++) {
- const idx = Math.floor(chars.length * Math.random());
- result += chars[idx];
- }
- return result;
- }
- exports.makeRandomHexString = makeRandomHexString;
- function getTempDirectory() {
- let dir = path_1.default.join(os_1.default.tmpdir(), `coc.nvim-${process.pid}`);
- if (!fs_1.default.existsSync(dir)) {
- fs_1.default.mkdirSync(dir);
- }
- return dir;
- }
- exports.getTempDirectory = getTempDirectory;
- function generatePipeName() {
- return getPipeName(makeRandomHexString(40));
- }
- function getPipeName(name) {
- const fullName = 'coc-tsc-' + name;
- if (process.platform === 'win32') {
- return '\\\\.\\pipe\\' + fullName + '-sock';
- }
- const tmpdir = getTempDirectory();
- // Mac/Unix: use socket file
- return path_1.default.join(tmpdir, fullName + '.sock');
- }
- function getTempFile(name) {
- const fullName = 'coc-nvim-' + name;
- return path_1.default.join(getTempDirectory(), fullName + '.sock');
- }
- exports.getTempFile = getTempFile;
- function generatePatchedEnv(env, stdInPipeName, stdOutPipeName, stdErrPipeName) {
- const newEnv = Object.assign({}, env);
- // Set the two unique pipe names and the electron flag as process env
- newEnv['STDIN_PIPE_NAME'] = stdInPipeName; // tslint:disable-line
- newEnv['STDOUT_PIPE_NAME'] = stdOutPipeName; // tslint:disable-line
- newEnv['STDERR_PIPE_NAME'] = stdErrPipeName; // tslint:disable-line
- newEnv['TSS_LOG'] = `-level verbose -file ${path_1.default.join(os_1.default.tmpdir(), 'coc-nvim-tsc.log')}`; // tslint:disable-line
- // Ensure we always have a PATH set
- newEnv['PATH'] = newEnv['PATH'] || process.env.PATH; // tslint:disable-line
- return newEnv;
- }
- function fork(modulePath, args, options, logger, callback) {
- let callbackCalled = false;
- const resolve = (result) => {
- if (callbackCalled) {
- return;
- }
- callbackCalled = true;
- callback(null, result);
- };
- const reject = (err) => {
- if (callbackCalled) {
- return;
- }
- callbackCalled = true;
- callback(err, null);
- };
- // Generate three unique pipe names
- const stdInPipeName = generatePipeName();
- const stdOutPipeName = generatePipeName();
- const stdErrPipeName = generatePipeName();
- const newEnv = generatePatchedEnv(process.env, stdInPipeName, stdOutPipeName, stdErrPipeName);
- newEnv['NODE_PATH'] = path_1.default.join(modulePath, '..', '..', '..'); // tslint:disable-line
- let childProcess;
- // Begin listening to stderr pipe
- let stdErrServer = net_1.default.createServer(stdErrStream => {
- // From now on the childProcess.stderr is available for reading
- childProcess.stderr = stdErrStream;
- });
- stdErrServer.listen(stdErrPipeName);
- // Begin listening to stdout pipe
- let stdOutServer = net_1.default.createServer(stdOutStream => {
- // The child process will write exactly one chunk with content `ready` when it has installed a listener to the stdin pipe
- stdOutStream.once('data', (_chunk) => {
- // The child process is sending me the `ready` chunk, time to connect to the stdin pipe
- childProcess.stdin = net_1.default.connect(stdInPipeName);
- // From now on the childProcess.stdout is available for reading
- childProcess.stdout = stdOutStream;
- resolve(childProcess);
- });
- });
- stdOutServer.listen(stdOutPipeName);
- let serverClosed = false;
- const closeServer = () => {
- if (serverClosed) {
- return;
- }
- serverClosed = true;
- stdOutServer.close();
- stdErrServer.close();
- };
- // Create the process
- logger.info('Forking TSServer', `PATH: ${newEnv['PATH']} `);
- const bootstrapperPath = path_1.default.resolve(__dirname, '../bin/tsserverForkStart');
- childProcess = child_process_1.default.fork(bootstrapperPath, [modulePath].concat(args), {
- silent: true,
- env: newEnv,
- execArgv: options.execArgv
- });
- childProcess.once('error', (err) => {
- closeServer();
- reject(err);
- });
- childProcess.once('exit', (err) => {
- closeServer();
- reject(err);
- });
- }
- exports.fork = fork;
-
-
- /***/ }),
- /* 128 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- Object.defineProperty(exports, "__esModule", { value: true });
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const coc_nvim_1 = __webpack_require__(1);
- var Trace;
- (function (Trace) {
- Trace[Trace["Off"] = 0] = "Off";
- Trace[Trace["Messages"] = 1] = "Messages";
- Trace[Trace["Verbose"] = 2] = "Verbose";
- })(Trace || (Trace = {}));
- (function (Trace) {
- function fromString(value) {
- value = value || '';
- value = value.toLowerCase();
- switch (value) {
- case 'off':
- return Trace.Off;
- case 'messages':
- return Trace.Messages;
- case 'verbose':
- return Trace.Verbose;
- default:
- return Trace.Off;
- }
- }
- Trace.fromString = fromString;
- })(Trace || (Trace = {}));
- class Tracer {
- constructor(logger) {
- this.logger = logger;
- this.trace = Tracer.readTrace();
- }
- static readTrace() {
- let result = Trace.fromString(coc_nvim_1.workspace.getConfiguration('tsserver').get('trace.server', 'off'));
- if (result === Trace.Off && !!process.env.TSS_TRACE) {
- result = Trace.Messages;
- }
- return result;
- }
- traceRequest(request, responseExpected, queueLength) {
- if (this.trace === Trace.Off)
- return;
- let data;
- if (this.trace === Trace.Verbose && request.arguments) {
- data = `Arguments: ${JSON.stringify(request.arguments, null, 4)}`;
- }
- this.logTrace(`Sending request: ${request.command} (${request.seq}). Response expected: ${responseExpected ? 'yes' : 'no'}. Current queue length: ${queueLength}`, data);
- }
- traceResponse(response, startTime) {
- if (this.trace === Trace.Off) {
- return;
- }
- let data;
- if (this.trace === Trace.Verbose && response.body) {
- data = `Result: ${JSON.stringify(response.body, null, 4)}`;
- }
- this.logTrace(`Response received: ${response.command} (${response.request_seq}). Request took ${Date.now() - startTime} ms. Success: ${response.success} ${!response.success ? '. Message: ' + response.message : ''}`, data);
- }
- traceEvent(event) {
- if (this.trace === Trace.Off) {
- return;
- }
- let data;
- if (this.trace === Trace.Verbose && event.body) {
- data = `Data: ${JSON.stringify(event.body, null, 4)}`;
- }
- this.logTrace(`Event received: ${event.event} (${event.seq}).`, data);
- }
- logTrace(message, data) {
- if (this.trace !== Trace.Off) {
- this.logger.logLevel('Trace', message, data);
- }
- }
- traceRequestCompleted(command, request_seq, startTime) {
- if (this.trace === Trace.Off) {
- return;
- }
- this.logTrace(`Async response received: ${command} (${request_seq}). Request took ${Date.now() - startTime} ms.`);
- }
- }
- exports.default = Tracer;
-
-
- /***/ }),
- /* 129 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.inferredProjectConfig = void 0;
- function inferredProjectConfig(config) {
- const base = {
- module: 'commonjs',
- target: 'es2016',
- jsx: 'preserve'
- };
- if (config.checkJs) {
- base.checkJs = true;
- }
- if (config.experimentalDecorators) {
- base.experimentalDecorators = true;
- }
- return base;
- }
- exports.inferredProjectConfig = inferredProjectConfig;
-
-
- /***/ }),
- /* 130 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.TypeScriptVersionProvider = exports.TypeScriptVersion = void 0;
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const fs_1 = __importDefault(__webpack_require__(118));
- const path_1 = __importDefault(__webpack_require__(13));
- const coc_nvim_1 = __webpack_require__(1);
- const api_1 = __importDefault(__webpack_require__(40));
- const requireFunc = true ? require : undefined;
- class TypeScriptVersion {
- constructor(path, _pathLabel) {
- this.path = path;
- this._pathLabel = _pathLabel;
- this._api = null;
- }
- get tscPath() {
- return path_1.default.resolve(this.path, '../bin/tsc');
- }
- get tsServerPath() {
- return path_1.default.resolve(this.path, 'tsserver.js');
- }
- get pathLabel() {
- return typeof this._pathLabel === 'undefined' ? this.path : this._pathLabel;
- }
- get isValid() {
- return this.version != null;
- }
- get version() {
- if (this._api)
- return this._api;
- let api = this._api = this.getTypeScriptVersion(this.tsServerPath);
- return api;
- }
- get versionString() {
- const version = this.version;
- return version ? version.versionString : null;
- }
- getTypeScriptVersion(serverPath) {
- if (!fs_1.default.existsSync(serverPath)) {
- return undefined;
- }
- const p = serverPath.split(path_1.default.sep);
- if (p.length <= 2) {
- return undefined;
- }
- const p2 = p.slice(0, -2);
- const modulePath = p2.join(path_1.default.sep);
- let fileName = path_1.default.join(modulePath, 'package.json');
- if (!fs_1.default.existsSync(fileName)) {
- // Special case for ts dev versions
- if (path_1.default.basename(modulePath) === 'built') {
- fileName = path_1.default.join(modulePath, '..', 'package.json');
- }
- }
- if (!fs_1.default.existsSync(fileName)) {
- return undefined;
- }
- const contents = fs_1.default.readFileSync(fileName).toString();
- let desc = null;
- try {
- desc = JSON.parse(contents);
- }
- catch (err) {
- return undefined;
- }
- if (!desc || !desc.version) {
- return undefined;
- }
- return desc.version ? api_1.default.fromVersionString(desc.version) : undefined;
- }
- }
- exports.TypeScriptVersion = TypeScriptVersion;
- const MODULE_FOLDERS = ['node_modules/typescript/lib', '.vscode/pnpify/typescript/lib'];
- class TypeScriptVersionProvider {
- constructor(configuration) {
- this.configuration = configuration;
- }
- updateConfiguration(configuration) {
- this.configuration = configuration;
- }
- getDefaultVersion() {
- // tsdk from configuration
- let { globalTsdk } = this.configuration;
- if (globalTsdk)
- return new TypeScriptVersion(globalTsdk);
- return this.bundledVersion;
- }
- get globalVersion() {
- let { globalTsdk } = this.configuration;
- if (globalTsdk)
- return new TypeScriptVersion(globalTsdk);
- return undefined;
- }
- getLocalVersion() {
- let folders = coc_nvim_1.workspace.workspaceFolders.map(f => coc_nvim_1.Uri.parse(f.uri).fsPath);
- for (let p of folders) {
- for (let folder of MODULE_FOLDERS) {
- let libFolder = path_1.default.join(p, folder);
- if (fs_1.default.existsSync(libFolder)) {
- let version = new TypeScriptVersion(libFolder);
- if (version.isValid)
- return version;
- }
- }
- }
- return null;
- }
- get bundledVersion() {
- try {
- const file = requireFunc.resolve('typescript');
- const bundledVersion = new TypeScriptVersion(path_1.default.dirname(file), '');
- return bundledVersion;
- }
- catch (e) {
- coc_nvim_1.workspace.showMessage('Bundled typescript module not found', 'error');
- return null;
- }
- }
- }
- exports.TypeScriptVersionProvider = TypeScriptVersionProvider;
-
-
- /***/ }),
- /* 131 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- const coc_nvim_1 = __webpack_require__(1);
- class VersionStatus {
- constructor(_normalizePath, enableJavascript) {
- this._normalizePath = _normalizePath;
- this.enableJavascript = enableJavascript;
- this._versionBarEntry = coc_nvim_1.workspace.createStatusBarItem(99);
- this._onChangeEditorSub = coc_nvim_1.events.on('BufEnter', this.onBufEnter, this);
- this._versionBarEntry.show();
- }
- dispose() {
- this._versionBarEntry.dispose();
- this._onChangeEditorSub.dispose();
- }
- onDidChangeTypeScriptVersion(_version) {
- this._versionBarEntry.text = `TSC`;
- }
- set loading(isLoading) {
- this._versionBarEntry.isProgress = isLoading;
- }
- checkFiletype(filetype) {
- if (filetype.startsWith('javascript') && this.enableJavascript) {
- return true;
- }
- return filetype.startsWith('typescript');
- }
- onBufEnter(bufnr) {
- return __awaiter(this, void 0, void 0, function* () {
- let filetype = yield coc_nvim_1.workspace.nvim.call('getbufvar', [bufnr, '&filetype', '']);
- if (this.checkFiletype(filetype)) {
- this._versionBarEntry.show();
- }
- else {
- this._versionBarEntry.hide();
- }
- });
- }
- }
- exports.default = VersionStatus;
-
-
- /***/ }),
- /* 132 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.Reader = void 0;
- const DefaultSize = 8192;
- const ContentLength = 'Content-Length: ';
- const ContentLengthSize = Buffer.byteLength(ContentLength, 'utf8');
- const Blank = Buffer.from(' ', 'utf8')[0];
- const BackslashR = Buffer.from('\r', 'utf8')[0];
- const BackslashN = Buffer.from('\n', 'utf8')[0];
- class ProtocolBuffer {
- constructor() {
- this.index = 0;
- this.buffer = Buffer.allocUnsafe(DefaultSize);
- }
- append(data) {
- let toAppend = null;
- if (Buffer.isBuffer(data)) {
- toAppend = data;
- }
- else {
- toAppend = Buffer.from(data, 'utf8');
- }
- if (this.buffer.length - this.index >= toAppend.length) {
- toAppend.copy(this.buffer, this.index, 0, toAppend.length);
- }
- else {
- let newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) *
- DefaultSize;
- if (this.index === 0) {
- this.buffer = Buffer.allocUnsafe(newSize);
- toAppend.copy(this.buffer, 0, 0, toAppend.length);
- }
- else {
- this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
- }
- }
- this.index += toAppend.length;
- }
- tryReadContentLength() {
- let result = -1;
- let current = 0;
- // we are utf8 encoding...
- while (current < this.index &&
- (this.buffer[current] === Blank ||
- this.buffer[current] === BackslashR ||
- this.buffer[current] === BackslashN)) {
- current++;
- }
- if (this.index < current + ContentLengthSize) {
- return result;
- }
- current += ContentLengthSize;
- let start = current;
- while (current < this.index && this.buffer[current] !== BackslashR) {
- current++;
- }
- if (current + 3 >= this.index ||
- this.buffer[current + 1] !== BackslashN ||
- this.buffer[current + 2] !== BackslashR ||
- this.buffer[current + 3] !== BackslashN) {
- return result;
- }
- let data = this.buffer.toString('utf8', start, current);
- result = parseInt(data, 10);
- this.buffer = this.buffer.slice(current + 4);
- this.index = this.index - (current + 4);
- return result;
- }
- tryReadContent(length) {
- if (this.index < length) {
- return null;
- }
- let result = this.buffer.toString('utf8', 0, length);
- let sourceStart = length;
- while (sourceStart < this.index &&
- (this.buffer[sourceStart] === BackslashR ||
- this.buffer[sourceStart] === BackslashN)) {
- sourceStart++;
- }
- this.buffer.copy(this.buffer, 0, sourceStart);
- this.index = this.index - sourceStart;
- return result;
- }
- }
- class Reader {
- constructor(readable, callback, onError) {
- this.readable = readable;
- this.callback = callback;
- this.onError = onError;
- this.buffer = new ProtocolBuffer();
- this.nextMessageLength = -1;
- this.readable.on('data', (data) => {
- this.onLengthData(data);
- });
- }
- onLengthData(data) {
- try {
- this.buffer.append(data);
- while (true) {
- if (this.nextMessageLength === -1) {
- this.nextMessageLength = this.buffer.tryReadContentLength();
- if (this.nextMessageLength === -1) {
- return;
- }
- }
- const msg = this.buffer.tryReadContent(this.nextMessageLength);
- if (msg === null) {
- return;
- }
- this.nextMessageLength = -1;
- const json = JSON.parse(msg);
- this.callback(json);
- }
- }
- catch (e) {
- this.onError(e);
- }
- }
- }
- exports.Reader = Reader;
-
-
- /***/ }),
- /* 133 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.CallbackMap = void 0;
- const typescriptService_1 = __webpack_require__(123);
- class CallbackMap {
- constructor() {
- this._callbacks = new Map();
- this._asyncCallbacks = new Map();
- }
- destroy(cause) {
- const cancellation = new typescriptService_1.ServerResponse.Cancelled(cause);
- for (const callback of this._callbacks.values()) {
- callback.onSuccess(cancellation);
- }
- this._callbacks.clear();
- for (const callback of this._asyncCallbacks.values()) {
- callback.onSuccess(cancellation);
- }
- this._asyncCallbacks.clear();
- }
- add(seq, callback, isAsync) {
- if (isAsync) {
- this._asyncCallbacks.set(seq, callback);
- }
- else {
- this._callbacks.set(seq, callback);
- }
- }
- fetch(seq) {
- const callback = this._callbacks.get(seq) || this._asyncCallbacks.get(seq);
- this.delete(seq);
- return callback;
- }
- delete(seq) {
- if (!this._callbacks.delete(seq)) {
- this._asyncCallbacks.delete(seq);
- }
- }
- }
- exports.CallbackMap = CallbackMap;
-
-
- /***/ }),
- /* 134 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.RequestQueue = exports.RequestQueueingType = void 0;
- var RequestQueueingType;
- (function (RequestQueueingType) {
- /**
- * Normal request that is executed in order.
- */
- RequestQueueingType[RequestQueueingType["Normal"] = 1] = "Normal";
- /**
- * Request that normal requests jump in front of in the queue.
- */
- RequestQueueingType[RequestQueueingType["LowPriority"] = 2] = "LowPriority";
- /**
- * A fence that blocks request reordering.
- *
- * Fences are not reordered. Unlike a normal request, a fence will never jump in front of a low priority request
- * in the request queue.
- */
- RequestQueueingType[RequestQueueingType["Fence"] = 3] = "Fence";
- })(RequestQueueingType = exports.RequestQueueingType || (exports.RequestQueueingType = {}));
- class RequestQueue {
- constructor() {
- this.queue = [];
- this.sequenceNumber = 0;
- }
- get length() {
- return this.queue.length;
- }
- enqueue(item) {
- if (item.queueingType === RequestQueueingType.Normal) {
- let index = this.queue.length - 1;
- while (index >= 0) {
- if (this.queue[index].queueingType !== RequestQueueingType.LowPriority) {
- break;
- }
- --index;
- }
- this.queue.splice(index + 1, 0, item);
- }
- else {
- // Only normal priority requests can be reordered. All other requests just go to the end.
- this.queue.push(item);
- }
- }
- dequeue() {
- return this.queue.shift();
- }
- tryDeletePendingRequest(seq) {
- for (let i = 0; i < this.queue.length; i++) {
- if (this.queue[i].request.seq === seq) {
- this.queue.splice(i, 1);
- return true;
- }
- }
- return false;
- }
- createRequest(command, args) {
- return {
- seq: this.sequenceNumber++,
- type: 'request',
- command,
- arguments: args
- };
- }
- }
- exports.RequestQueue = RequestQueue;
-
-
- /***/ }),
- /* 135 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const coc_nvim_1 = __webpack_require__(1);
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- const api_1 = __importDefault(__webpack_require__(40));
- const async_1 = __webpack_require__(136);
- const typeConverters = __importStar(__webpack_require__(37));
- const languageModeIds = __importStar(__webpack_require__(116));
- function mode2ScriptKind(mode) {
- switch (mode) {
- case languageModeIds.typescript:
- return 'TS';
- case languageModeIds.typescripttsx:
- return 'TSX';
- case languageModeIds.typescriptjsx:
- return 'TSX';
- case languageModeIds.typescriptreact:
- return 'TSX';
- case languageModeIds.javascript:
- return 'JS';
- case languageModeIds.javascriptreact:
- return 'JSX';
- }
- return undefined;
- }
- /**
- * Manages synchronization of buffers with the TS server.
- *
- * If supported, batches together file changes. This allows the TS server to more efficiently process changes.
- */
- class BufferSynchronizer {
- constructor(client) {
- this.client = client;
- this._pending = {};
- this._pendingFiles = new Set();
- }
- open(args) {
- this.client.executeWithoutWaitingForResponse('open', args);
- }
- close(filepath) {
- const args = { file: filepath };
- this.client.executeWithoutWaitingForResponse('close', args);
- }
- change(filepath, events) {
- if (!events.length) {
- return;
- }
- if (this.supportsBatching) {
- this.updatePending(filepath, pending => {
- if (!pending.changedFiles) {
- pending.changedFiles = [];
- }
- pending.changedFiles.push({
- fileName: filepath,
- textChanges: events.map((change) => ({
- newText: change.text,
- start: typeConverters.Position.toLocation(change.range.start),
- end: typeConverters.Position.toLocation(change.range.end),
- })).reverse(),
- });
- });
- }
- else {
- for (const event of events) {
- const args = Object.assign({ insertString: event.text }, typeConverters.Range.toFormattingRequestArgs(filepath, event.range));
- this.client.executeWithoutWaitingForResponse('change', args);
- }
- }
- }
- beforeCommand(command) {
- if (command === 'updateOpen') {
- return;
- }
- this.flush();
- }
- flush() {
- if (!this.supportsBatching) {
- // We've already eagerly synchronized
- return;
- }
- if (this._pending.changedFiles) {
- this.client.executeWithoutWaitingForResponse('updateOpen', this._pending);
- this._pending = {};
- this._pendingFiles.clear();
- }
- }
- get supportsBatching() {
- return this.client.apiVersion.gte(api_1.default.v340) && coc_nvim_1.workspace.getConfiguration('tsserver').get('useBatchedBufferSync', true);
- }
- updatePending(filepath, f) {
- if (this.supportsBatching && this._pendingFiles.has(filepath)) {
- this.flush();
- this._pendingFiles.clear();
- f(this._pending);
- this._pendingFiles.add(filepath);
- }
- else {
- f(this._pending);
- }
- }
- reset() {
- this._pending = {};
- this._pendingFiles.clear();
- }
- }
- class BufferSyncSupport {
- constructor(client) {
- this.uris = new Set();
- this.disposables = [];
- this.pendingDiagnostics = new Map();
- this._validateJavaScript = true;
- this._validateTypeScript = true;
- this.listening = false;
- this._onDelete = new vscode_languageserver_protocol_1.Emitter();
- this.onDelete = this._onDelete.event;
- this.client = client;
- this.synchronizer = new BufferSynchronizer(client);
- this.modeIds = new Set(languageModeIds.languageIds);
- this.diagnosticDelayer = new async_1.Delayer(300);
- }
- listen() {
- if (this.listening) {
- return;
- }
- this.listening = true;
- coc_nvim_1.workspace.onDidOpenTextDocument(this.onDidOpenTextDocument, this, this.disposables);
- coc_nvim_1.workspace.onDidCloseTextDocument(this.onDidCloseTextDocument, this, this.disposables);
- coc_nvim_1.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this, this.disposables);
- coc_nvim_1.workspace.textDocuments.forEach(this.onDidOpenTextDocument, this);
- this.updateConfiguration();
- coc_nvim_1.workspace.onDidChangeConfiguration(this.updateConfiguration, this, this.disposables);
- }
- dispose() {
- this.pendingDiagnostics.clear();
- coc_nvim_1.disposeAll(this.disposables);
- }
- onDidOpenTextDocument(document) {
- if (!this.modeIds.has(document.languageId))
- return;
- let { uri } = document;
- let filepath = this.client.toPath(uri);
- this.uris.add(uri);
- const args = {
- file: filepath,
- fileContent: document.getText()
- };
- if (this.client.apiVersion.gte(api_1.default.v203)) {
- const scriptKind = mode2ScriptKind(document.languageId);
- if (scriptKind) {
- args.scriptKindName = scriptKind;
- }
- }
- if (this.client.apiVersion.gte(api_1.default.v230)) {
- let root = this.client.getProjectRootPath(document.uri);
- if (root)
- args.projectRootPath = root;
- }
- this.synchronizer.open(args);
- // this.client.executeWithoutWaitingForResponse('open', args)
- this.requestDiagnostic(uri);
- }
- onDidCloseTextDocument(document) {
- let { uri } = document;
- if (!this.uris.has(uri))
- return;
- let filepath = this.client.toPath(uri);
- this.uris.delete(uri);
- this.pendingDiagnostics.delete(uri);
- this.synchronizer.close(filepath);
- this._onDelete.fire(uri);
- this.requestAllDiagnostics();
- // this.client.executeWithoutWaitingForResponse('close', args)
- }
- onDidChangeTextDocument(e) {
- let { textDocument, contentChanges } = e;
- let { uri } = textDocument;
- if (!this.uris.has(uri))
- return;
- let filepath = this.client.toPath(uri);
- this.synchronizer.change(filepath, contentChanges);
- const didTrigger = this.requestDiagnostic(uri);
- if (!didTrigger && this.pendingGetErr) {
- // In this case we always want to re-trigger all diagnostics
- this.pendingGetErr.cancel();
- this.pendingGetErr = undefined;
- this.triggerDiagnostics();
- }
- }
- beforeCommand(command) {
- this.synchronizer.beforeCommand(command);
- }
- interuptGetErr(f) {
- if (!this.pendingGetErr) {
- return f();
- }
- this.pendingGetErr.cancel();
- this.pendingGetErr = undefined;
- const result = f();
- this.triggerDiagnostics();
- return result;
- }
- getErr(resources) {
- const handledResources = resources.filter(resource => this.uris.has(resource.toString()));
- if (!handledResources.length) {
- return;
- }
- for (const resource of handledResources) {
- let uri = resource.toString();
- if (this.shouldValidate(uri)) {
- this.pendingDiagnostics.set(uri, Date.now());
- }
- }
- this.triggerDiagnostics();
- }
- has(uri) {
- return this.uris.has(uri);
- }
- triggerDiagnostics(delay = 200) {
- this.diagnosticDelayer.trigger(() => {
- this.sendPendingDiagnostics();
- }, delay);
- }
- requestAllDiagnostics() {
- for (const uri of this.uris) {
- if (this.shouldValidate(uri)) {
- this.pendingDiagnostics.set(uri, Date.now());
- }
- }
- this.diagnosticDelayer.trigger(() => {
- this.sendPendingDiagnostics();
- }, 200);
- }
- requestDiagnostic(uri) {
- let document = coc_nvim_1.workspace.getDocument(uri);
- if (!document || !this.shouldValidate(uri))
- return false;
- this.pendingDiagnostics.set(uri, Date.now());
- const lineCount = document.lineCount;
- const delay = Math.min(Math.max(Math.ceil(lineCount / 20), 300), 800);
- this.triggerDiagnostics(delay);
- return true;
- }
- hasPendingDiagnostics(uri) {
- return this.pendingDiagnostics.has(uri);
- }
- sendPendingDiagnostics() {
- const uris = Array.from(this.pendingDiagnostics.entries())
- .sort((a, b) => a[1] - b[1])
- .map(entry => entry[0]);
- // Add all open TS buffers to the geterr request. They might be visible
- for (const uri of this.uris) {
- if (uris.indexOf(uri) == -1) {
- uris.push(uri);
- }
- }
- let files = uris.map(uri => this.client.toPath(uri));
- if (files.length) {
- if (this.pendingGetErr)
- this.pendingGetErr.cancel();
- const getErr = this.pendingGetErr = GetErrRequest.executeGetErrRequest(this.client, files, () => {
- if (this.pendingGetErr === getErr) {
- this.pendingGetErr = undefined;
- }
- });
- }
- this.pendingDiagnostics.clear();
- }
- updateConfiguration() {
- const jsConfig = coc_nvim_1.workspace.getConfiguration('javascript', null);
- const tsConfig = coc_nvim_1.workspace.getConfiguration('typescript', null);
- this._validateJavaScript = jsConfig.get('validate.enable', true);
- this._validateTypeScript = tsConfig.get('validate.enable', true);
- }
- shouldValidate(uri) {
- let doc = coc_nvim_1.workspace.getDocument(uri);
- if (!doc)
- return false;
- if (languageModeIds.languageIds.indexOf(doc.filetype) == -1) {
- return false;
- }
- if (doc.filetype.startsWith('javascript')) {
- return this._validateJavaScript;
- }
- return this._validateTypeScript;
- }
- reinitialize() {
- var _a;
- this.pendingDiagnostics.clear();
- (_a = this.pendingGetErr) === null || _a === void 0 ? void 0 : _a.cancel();
- this.synchronizer.reset();
- for (let doc of coc_nvim_1.workspace.documents) {
- this.onDidOpenTextDocument(doc.textDocument);
- }
- }
- }
- exports.default = BufferSyncSupport;
- class GetErrRequest {
- constructor(client, files, _token, onDone) {
- this.files = files;
- this._token = _token;
- this._done = false;
- const args = {
- delay: 0,
- files: this.files
- };
- const done = () => {
- if (this._done) {
- return;
- }
- this._done = true;
- onDone();
- };
- client.executeAsync('geterr', args, _token.token).then(done, done);
- }
- static executeGetErrRequest(client, files, onDone) {
- const token = new vscode_languageserver_protocol_1.CancellationTokenSource();
- return new GetErrRequest(client, files, token, onDone);
- }
- cancel() {
- if (!this._done) {
- this._token.cancel();
- }
- this._token.dispose();
- }
- }
-
-
- /***/ }),
- /* 136 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.Delayer = void 0;
- class Delayer {
- constructor(defaultDelay) {
- this.defaultDelay = defaultDelay;
- this.timeout = null;
- this.completionPromise = null;
- this.onSuccess = null;
- this.task = null;
- }
- trigger(task, delay = this.defaultDelay) {
- this.task = task;
- if (delay >= 0) {
- this.cancelTimeout();
- }
- if (!this.completionPromise) {
- this.completionPromise = new Promise(resolve => {
- this.onSuccess = resolve;
- }).then(() => {
- this.completionPromise = null;
- this.onSuccess = null;
- let result = this.task && this.task();
- this.task = null;
- return result;
- });
- }
- if (delay >= 0 || this.timeout === null) {
- this.timeout = setTimeout(() => {
- this.timeout = null;
- if (this.onSuccess) {
- this.onSuccess(undefined);
- }
- }, delay >= 0 ? delay : this.defaultDelay);
- }
- return this.completionPromise;
- }
- cancelTimeout() {
- if (this.timeout !== null) {
- clearTimeout(this.timeout);
- this.timeout = null;
- }
- }
- }
- exports.Delayer = Delayer;
-
-
- /***/ }),
- /* 137 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.DiagnosticsManager = exports.DiagnosticKind = exports.DiagnosticSet = void 0;
- const coc_nvim_1 = __webpack_require__(1);
- const resourceMap_1 = __webpack_require__(138);
- class DiagnosticSet {
- constructor() {
- this._map = new resourceMap_1.ResourceMap();
- }
- set(uri, diagnostics) {
- this._map.set(uri, diagnostics);
- }
- get(uri) {
- return this._map.get(uri) || [];
- }
- clear() {
- this._map = new resourceMap_1.ResourceMap();
- }
- }
- exports.DiagnosticSet = DiagnosticSet;
- var DiagnosticKind;
- (function (DiagnosticKind) {
- DiagnosticKind[DiagnosticKind["Syntax"] = 0] = "Syntax";
- DiagnosticKind[DiagnosticKind["Semantic"] = 1] = "Semantic";
- DiagnosticKind[DiagnosticKind["Suggestion"] = 2] = "Suggestion";
- })(DiagnosticKind = exports.DiagnosticKind || (exports.DiagnosticKind = {}));
- const allDiagnosticKinds = [
- DiagnosticKind.Syntax,
- DiagnosticKind.Semantic,
- DiagnosticKind.Suggestion
- ];
- class DiagnosticsManager {
- constructor() {
- this._diagnostics = new Map();
- this._pendingUpdates = new resourceMap_1.ResourceMap();
- this._enableJavascriptSuggestions = true;
- this._enableTypescriptSuggestions = true;
- this.updateDelay = 200;
- for (const kind of allDiagnosticKinds) {
- this._diagnostics.set(kind, new DiagnosticSet());
- }
- this._currentDiagnostics = coc_nvim_1.languages.createDiagnosticCollection('tsserver');
- }
- dispose() {
- this._currentDiagnostics.dispose();
- for (const value of this._pendingUpdates.values) {
- clearTimeout(value);
- }
- this._pendingUpdates = new resourceMap_1.ResourceMap();
- }
- reInitialize() {
- this._currentDiagnostics.clear();
- for (const diagnosticSet of this._diagnostics.values()) {
- diagnosticSet.clear();
- }
- }
- setEnableSuggestions(languageId, value) {
- let curr = languageId == 'javascript' ? this._enableJavascriptSuggestions : this._enableTypescriptSuggestions;
- if (curr == value) {
- return;
- }
- if (languageId == 'javascript') {
- this._enableJavascriptSuggestions = value;
- }
- else {
- this._enableTypescriptSuggestions = value;
- }
- }
- diagnosticsReceived(kind, uri, diagnostics) {
- const collection = this._diagnostics.get(kind);
- if (!collection)
- return;
- if (diagnostics.length === 0) {
- const existing = collection.get(uri);
- if (existing.length === 0) {
- // No need to update
- return;
- }
- }
- collection.set(uri, diagnostics);
- this.scheduleDiagnosticsUpdate(uri);
- }
- configFileDiagnosticsReceived(uri, diagnostics) {
- this._currentDiagnostics.set(uri, diagnostics);
- }
- delete(uri) {
- this._currentDiagnostics.delete(uri);
- }
- getDiagnostics(uri) {
- return this._currentDiagnostics.get(uri) || [];
- return [];
- }
- scheduleDiagnosticsUpdate(uri) {
- if (!this._pendingUpdates.has(uri)) {
- this._pendingUpdates.set(uri, setTimeout(() => this.updateCurrentDiagnostics(uri), this.updateDelay));
- }
- }
- updateCurrentDiagnostics(uri) {
- if (this._pendingUpdates.has(uri)) {
- clearTimeout(this._pendingUpdates.get(uri));
- this._pendingUpdates.delete(uri);
- }
- const allDiagnostics = [
- ...this._diagnostics.get(DiagnosticKind.Syntax).get(uri),
- ...this._diagnostics.get(DiagnosticKind.Semantic).get(uri),
- ...this.getSuggestionDiagnostics(uri)
- ];
- this._currentDiagnostics.set(uri, allDiagnostics);
- }
- getSuggestionDiagnostics(uri) {
- const enabled = this.suggestionsEnabled(uri);
- return this._diagnostics
- .get(DiagnosticKind.Suggestion)
- .get(uri)
- .filter(x => {
- if (!enabled) {
- // Still show unused
- return x.code == 6133;
- }
- return enabled;
- });
- }
- suggestionsEnabled(uri) {
- let doc = coc_nvim_1.workspace.getDocument(uri);
- if (!doc)
- return false;
- if (doc.filetype.startsWith('javascript')) {
- return this._enableJavascriptSuggestions;
- }
- if (doc.filetype.startsWith('typescript')) {
- return this._enableTypescriptSuggestions;
- }
- return true;
- }
- }
- exports.DiagnosticsManager = DiagnosticsManager;
-
-
- /***/ }),
- /* 138 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.isWindowsPath = exports.ResourceMap = void 0;
- /**
- * Maps of file resources
- *
- * Attempts to handle correct mapping on both case sensitive and case in-sensitive
- * file systems.
- */
- class ResourceMap {
- constructor(_normalizePath) {
- this._normalizePath = _normalizePath;
- this._map = new Map();
- }
- has(resource) {
- const file = this.toKey(resource);
- return !!file && this._map.has(file);
- }
- get(resource) {
- const file = this.toKey(resource);
- return file ? this._map.get(file) : undefined;
- }
- set(resource, value) {
- const file = this.toKey(resource);
- if (file) {
- this._map.set(file, value);
- }
- }
- delete(resource) {
- const file = this.toKey(resource);
- if (file) {
- this._map.delete(file);
- }
- }
- get values() {
- return this._map.values();
- }
- get keys() {
- return this._map.keys();
- }
- toKey(resource) {
- const key = this._normalizePath
- ? this._normalizePath(resource)
- : resource;
- if (!key) {
- return key;
- }
- return this.isCaseInsensitivePath(key) ? key.toLowerCase() : key;
- }
- isCaseInsensitivePath(path) {
- if (isWindowsPath(path)) {
- return true;
- }
- return path[0] === '/' && this.onIsCaseInsenitiveFileSystem;
- }
- get onIsCaseInsenitiveFileSystem() {
- if (process.platform === 'win32') {
- return true;
- }
- if (process.platform === 'darwin') {
- return true;
- }
- return false;
- }
- }
- exports.ResourceMap = ResourceMap;
- function isWindowsPath(path) {
- return /^[a-zA-Z]:\\/.test(path);
- }
- exports.isWindowsPath = isWindowsPath;
-
-
- /***/ }),
- /* 139 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.AtaProgressReporter = void 0;
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- const coc_nvim_1 = __webpack_require__(1);
- const typingsInstallTimeout = 30 * 1000;
- class TypingsStatus {
- constructor(client) {
- this._acquiringTypings = Object.create({});
- this._subscriptions = [];
- this._client = client;
- this._subscriptions.push(this._client.onDidBeginInstallTypings(event => this.onBeginInstallTypings(event.eventId)));
- this._subscriptions.push(this._client.onDidEndInstallTypings(event => this.onEndInstallTypings(event.eventId)));
- }
- dispose() {
- this._subscriptions.forEach(x => x.dispose());
- for (const eventId of Object.keys(this._acquiringTypings)) {
- clearTimeout(this._acquiringTypings[eventId]);
- }
- }
- get isAcquiringTypings() {
- return Object.keys(this._acquiringTypings).length > 0;
- }
- onBeginInstallTypings(eventId) {
- if (this._acquiringTypings[eventId]) {
- return;
- }
- this._acquiringTypings[eventId] = setTimeout(() => {
- this.onEndInstallTypings(eventId);
- }, typingsInstallTimeout);
- }
- onEndInstallTypings(eventId) {
- const timer = this._acquiringTypings[eventId];
- if (timer) {
- clearTimeout(timer);
- }
- delete this._acquiringTypings[eventId];
- }
- }
- exports.default = TypingsStatus;
- class AtaProgressReporter {
- constructor(client) {
- this._promises = new Map();
- this._invalid = false;
- this.statusItem = coc_nvim_1.workspace.createStatusBarItem(10, { progress: true });
- const disposables = [];
- disposables.push(client.onDidBeginInstallTypings(e => this._onBegin(e.eventId)));
- disposables.push(client.onDidEndInstallTypings(e => this._onEndOrTimeout(e.eventId)));
- disposables.push(client.onTypesInstallerInitializationFailed(_ => this.onTypesInstallerInitializationFailed()));
- this._disposable = vscode_languageserver_protocol_1.Disposable.create(() => {
- disposables.forEach(disposable => {
- disposable.dispose();
- });
- });
- }
- dispose() {
- this._disposable.dispose();
- this._promises.forEach(value => value());
- }
- _onBegin(eventId) {
- const handle = setTimeout(() => this._onEndOrTimeout(eventId), typingsInstallTimeout);
- new Promise(resolve => {
- this._promises.set(eventId, () => {
- clearTimeout(handle);
- resolve();
- });
- });
- this.statusItem.text = 'Fetching data for better TypeScript IntelliSense';
- this.statusItem.show();
- }
- _onEndOrTimeout(eventId) {
- this.statusItem.hide();
- const resolve = this._promises.get(eventId);
- if (resolve) {
- this._promises.delete(eventId);
- resolve();
- }
- }
- onTypesInstallerInitializationFailed() {
- this.statusItem.hide();
- if (!this._invalid) {
- coc_nvim_1.workspace.showMessage('Could not install typings files for JavaScript language features. Please ensure that NPM is installed', 'error');
- }
- this._invalid = true;
- }
- }
- exports.AtaProgressReporter = AtaProgressReporter;
-
-
- /***/ }),
- /* 140 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ConfigurePluginCommand = exports.AutoFixCommand = exports.TypeScriptGoToProjectConfigCommand = exports.OpenTsServerLogCommand = exports.ReloadProjectsCommand = void 0;
- const coc_nvim_1 = __webpack_require__(1);
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- const typeConverters = __importStar(__webpack_require__(37));
- const vscode_languageserver_types_1 = __webpack_require__(18);
- const modules_1 = __webpack_require__(112);
- const helper_1 = __webpack_require__(100);
- const languageModeIds_1 = __webpack_require__(116);
- class ReloadProjectsCommand {
- constructor(client) {
- this.client = client;
- this.id = 'tsserver.reloadProjects';
- }
- execute() {
- this.client.reloadProjects();
- coc_nvim_1.workspace.showMessage('projects reloaded');
- }
- }
- exports.ReloadProjectsCommand = ReloadProjectsCommand;
- class OpenTsServerLogCommand {
- constructor(client) {
- this.client = client;
- this.id = 'tsserver.openTsServerLog';
- }
- execute() {
- this.client.serviceClient.openTsServerLogFile(); // tslint:disable-line
- }
- }
- exports.OpenTsServerLogCommand = OpenTsServerLogCommand;
- class TypeScriptGoToProjectConfigCommand {
- constructor(client) {
- this.client = client;
- this.id = 'tsserver.goToProjectConfig';
- }
- execute() {
- return __awaiter(this, void 0, void 0, function* () {
- let doc = yield coc_nvim_1.workspace.document;
- let { filetype } = doc;
- if (languageModeIds_1.languageIds.indexOf(filetype) == -1) {
- coc_nvim_1.workspace.showMessage(`Could not determine TypeScript or JavaScript project. Unsupported file type: ${filetype}`, 'warning');
- return;
- }
- // doc.filetype
- yield goToProjectConfig(this.client, doc.uri);
- });
- }
- }
- exports.TypeScriptGoToProjectConfigCommand = TypeScriptGoToProjectConfigCommand;
- function goToProjectConfig(clientHost, uri) {
- return __awaiter(this, void 0, void 0, function* () {
- const client = clientHost.serviceClient;
- const file = client.toPath(uri);
- let res;
- try {
- res = yield client.execute('projectInfo', { file, needFileNameList: false }, vscode_languageserver_protocol_1.CancellationToken.None);
- }
- catch (_a) {
- // noop
- }
- if (!res || !res.body) {
- coc_nvim_1.workspace.showMessage('Could not determine TypeScript or JavaScript project.', 'warning');
- return;
- }
- const { configFileName } = res.body;
- if (configFileName && !isImplicitProjectConfigFile(configFileName)) {
- yield coc_nvim_1.workspace.openResource(coc_nvim_1.Uri.file(configFileName).toString());
- return;
- }
- coc_nvim_1.workspace.showMessage('Config file not found', 'warning');
- });
- }
- function isImplicitProjectConfigFile(configFileName) {
- return configFileName.indexOf('/dev/null/') === 0;
- }
- const autoFixableDiagnosticCodes = new Set([
- 2420,
- 2552,
- 2304,
- ]);
- class AutoFixCommand {
- constructor(client) {
- this.client = client;
- this.id = 'tsserver.executeAutofix';
- }
- execute() {
- return __awaiter(this, void 0, void 0, function* () {
- let document = yield coc_nvim_1.workspace.document;
- let { uri } = document;
- if (!this.client.handles(uri)) {
- coc_nvim_1.workspace.showMessage(`Document ${uri} is not handled by tsserver.`, 'warning');
- return;
- }
- let file = this.client.serviceClient.toPath(document.uri);
- let diagnostics = coc_nvim_1.diagnosticManager.getDiagnostics(document.uri);
- let missingDiagnostics = diagnostics.filter(o => o.code == 2307);
- if (missingDiagnostics.length) {
- let names = missingDiagnostics.map(o => {
- let ms = o.message.match(/module\s'(.+)'\./);
- return ms ? ms[1] : null;
- });
- names = names.filter(s => s != null);
- if (names.length) {
- modules_1.installModules(document.uri, names).catch(e => {
- console.error(e.message); // tslint:disable-line
- });
- }
- }
- diagnostics = diagnostics.filter(x => autoFixableDiagnosticCodes.has(x.code));
- if (diagnostics.length == 0)
- return;
- diagnostics = diagnostics.reduce((arr, curr) => {
- if (curr.code == 2304 && arr.findIndex(o => o.message == curr.message) != -1)
- return arr;
- arr.push(curr);
- return arr;
- }, []);
- let client = this.client.serviceClient;
- let edits = [];
- let command;
- let names = [];
- for (let diagnostic of diagnostics) {
- const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, diagnostic.range)), { errorCodes: [+(diagnostic.code)] });
- const response = yield client.execute('getCodeFixes', args, vscode_languageserver_protocol_1.CancellationToken.None);
- if (response.type !== 'response' || !response.body || response.body.length < 1) {
- if (diagnostic.code == 2304) {
- let { range } = diagnostic;
- let line = document.getline(range.start.line);
- let name = line.slice(range.start.character, range.end.character);
- if (helper_1.nodeModules.indexOf(name) !== -1 && names.indexOf(name) == -1) {
- names.push(name);
- edits.push({
- range: vscode_languageserver_types_1.Range.create(0, 0, 0, 0),
- newText: `import ${name} from '${name}'\n`
- });
- command = 'tsserver.organizeImports';
- }
- }
- continue;
- }
- const fix = response.body[0];
- for (let change of fix.changes) {
- if (change.fileName != file)
- continue;
- // change.fileName
- for (let ch of change.textChanges) {
- edits.push({
- range: typeConverters.Range.fromTextSpan(ch),
- newText: ch.newText
- });
- }
- }
- }
- if (edits.length)
- yield document.applyEdits(coc_nvim_1.workspace.nvim, edits);
- if (command)
- coc_nvim_1.commands.executeCommand(command);
- });
- }
- }
- exports.AutoFixCommand = AutoFixCommand;
- class ConfigurePluginCommand {
- constructor(pluginManager) {
- this.pluginManager = pluginManager;
- this.id = '_typescript.configurePlugin';
- }
- execute(pluginId, configuration) {
- this.pluginManager.setConfiguration(pluginId, configuration);
- }
- }
- exports.ConfigurePluginCommand = ConfigurePluginCommand;
-
-
- /***/ }),
- /* 141 */
- /***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- /*---------------------------------------------------------------------------------------------
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.PluginManager = void 0;
- const coc_nvim_1 = __webpack_require__(1);
- const arrays = __importStar(__webpack_require__(91));
- const vscode_languageserver_protocol_1 = __webpack_require__(3);
- var TypeScriptServerPlugin;
- (function (TypeScriptServerPlugin) {
- function equals(a, b) {
- return a.path === b.path
- && a.name === b.name
- && a.enableForWorkspaceTypeScriptVersions === b.enableForWorkspaceTypeScriptVersions
- && arrays.equals(a.languages, b.languages);
- }
- TypeScriptServerPlugin.equals = equals;
- })(TypeScriptServerPlugin || (TypeScriptServerPlugin = {}));
- class PluginManager {
- constructor() {
- this._pluginConfigurations = new Map();
- this._disposables = [];
- this._onDidUpdatePlugins = this._register(new vscode_languageserver_protocol_1.Emitter());
- this.onDidChangePlugins = this._onDidUpdatePlugins.event;
- this._onDidUpdateConfig = this._register(new vscode_languageserver_protocol_1.Emitter());
- this.onDidUpdateConfig = this._onDidUpdateConfig.event;
- let loadPlugins = () => {
- if (!this._plugins) {
- return;
- }
- const newPlugins = this.readPlugins();
- if (!arrays.equals(arrays.flatten(Array.from(this._plugins.values())), arrays.flatten(Array.from(newPlugins.values())), TypeScriptServerPlugin.equals)) {
- this._plugins = newPlugins;
- this._onDidUpdatePlugins.fire(this);
- }
- };
- coc_nvim_1.extensions.onDidActiveExtension(loadPlugins, undefined, this._disposables);
- coc_nvim_1.extensions.onDidUnloadExtension(loadPlugins, undefined, this._disposables);
- }
- dispose() {
- coc_nvim_1.disposeAll(this._disposables);
- }
- get plugins() {
- if (!this._plugins) {
- this._plugins = this.readPlugins();
- }
- return arrays.flatten(Array.from(this._plugins.values()));
- }
- _register(value) {
- this._disposables.push(value);
- return value;
- }
- setConfiguration(pluginId, config) {
- this._pluginConfigurations.set(pluginId, config);
- this._onDidUpdateConfig.fire({ pluginId, config });
- }
- configurations() {
- return this._pluginConfigurations.entries();
- }
- readPlugins() {
- const pluginMap = new Map();
- for (const extension of coc_nvim_1.extensions.all) {
- const pack = extension.packageJSON;
- if (pack.contributes && Array.isArray(pack.contributes.typescriptServerPlugins)) {
- const plugins = [];
- for (const plugin of pack.contributes.typescriptServerPlugins) {
- plugins.push({
- name: plugin.name,
- enableForWorkspaceTypeScriptVersions: !!plugin.enableForWorkspaceTypeScriptVersions,
- path: extension.extensionPath,
- languages: Array.isArray(plugin.languages) ? plugin.languages : [],
- });
- }
- if (plugins.length) {
- pluginMap.set(extension.id, plugins);
- }
- }
- }
- return pluginMap;
- }
- }
- exports.PluginManager = PluginManager;
-
-
- /***/ })
- /******/ ])));
|