jsonWorker.js 421 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847
  1. (function (factory) {
  2. if (typeof module === "object" && typeof module.exports === "object") {
  3. var v = factory(require, exports);
  4. if (v !== undefined) module.exports = v;
  5. }
  6. else if (typeof define === "function" && define.amd) {
  7. define('jsonc-parser/impl/scanner',["require", "exports"], factory);
  8. }
  9. })(function (require, exports) {
  10. /*---------------------------------------------------------------------------------------------
  11. * Copyright (c) Microsoft Corporation. All rights reserved.
  12. * Licensed under the MIT License. See License.txt in the project root for license information.
  13. *--------------------------------------------------------------------------------------------*/
  14. 'use strict';
  15. Object.defineProperty(exports, "__esModule", { value: true });
  16. exports.createScanner = void 0;
  17. /**
  18. * Creates a JSON scanner on the given text.
  19. * If ignoreTrivia is set, whitespaces or comments are ignored.
  20. */
  21. function createScanner(text, ignoreTrivia) {
  22. if (ignoreTrivia === void 0) { ignoreTrivia = false; }
  23. var len = text.length;
  24. var pos = 0, value = '', tokenOffset = 0, token = 16 /* Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* None */;
  25. function scanHexDigits(count, exact) {
  26. var digits = 0;
  27. var value = 0;
  28. while (digits < count || !exact) {
  29. var ch = text.charCodeAt(pos);
  30. if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) {
  31. value = value * 16 + ch - 48 /* _0 */;
  32. }
  33. else if (ch >= 65 /* A */ && ch <= 70 /* F */) {
  34. value = value * 16 + ch - 65 /* A */ + 10;
  35. }
  36. else if (ch >= 97 /* a */ && ch <= 102 /* f */) {
  37. value = value * 16 + ch - 97 /* a */ + 10;
  38. }
  39. else {
  40. break;
  41. }
  42. pos++;
  43. digits++;
  44. }
  45. if (digits < count) {
  46. value = -1;
  47. }
  48. return value;
  49. }
  50. function setPosition(newPosition) {
  51. pos = newPosition;
  52. value = '';
  53. tokenOffset = 0;
  54. token = 16 /* Unknown */;
  55. scanError = 0 /* None */;
  56. }
  57. function scanNumber() {
  58. var start = pos;
  59. if (text.charCodeAt(pos) === 48 /* _0 */) {
  60. pos++;
  61. }
  62. else {
  63. pos++;
  64. while (pos < text.length && isDigit(text.charCodeAt(pos))) {
  65. pos++;
  66. }
  67. }
  68. if (pos < text.length && text.charCodeAt(pos) === 46 /* dot */) {
  69. pos++;
  70. if (pos < text.length && isDigit(text.charCodeAt(pos))) {
  71. pos++;
  72. while (pos < text.length && isDigit(text.charCodeAt(pos))) {
  73. pos++;
  74. }
  75. }
  76. else {
  77. scanError = 3 /* UnexpectedEndOfNumber */;
  78. return text.substring(start, pos);
  79. }
  80. }
  81. var end = pos;
  82. if (pos < text.length && (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */)) {
  83. pos++;
  84. if (pos < text.length && text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) {
  85. pos++;
  86. }
  87. if (pos < text.length && isDigit(text.charCodeAt(pos))) {
  88. pos++;
  89. while (pos < text.length && isDigit(text.charCodeAt(pos))) {
  90. pos++;
  91. }
  92. end = pos;
  93. }
  94. else {
  95. scanError = 3 /* UnexpectedEndOfNumber */;
  96. }
  97. }
  98. return text.substring(start, end);
  99. }
  100. function scanString() {
  101. var result = '', start = pos;
  102. while (true) {
  103. if (pos >= len) {
  104. result += text.substring(start, pos);
  105. scanError = 2 /* UnexpectedEndOfString */;
  106. break;
  107. }
  108. var ch = text.charCodeAt(pos);
  109. if (ch === 34 /* doubleQuote */) {
  110. result += text.substring(start, pos);
  111. pos++;
  112. break;
  113. }
  114. if (ch === 92 /* backslash */) {
  115. result += text.substring(start, pos);
  116. pos++;
  117. if (pos >= len) {
  118. scanError = 2 /* UnexpectedEndOfString */;
  119. break;
  120. }
  121. var ch2 = text.charCodeAt(pos++);
  122. switch (ch2) {
  123. case 34 /* doubleQuote */:
  124. result += '\"';
  125. break;
  126. case 92 /* backslash */:
  127. result += '\\';
  128. break;
  129. case 47 /* slash */:
  130. result += '/';
  131. break;
  132. case 98 /* b */:
  133. result += '\b';
  134. break;
  135. case 102 /* f */:
  136. result += '\f';
  137. break;
  138. case 110 /* n */:
  139. result += '\n';
  140. break;
  141. case 114 /* r */:
  142. result += '\r';
  143. break;
  144. case 116 /* t */:
  145. result += '\t';
  146. break;
  147. case 117 /* u */:
  148. var ch3 = scanHexDigits(4, true);
  149. if (ch3 >= 0) {
  150. result += String.fromCharCode(ch3);
  151. }
  152. else {
  153. scanError = 4 /* InvalidUnicode */;
  154. }
  155. break;
  156. default:
  157. scanError = 5 /* InvalidEscapeCharacter */;
  158. }
  159. start = pos;
  160. continue;
  161. }
  162. if (ch >= 0 && ch <= 0x1f) {
  163. if (isLineBreak(ch)) {
  164. result += text.substring(start, pos);
  165. scanError = 2 /* UnexpectedEndOfString */;
  166. break;
  167. }
  168. else {
  169. scanError = 6 /* InvalidCharacter */;
  170. // mark as error but continue with string
  171. }
  172. }
  173. pos++;
  174. }
  175. return result;
  176. }
  177. function scanNext() {
  178. value = '';
  179. scanError = 0 /* None */;
  180. tokenOffset = pos;
  181. lineStartOffset = lineNumber;
  182. prevTokenLineStartOffset = tokenLineStartOffset;
  183. if (pos >= len) {
  184. // at the end
  185. tokenOffset = len;
  186. return token = 17 /* EOF */;
  187. }
  188. var code = text.charCodeAt(pos);
  189. // trivia: whitespace
  190. if (isWhiteSpace(code)) {
  191. do {
  192. pos++;
  193. value += String.fromCharCode(code);
  194. code = text.charCodeAt(pos);
  195. } while (isWhiteSpace(code));
  196. return token = 15 /* Trivia */;
  197. }
  198. // trivia: newlines
  199. if (isLineBreak(code)) {
  200. pos++;
  201. value += String.fromCharCode(code);
  202. if (code === 13 /* carriageReturn */ && text.charCodeAt(pos) === 10 /* lineFeed */) {
  203. pos++;
  204. value += '\n';
  205. }
  206. lineNumber++;
  207. tokenLineStartOffset = pos;
  208. return token = 14 /* LineBreakTrivia */;
  209. }
  210. switch (code) {
  211. // tokens: []{}:,
  212. case 123 /* openBrace */:
  213. pos++;
  214. return token = 1 /* OpenBraceToken */;
  215. case 125 /* closeBrace */:
  216. pos++;
  217. return token = 2 /* CloseBraceToken */;
  218. case 91 /* openBracket */:
  219. pos++;
  220. return token = 3 /* OpenBracketToken */;
  221. case 93 /* closeBracket */:
  222. pos++;
  223. return token = 4 /* CloseBracketToken */;
  224. case 58 /* colon */:
  225. pos++;
  226. return token = 6 /* ColonToken */;
  227. case 44 /* comma */:
  228. pos++;
  229. return token = 5 /* CommaToken */;
  230. // strings
  231. case 34 /* doubleQuote */:
  232. pos++;
  233. value = scanString();
  234. return token = 10 /* StringLiteral */;
  235. // comments
  236. case 47 /* slash */:
  237. var start = pos - 1;
  238. // Single-line comment
  239. if (text.charCodeAt(pos + 1) === 47 /* slash */) {
  240. pos += 2;
  241. while (pos < len) {
  242. if (isLineBreak(text.charCodeAt(pos))) {
  243. break;
  244. }
  245. pos++;
  246. }
  247. value = text.substring(start, pos);
  248. return token = 12 /* LineCommentTrivia */;
  249. }
  250. // Multi-line comment
  251. if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
  252. pos += 2;
  253. var safeLength = len - 1; // For lookahead.
  254. var commentClosed = false;
  255. while (pos < safeLength) {
  256. var ch = text.charCodeAt(pos);
  257. if (ch === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
  258. pos += 2;
  259. commentClosed = true;
  260. break;
  261. }
  262. pos++;
  263. if (isLineBreak(ch)) {
  264. if (ch === 13 /* carriageReturn */ && text.charCodeAt(pos) === 10 /* lineFeed */) {
  265. pos++;
  266. }
  267. lineNumber++;
  268. tokenLineStartOffset = pos;
  269. }
  270. }
  271. if (!commentClosed) {
  272. pos++;
  273. scanError = 1 /* UnexpectedEndOfComment */;
  274. }
  275. value = text.substring(start, pos);
  276. return token = 13 /* BlockCommentTrivia */;
  277. }
  278. // just a single slash
  279. value += String.fromCharCode(code);
  280. pos++;
  281. return token = 16 /* Unknown */;
  282. // numbers
  283. case 45 /* minus */:
  284. value += String.fromCharCode(code);
  285. pos++;
  286. if (pos === len || !isDigit(text.charCodeAt(pos))) {
  287. return token = 16 /* Unknown */;
  288. }
  289. // found a minus, followed by a number so
  290. // we fall through to proceed with scanning
  291. // numbers
  292. case 48 /* _0 */:
  293. case 49 /* _1 */:
  294. case 50 /* _2 */:
  295. case 51 /* _3 */:
  296. case 52 /* _4 */:
  297. case 53 /* _5 */:
  298. case 54 /* _6 */:
  299. case 55 /* _7 */:
  300. case 56 /* _8 */:
  301. case 57 /* _9 */:
  302. value += scanNumber();
  303. return token = 11 /* NumericLiteral */;
  304. // literals and unknown symbols
  305. default:
  306. // is a literal? Read the full word.
  307. while (pos < len && isUnknownContentCharacter(code)) {
  308. pos++;
  309. code = text.charCodeAt(pos);
  310. }
  311. if (tokenOffset !== pos) {
  312. value = text.substring(tokenOffset, pos);
  313. // keywords: true, false, null
  314. switch (value) {
  315. case 'true': return token = 8 /* TrueKeyword */;
  316. case 'false': return token = 9 /* FalseKeyword */;
  317. case 'null': return token = 7 /* NullKeyword */;
  318. }
  319. return token = 16 /* Unknown */;
  320. }
  321. // some
  322. value += String.fromCharCode(code);
  323. pos++;
  324. return token = 16 /* Unknown */;
  325. }
  326. }
  327. function isUnknownContentCharacter(code) {
  328. if (isWhiteSpace(code) || isLineBreak(code)) {
  329. return false;
  330. }
  331. switch (code) {
  332. case 125 /* closeBrace */:
  333. case 93 /* closeBracket */:
  334. case 123 /* openBrace */:
  335. case 91 /* openBracket */:
  336. case 34 /* doubleQuote */:
  337. case 58 /* colon */:
  338. case 44 /* comma */:
  339. case 47 /* slash */:
  340. return false;
  341. }
  342. return true;
  343. }
  344. function scanNextNonTrivia() {
  345. var result;
  346. do {
  347. result = scanNext();
  348. } while (result >= 12 /* LineCommentTrivia */ && result <= 15 /* Trivia */);
  349. return result;
  350. }
  351. return {
  352. setPosition: setPosition,
  353. getPosition: function () { return pos; },
  354. scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
  355. getToken: function () { return token; },
  356. getTokenValue: function () { return value; },
  357. getTokenOffset: function () { return tokenOffset; },
  358. getTokenLength: function () { return pos - tokenOffset; },
  359. getTokenStartLine: function () { return lineStartOffset; },
  360. getTokenStartCharacter: function () { return tokenOffset - prevTokenLineStartOffset; },
  361. getTokenError: function () { return scanError; },
  362. };
  363. }
  364. exports.createScanner = createScanner;
  365. function isWhiteSpace(ch) {
  366. return ch === 32 /* space */ || ch === 9 /* tab */ || ch === 11 /* verticalTab */ || ch === 12 /* formFeed */ ||
  367. ch === 160 /* nonBreakingSpace */ || ch === 5760 /* ogham */ || ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
  368. ch === 8239 /* narrowNoBreakSpace */ || ch === 8287 /* mathematicalSpace */ || ch === 12288 /* ideographicSpace */ || ch === 65279 /* byteOrderMark */;
  369. }
  370. function isLineBreak(ch) {
  371. return ch === 10 /* lineFeed */ || ch === 13 /* carriageReturn */ || ch === 8232 /* lineSeparator */ || ch === 8233 /* paragraphSeparator */;
  372. }
  373. function isDigit(ch) {
  374. return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
  375. }
  376. });
  377. (function (factory) {
  378. if (typeof module === "object" && typeof module.exports === "object") {
  379. var v = factory(require, exports);
  380. if (v !== undefined) module.exports = v;
  381. }
  382. else if (typeof define === "function" && define.amd) {
  383. define('jsonc-parser/impl/format',["require", "exports", "./scanner"], factory);
  384. }
  385. })(function (require, exports) {
  386. /*---------------------------------------------------------------------------------------------
  387. * Copyright (c) Microsoft Corporation. All rights reserved.
  388. * Licensed under the MIT License. See License.txt in the project root for license information.
  389. *--------------------------------------------------------------------------------------------*/
  390. 'use strict';
  391. Object.defineProperty(exports, "__esModule", { value: true });
  392. exports.isEOL = exports.format = void 0;
  393. var scanner_1 = require("./scanner");
  394. function format(documentText, range, options) {
  395. var initialIndentLevel;
  396. var formatText;
  397. var formatTextStart;
  398. var rangeStart;
  399. var rangeEnd;
  400. if (range) {
  401. rangeStart = range.offset;
  402. rangeEnd = rangeStart + range.length;
  403. formatTextStart = rangeStart;
  404. while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {
  405. formatTextStart--;
  406. }
  407. var endOffset = rangeEnd;
  408. while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {
  409. endOffset++;
  410. }
  411. formatText = documentText.substring(formatTextStart, endOffset);
  412. initialIndentLevel = computeIndentLevel(formatText, options);
  413. }
  414. else {
  415. formatText = documentText;
  416. initialIndentLevel = 0;
  417. formatTextStart = 0;
  418. rangeStart = 0;
  419. rangeEnd = documentText.length;
  420. }
  421. var eol = getEOL(options, documentText);
  422. var lineBreak = false;
  423. var indentLevel = 0;
  424. var indentValue;
  425. if (options.insertSpaces) {
  426. indentValue = repeat(' ', options.tabSize || 4);
  427. }
  428. else {
  429. indentValue = '\t';
  430. }
  431. var scanner = scanner_1.createScanner(formatText, false);
  432. var hasError = false;
  433. function newLineAndIndent() {
  434. return eol + repeat(indentValue, initialIndentLevel + indentLevel);
  435. }
  436. function scanNext() {
  437. var token = scanner.scan();
  438. lineBreak = false;
  439. while (token === 15 /* Trivia */ || token === 14 /* LineBreakTrivia */) {
  440. lineBreak = lineBreak || (token === 14 /* LineBreakTrivia */);
  441. token = scanner.scan();
  442. }
  443. hasError = token === 16 /* Unknown */ || scanner.getTokenError() !== 0 /* None */;
  444. return token;
  445. }
  446. var editOperations = [];
  447. function addEdit(text, startOffset, endOffset) {
  448. if (!hasError && (!range || (startOffset < rangeEnd && endOffset > rangeStart)) && documentText.substring(startOffset, endOffset) !== text) {
  449. editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });
  450. }
  451. }
  452. var firstToken = scanNext();
  453. if (firstToken !== 17 /* EOF */) {
  454. var firstTokenStart = scanner.getTokenOffset() + formatTextStart;
  455. var initialIndent = repeat(indentValue, initialIndentLevel);
  456. addEdit(initialIndent, formatTextStart, firstTokenStart);
  457. }
  458. while (firstToken !== 17 /* EOF */) {
  459. var firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
  460. var secondToken = scanNext();
  461. var replaceContent = '';
  462. var needsLineBreak = false;
  463. while (!lineBreak && (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */)) {
  464. // comments on the same line: keep them on the same line, but ignore them otherwise
  465. var commentTokenStart = scanner.getTokenOffset() + formatTextStart;
  466. addEdit(' ', firstTokenEnd, commentTokenStart);
  467. firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
  468. needsLineBreak = secondToken === 12 /* LineCommentTrivia */;
  469. replaceContent = needsLineBreak ? newLineAndIndent() : '';
  470. secondToken = scanNext();
  471. }
  472. if (secondToken === 2 /* CloseBraceToken */) {
  473. if (firstToken !== 1 /* OpenBraceToken */) {
  474. indentLevel--;
  475. replaceContent = newLineAndIndent();
  476. }
  477. }
  478. else if (secondToken === 4 /* CloseBracketToken */) {
  479. if (firstToken !== 3 /* OpenBracketToken */) {
  480. indentLevel--;
  481. replaceContent = newLineAndIndent();
  482. }
  483. }
  484. else {
  485. switch (firstToken) {
  486. case 3 /* OpenBracketToken */:
  487. case 1 /* OpenBraceToken */:
  488. indentLevel++;
  489. replaceContent = newLineAndIndent();
  490. break;
  491. case 5 /* CommaToken */:
  492. case 12 /* LineCommentTrivia */:
  493. replaceContent = newLineAndIndent();
  494. break;
  495. case 13 /* BlockCommentTrivia */:
  496. if (lineBreak) {
  497. replaceContent = newLineAndIndent();
  498. }
  499. else if (!needsLineBreak) {
  500. // symbol following comment on the same line: keep on same line, separate with ' '
  501. replaceContent = ' ';
  502. }
  503. break;
  504. case 6 /* ColonToken */:
  505. if (!needsLineBreak) {
  506. replaceContent = ' ';
  507. }
  508. break;
  509. case 10 /* StringLiteral */:
  510. if (secondToken === 6 /* ColonToken */) {
  511. if (!needsLineBreak) {
  512. replaceContent = '';
  513. }
  514. break;
  515. }
  516. // fall through
  517. case 7 /* NullKeyword */:
  518. case 8 /* TrueKeyword */:
  519. case 9 /* FalseKeyword */:
  520. case 11 /* NumericLiteral */:
  521. case 2 /* CloseBraceToken */:
  522. case 4 /* CloseBracketToken */:
  523. if (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */) {
  524. if (!needsLineBreak) {
  525. replaceContent = ' ';
  526. }
  527. }
  528. else if (secondToken !== 5 /* CommaToken */ && secondToken !== 17 /* EOF */) {
  529. hasError = true;
  530. }
  531. break;
  532. case 16 /* Unknown */:
  533. hasError = true;
  534. break;
  535. }
  536. if (lineBreak && (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */)) {
  537. replaceContent = newLineAndIndent();
  538. }
  539. }
  540. if (secondToken === 17 /* EOF */) {
  541. replaceContent = options.insertFinalNewline ? eol : '';
  542. }
  543. var secondTokenStart = scanner.getTokenOffset() + formatTextStart;
  544. addEdit(replaceContent, firstTokenEnd, secondTokenStart);
  545. firstToken = secondToken;
  546. }
  547. return editOperations;
  548. }
  549. exports.format = format;
  550. function repeat(s, count) {
  551. var result = '';
  552. for (var i = 0; i < count; i++) {
  553. result += s;
  554. }
  555. return result;
  556. }
  557. function computeIndentLevel(content, options) {
  558. var i = 0;
  559. var nChars = 0;
  560. var tabSize = options.tabSize || 4;
  561. while (i < content.length) {
  562. var ch = content.charAt(i);
  563. if (ch === ' ') {
  564. nChars++;
  565. }
  566. else if (ch === '\t') {
  567. nChars += tabSize;
  568. }
  569. else {
  570. break;
  571. }
  572. i++;
  573. }
  574. return Math.floor(nChars / tabSize);
  575. }
  576. function getEOL(options, text) {
  577. for (var i = 0; i < text.length; i++) {
  578. var ch = text.charAt(i);
  579. if (ch === '\r') {
  580. if (i + 1 < text.length && text.charAt(i + 1) === '\n') {
  581. return '\r\n';
  582. }
  583. return '\r';
  584. }
  585. else if (ch === '\n') {
  586. return '\n';
  587. }
  588. }
  589. return (options && options.eol) || '\n';
  590. }
  591. function isEOL(text, offset) {
  592. return '\r\n'.indexOf(text.charAt(offset)) !== -1;
  593. }
  594. exports.isEOL = isEOL;
  595. });
  596. (function (factory) {
  597. if (typeof module === "object" && typeof module.exports === "object") {
  598. var v = factory(require, exports);
  599. if (v !== undefined) module.exports = v;
  600. }
  601. else if (typeof define === "function" && define.amd) {
  602. define('jsonc-parser/impl/parser',["require", "exports", "./scanner"], factory);
  603. }
  604. })(function (require, exports) {
  605. /*---------------------------------------------------------------------------------------------
  606. * Copyright (c) Microsoft Corporation. All rights reserved.
  607. * Licensed under the MIT License. See License.txt in the project root for license information.
  608. *--------------------------------------------------------------------------------------------*/
  609. 'use strict';
  610. Object.defineProperty(exports, "__esModule", { value: true });
  611. exports.getNodeType = exports.stripComments = exports.visit = exports.findNodeAtOffset = exports.contains = exports.getNodeValue = exports.getNodePath = exports.findNodeAtLocation = exports.parseTree = exports.parse = exports.getLocation = void 0;
  612. var scanner_1 = require("./scanner");
  613. var ParseOptions;
  614. (function (ParseOptions) {
  615. ParseOptions.DEFAULT = {
  616. allowTrailingComma: false
  617. };
  618. })(ParseOptions || (ParseOptions = {}));
  619. /**
  620. * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.
  621. */
  622. function getLocation(text, position) {
  623. var segments = []; // strings or numbers
  624. var earlyReturnException = new Object();
  625. var previousNode = undefined;
  626. var previousNodeInst = {
  627. value: {},
  628. offset: 0,
  629. length: 0,
  630. type: 'object',
  631. parent: undefined
  632. };
  633. var isAtPropertyKey = false;
  634. function setPreviousNode(value, offset, length, type) {
  635. previousNodeInst.value = value;
  636. previousNodeInst.offset = offset;
  637. previousNodeInst.length = length;
  638. previousNodeInst.type = type;
  639. previousNodeInst.colonOffset = undefined;
  640. previousNode = previousNodeInst;
  641. }
  642. try {
  643. visit(text, {
  644. onObjectBegin: function (offset, length) {
  645. if (position <= offset) {
  646. throw earlyReturnException;
  647. }
  648. previousNode = undefined;
  649. isAtPropertyKey = position > offset;
  650. segments.push(''); // push a placeholder (will be replaced)
  651. },
  652. onObjectProperty: function (name, offset, length) {
  653. if (position < offset) {
  654. throw earlyReturnException;
  655. }
  656. setPreviousNode(name, offset, length, 'property');
  657. segments[segments.length - 1] = name;
  658. if (position <= offset + length) {
  659. throw earlyReturnException;
  660. }
  661. },
  662. onObjectEnd: function (offset, length) {
  663. if (position <= offset) {
  664. throw earlyReturnException;
  665. }
  666. previousNode = undefined;
  667. segments.pop();
  668. },
  669. onArrayBegin: function (offset, length) {
  670. if (position <= offset) {
  671. throw earlyReturnException;
  672. }
  673. previousNode = undefined;
  674. segments.push(0);
  675. },
  676. onArrayEnd: function (offset, length) {
  677. if (position <= offset) {
  678. throw earlyReturnException;
  679. }
  680. previousNode = undefined;
  681. segments.pop();
  682. },
  683. onLiteralValue: function (value, offset, length) {
  684. if (position < offset) {
  685. throw earlyReturnException;
  686. }
  687. setPreviousNode(value, offset, length, getNodeType(value));
  688. if (position <= offset + length) {
  689. throw earlyReturnException;
  690. }
  691. },
  692. onSeparator: function (sep, offset, length) {
  693. if (position <= offset) {
  694. throw earlyReturnException;
  695. }
  696. if (sep === ':' && previousNode && previousNode.type === 'property') {
  697. previousNode.colonOffset = offset;
  698. isAtPropertyKey = false;
  699. previousNode = undefined;
  700. }
  701. else if (sep === ',') {
  702. var last = segments[segments.length - 1];
  703. if (typeof last === 'number') {
  704. segments[segments.length - 1] = last + 1;
  705. }
  706. else {
  707. isAtPropertyKey = true;
  708. segments[segments.length - 1] = '';
  709. }
  710. previousNode = undefined;
  711. }
  712. }
  713. });
  714. }
  715. catch (e) {
  716. if (e !== earlyReturnException) {
  717. throw e;
  718. }
  719. }
  720. return {
  721. path: segments,
  722. previousNode: previousNode,
  723. isAtPropertyKey: isAtPropertyKey,
  724. matches: function (pattern) {
  725. var k = 0;
  726. for (var i = 0; k < pattern.length && i < segments.length; i++) {
  727. if (pattern[k] === segments[i] || pattern[k] === '*') {
  728. k++;
  729. }
  730. else if (pattern[k] !== '**') {
  731. return false;
  732. }
  733. }
  734. return k === pattern.length;
  735. }
  736. };
  737. }
  738. exports.getLocation = getLocation;
  739. /**
  740. * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
  741. * Therefore always check the errors list to find out if the input was valid.
  742. */
  743. function parse(text, errors, options) {
  744. if (errors === void 0) { errors = []; }
  745. if (options === void 0) { options = ParseOptions.DEFAULT; }
  746. var currentProperty = null;
  747. var currentParent = [];
  748. var previousParents = [];
  749. function onValue(value) {
  750. if (Array.isArray(currentParent)) {
  751. currentParent.push(value);
  752. }
  753. else if (currentProperty !== null) {
  754. currentParent[currentProperty] = value;
  755. }
  756. }
  757. var visitor = {
  758. onObjectBegin: function () {
  759. var object = {};
  760. onValue(object);
  761. previousParents.push(currentParent);
  762. currentParent = object;
  763. currentProperty = null;
  764. },
  765. onObjectProperty: function (name) {
  766. currentProperty = name;
  767. },
  768. onObjectEnd: function () {
  769. currentParent = previousParents.pop();
  770. },
  771. onArrayBegin: function () {
  772. var array = [];
  773. onValue(array);
  774. previousParents.push(currentParent);
  775. currentParent = array;
  776. currentProperty = null;
  777. },
  778. onArrayEnd: function () {
  779. currentParent = previousParents.pop();
  780. },
  781. onLiteralValue: onValue,
  782. onError: function (error, offset, length) {
  783. errors.push({ error: error, offset: offset, length: length });
  784. }
  785. };
  786. visit(text, visitor, options);
  787. return currentParent[0];
  788. }
  789. exports.parse = parse;
  790. /**
  791. * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
  792. */
  793. function parseTree(text, errors, options) {
  794. if (errors === void 0) { errors = []; }
  795. if (options === void 0) { options = ParseOptions.DEFAULT; }
  796. var currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root
  797. function ensurePropertyComplete(endOffset) {
  798. if (currentParent.type === 'property') {
  799. currentParent.length = endOffset - currentParent.offset;
  800. currentParent = currentParent.parent;
  801. }
  802. }
  803. function onValue(valueNode) {
  804. currentParent.children.push(valueNode);
  805. return valueNode;
  806. }
  807. var visitor = {
  808. onObjectBegin: function (offset) {
  809. currentParent = onValue({ type: 'object', offset: offset, length: -1, parent: currentParent, children: [] });
  810. },
  811. onObjectProperty: function (name, offset, length) {
  812. currentParent = onValue({ type: 'property', offset: offset, length: -1, parent: currentParent, children: [] });
  813. currentParent.children.push({ type: 'string', value: name, offset: offset, length: length, parent: currentParent });
  814. },
  815. onObjectEnd: function (offset, length) {
  816. ensurePropertyComplete(offset + length); // in case of a missing value for a property: make sure property is complete
  817. currentParent.length = offset + length - currentParent.offset;
  818. currentParent = currentParent.parent;
  819. ensurePropertyComplete(offset + length);
  820. },
  821. onArrayBegin: function (offset, length) {
  822. currentParent = onValue({ type: 'array', offset: offset, length: -1, parent: currentParent, children: [] });
  823. },
  824. onArrayEnd: function (offset, length) {
  825. currentParent.length = offset + length - currentParent.offset;
  826. currentParent = currentParent.parent;
  827. ensurePropertyComplete(offset + length);
  828. },
  829. onLiteralValue: function (value, offset, length) {
  830. onValue({ type: getNodeType(value), offset: offset, length: length, parent: currentParent, value: value });
  831. ensurePropertyComplete(offset + length);
  832. },
  833. onSeparator: function (sep, offset, length) {
  834. if (currentParent.type === 'property') {
  835. if (sep === ':') {
  836. currentParent.colonOffset = offset;
  837. }
  838. else if (sep === ',') {
  839. ensurePropertyComplete(offset);
  840. }
  841. }
  842. },
  843. onError: function (error, offset, length) {
  844. errors.push({ error: error, offset: offset, length: length });
  845. }
  846. };
  847. visit(text, visitor, options);
  848. var result = currentParent.children[0];
  849. if (result) {
  850. delete result.parent;
  851. }
  852. return result;
  853. }
  854. exports.parseTree = parseTree;
  855. /**
  856. * Finds the node at the given path in a JSON DOM.
  857. */
  858. function findNodeAtLocation(root, path) {
  859. if (!root) {
  860. return undefined;
  861. }
  862. var node = root;
  863. for (var _i = 0, path_1 = path; _i < path_1.length; _i++) {
  864. var segment = path_1[_i];
  865. if (typeof segment === 'string') {
  866. if (node.type !== 'object' || !Array.isArray(node.children)) {
  867. return undefined;
  868. }
  869. var found = false;
  870. for (var _a = 0, _b = node.children; _a < _b.length; _a++) {
  871. var propertyNode = _b[_a];
  872. if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment) {
  873. node = propertyNode.children[1];
  874. found = true;
  875. break;
  876. }
  877. }
  878. if (!found) {
  879. return undefined;
  880. }
  881. }
  882. else {
  883. var index = segment;
  884. if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {
  885. return undefined;
  886. }
  887. node = node.children[index];
  888. }
  889. }
  890. return node;
  891. }
  892. exports.findNodeAtLocation = findNodeAtLocation;
  893. /**
  894. * Gets the JSON path of the given JSON DOM node
  895. */
  896. function getNodePath(node) {
  897. if (!node.parent || !node.parent.children) {
  898. return [];
  899. }
  900. var path = getNodePath(node.parent);
  901. if (node.parent.type === 'property') {
  902. var key = node.parent.children[0].value;
  903. path.push(key);
  904. }
  905. else if (node.parent.type === 'array') {
  906. var index = node.parent.children.indexOf(node);
  907. if (index !== -1) {
  908. path.push(index);
  909. }
  910. }
  911. return path;
  912. }
  913. exports.getNodePath = getNodePath;
  914. /**
  915. * Evaluates the JavaScript object of the given JSON DOM node
  916. */
  917. function getNodeValue(node) {
  918. switch (node.type) {
  919. case 'array':
  920. return node.children.map(getNodeValue);
  921. case 'object':
  922. var obj = Object.create(null);
  923. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  924. var prop = _a[_i];
  925. var valueNode = prop.children[1];
  926. if (valueNode) {
  927. obj[prop.children[0].value] = getNodeValue(valueNode);
  928. }
  929. }
  930. return obj;
  931. case 'null':
  932. case 'string':
  933. case 'number':
  934. case 'boolean':
  935. return node.value;
  936. default:
  937. return undefined;
  938. }
  939. }
  940. exports.getNodeValue = getNodeValue;
  941. function contains(node, offset, includeRightBound) {
  942. if (includeRightBound === void 0) { includeRightBound = false; }
  943. return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length));
  944. }
  945. exports.contains = contains;
  946. /**
  947. * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.
  948. */
  949. function findNodeAtOffset(node, offset, includeRightBound) {
  950. if (includeRightBound === void 0) { includeRightBound = false; }
  951. if (contains(node, offset, includeRightBound)) {
  952. var children = node.children;
  953. if (Array.isArray(children)) {
  954. for (var i = 0; i < children.length && children[i].offset <= offset; i++) {
  955. var item = findNodeAtOffset(children[i], offset, includeRightBound);
  956. if (item) {
  957. return item;
  958. }
  959. }
  960. }
  961. return node;
  962. }
  963. return undefined;
  964. }
  965. exports.findNodeAtOffset = findNodeAtOffset;
  966. /**
  967. * Parses the given text and invokes the visitor functions for each object, array and literal reached.
  968. */
  969. function visit(text, visitor, options) {
  970. if (options === void 0) { options = ParseOptions.DEFAULT; }
  971. var _scanner = scanner_1.createScanner(text, false);
  972. function toNoArgVisit(visitFunction) {
  973. return visitFunction ? function () { return visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); } : function () { return true; };
  974. }
  975. function toOneArgVisit(visitFunction) {
  976. return visitFunction ? function (arg) { return visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); } : function () { return true; };
  977. }
  978. var onObjectBegin = toNoArgVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisit(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisit(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisit(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
  979. var disallowComments = options && options.disallowComments;
  980. var allowTrailingComma = options && options.allowTrailingComma;
  981. function scanNext() {
  982. while (true) {
  983. var token = _scanner.scan();
  984. switch (_scanner.getTokenError()) {
  985. case 4 /* InvalidUnicode */:
  986. handleError(14 /* InvalidUnicode */);
  987. break;
  988. case 5 /* InvalidEscapeCharacter */:
  989. handleError(15 /* InvalidEscapeCharacter */);
  990. break;
  991. case 3 /* UnexpectedEndOfNumber */:
  992. handleError(13 /* UnexpectedEndOfNumber */);
  993. break;
  994. case 1 /* UnexpectedEndOfComment */:
  995. if (!disallowComments) {
  996. handleError(11 /* UnexpectedEndOfComment */);
  997. }
  998. break;
  999. case 2 /* UnexpectedEndOfString */:
  1000. handleError(12 /* UnexpectedEndOfString */);
  1001. break;
  1002. case 6 /* InvalidCharacter */:
  1003. handleError(16 /* InvalidCharacter */);
  1004. break;
  1005. }
  1006. switch (token) {
  1007. case 12 /* LineCommentTrivia */:
  1008. case 13 /* BlockCommentTrivia */:
  1009. if (disallowComments) {
  1010. handleError(10 /* InvalidCommentToken */);
  1011. }
  1012. else {
  1013. onComment();
  1014. }
  1015. break;
  1016. case 16 /* Unknown */:
  1017. handleError(1 /* InvalidSymbol */);
  1018. break;
  1019. case 15 /* Trivia */:
  1020. case 14 /* LineBreakTrivia */:
  1021. break;
  1022. default:
  1023. return token;
  1024. }
  1025. }
  1026. }
  1027. function handleError(error, skipUntilAfter, skipUntil) {
  1028. if (skipUntilAfter === void 0) { skipUntilAfter = []; }
  1029. if (skipUntil === void 0) { skipUntil = []; }
  1030. onError(error);
  1031. if (skipUntilAfter.length + skipUntil.length > 0) {
  1032. var token = _scanner.getToken();
  1033. while (token !== 17 /* EOF */) {
  1034. if (skipUntilAfter.indexOf(token) !== -1) {
  1035. scanNext();
  1036. break;
  1037. }
  1038. else if (skipUntil.indexOf(token) !== -1) {
  1039. break;
  1040. }
  1041. token = scanNext();
  1042. }
  1043. }
  1044. }
  1045. function parseString(isValue) {
  1046. var value = _scanner.getTokenValue();
  1047. if (isValue) {
  1048. onLiteralValue(value);
  1049. }
  1050. else {
  1051. onObjectProperty(value);
  1052. }
  1053. scanNext();
  1054. return true;
  1055. }
  1056. function parseLiteral() {
  1057. switch (_scanner.getToken()) {
  1058. case 11 /* NumericLiteral */:
  1059. var tokenValue = _scanner.getTokenValue();
  1060. var value = Number(tokenValue);
  1061. if (isNaN(value)) {
  1062. handleError(2 /* InvalidNumberFormat */);
  1063. value = 0;
  1064. }
  1065. onLiteralValue(value);
  1066. break;
  1067. case 7 /* NullKeyword */:
  1068. onLiteralValue(null);
  1069. break;
  1070. case 8 /* TrueKeyword */:
  1071. onLiteralValue(true);
  1072. break;
  1073. case 9 /* FalseKeyword */:
  1074. onLiteralValue(false);
  1075. break;
  1076. default:
  1077. return false;
  1078. }
  1079. scanNext();
  1080. return true;
  1081. }
  1082. function parseProperty() {
  1083. if (_scanner.getToken() !== 10 /* StringLiteral */) {
  1084. handleError(3 /* PropertyNameExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  1085. return false;
  1086. }
  1087. parseString(false);
  1088. if (_scanner.getToken() === 6 /* ColonToken */) {
  1089. onSeparator(':');
  1090. scanNext(); // consume colon
  1091. if (!parseValue()) {
  1092. handleError(4 /* ValueExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  1093. }
  1094. }
  1095. else {
  1096. handleError(5 /* ColonExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  1097. }
  1098. return true;
  1099. }
  1100. function parseObject() {
  1101. onObjectBegin();
  1102. scanNext(); // consume open brace
  1103. var needsComma = false;
  1104. while (_scanner.getToken() !== 2 /* CloseBraceToken */ && _scanner.getToken() !== 17 /* EOF */) {
  1105. if (_scanner.getToken() === 5 /* CommaToken */) {
  1106. if (!needsComma) {
  1107. handleError(4 /* ValueExpected */, [], []);
  1108. }
  1109. onSeparator(',');
  1110. scanNext(); // consume comma
  1111. if (_scanner.getToken() === 2 /* CloseBraceToken */ && allowTrailingComma) {
  1112. break;
  1113. }
  1114. }
  1115. else if (needsComma) {
  1116. handleError(6 /* CommaExpected */, [], []);
  1117. }
  1118. if (!parseProperty()) {
  1119. handleError(4 /* ValueExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  1120. }
  1121. needsComma = true;
  1122. }
  1123. onObjectEnd();
  1124. if (_scanner.getToken() !== 2 /* CloseBraceToken */) {
  1125. handleError(7 /* CloseBraceExpected */, [2 /* CloseBraceToken */], []);
  1126. }
  1127. else {
  1128. scanNext(); // consume close brace
  1129. }
  1130. return true;
  1131. }
  1132. function parseArray() {
  1133. onArrayBegin();
  1134. scanNext(); // consume open bracket
  1135. var needsComma = false;
  1136. while (_scanner.getToken() !== 4 /* CloseBracketToken */ && _scanner.getToken() !== 17 /* EOF */) {
  1137. if (_scanner.getToken() === 5 /* CommaToken */) {
  1138. if (!needsComma) {
  1139. handleError(4 /* ValueExpected */, [], []);
  1140. }
  1141. onSeparator(',');
  1142. scanNext(); // consume comma
  1143. if (_scanner.getToken() === 4 /* CloseBracketToken */ && allowTrailingComma) {
  1144. break;
  1145. }
  1146. }
  1147. else if (needsComma) {
  1148. handleError(6 /* CommaExpected */, [], []);
  1149. }
  1150. if (!parseValue()) {
  1151. handleError(4 /* ValueExpected */, [], [4 /* CloseBracketToken */, 5 /* CommaToken */]);
  1152. }
  1153. needsComma = true;
  1154. }
  1155. onArrayEnd();
  1156. if (_scanner.getToken() !== 4 /* CloseBracketToken */) {
  1157. handleError(8 /* CloseBracketExpected */, [4 /* CloseBracketToken */], []);
  1158. }
  1159. else {
  1160. scanNext(); // consume close bracket
  1161. }
  1162. return true;
  1163. }
  1164. function parseValue() {
  1165. switch (_scanner.getToken()) {
  1166. case 3 /* OpenBracketToken */:
  1167. return parseArray();
  1168. case 1 /* OpenBraceToken */:
  1169. return parseObject();
  1170. case 10 /* StringLiteral */:
  1171. return parseString(true);
  1172. default:
  1173. return parseLiteral();
  1174. }
  1175. }
  1176. scanNext();
  1177. if (_scanner.getToken() === 17 /* EOF */) {
  1178. if (options.allowEmptyContent) {
  1179. return true;
  1180. }
  1181. handleError(4 /* ValueExpected */, [], []);
  1182. return false;
  1183. }
  1184. if (!parseValue()) {
  1185. handleError(4 /* ValueExpected */, [], []);
  1186. return false;
  1187. }
  1188. if (_scanner.getToken() !== 17 /* EOF */) {
  1189. handleError(9 /* EndOfFileExpected */, [], []);
  1190. }
  1191. return true;
  1192. }
  1193. exports.visit = visit;
  1194. /**
  1195. * Takes JSON with JavaScript-style comments and remove
  1196. * them. Optionally replaces every none-newline character
  1197. * of comments with a replaceCharacter
  1198. */
  1199. function stripComments(text, replaceCh) {
  1200. var _scanner = scanner_1.createScanner(text), parts = [], kind, offset = 0, pos;
  1201. do {
  1202. pos = _scanner.getPosition();
  1203. kind = _scanner.scan();
  1204. switch (kind) {
  1205. case 12 /* LineCommentTrivia */:
  1206. case 13 /* BlockCommentTrivia */:
  1207. case 17 /* EOF */:
  1208. if (offset !== pos) {
  1209. parts.push(text.substring(offset, pos));
  1210. }
  1211. if (replaceCh !== undefined) {
  1212. parts.push(_scanner.getTokenValue().replace(/[^\r\n]/g, replaceCh));
  1213. }
  1214. offset = _scanner.getPosition();
  1215. break;
  1216. }
  1217. } while (kind !== 17 /* EOF */);
  1218. return parts.join('');
  1219. }
  1220. exports.stripComments = stripComments;
  1221. function getNodeType(value) {
  1222. switch (typeof value) {
  1223. case 'boolean': return 'boolean';
  1224. case 'number': return 'number';
  1225. case 'string': return 'string';
  1226. case 'object': {
  1227. if (!value) {
  1228. return 'null';
  1229. }
  1230. else if (Array.isArray(value)) {
  1231. return 'array';
  1232. }
  1233. return 'object';
  1234. }
  1235. default: return 'null';
  1236. }
  1237. }
  1238. exports.getNodeType = getNodeType;
  1239. });
  1240. (function (factory) {
  1241. if (typeof module === "object" && typeof module.exports === "object") {
  1242. var v = factory(require, exports);
  1243. if (v !== undefined) module.exports = v;
  1244. }
  1245. else if (typeof define === "function" && define.amd) {
  1246. define('jsonc-parser/impl/edit',["require", "exports", "./format", "./parser"], factory);
  1247. }
  1248. })(function (require, exports) {
  1249. /*---------------------------------------------------------------------------------------------
  1250. * Copyright (c) Microsoft Corporation. All rights reserved.
  1251. * Licensed under the MIT License. See License.txt in the project root for license information.
  1252. *--------------------------------------------------------------------------------------------*/
  1253. 'use strict';
  1254. Object.defineProperty(exports, "__esModule", { value: true });
  1255. exports.isWS = exports.applyEdit = exports.setProperty = exports.removeProperty = void 0;
  1256. var format_1 = require("./format");
  1257. var parser_1 = require("./parser");
  1258. function removeProperty(text, path, options) {
  1259. return setProperty(text, path, void 0, options);
  1260. }
  1261. exports.removeProperty = removeProperty;
  1262. function setProperty(text, originalPath, value, options) {
  1263. var _a;
  1264. var path = originalPath.slice();
  1265. var errors = [];
  1266. var root = parser_1.parseTree(text, errors);
  1267. var parent = void 0;
  1268. var lastSegment = void 0;
  1269. while (path.length > 0) {
  1270. lastSegment = path.pop();
  1271. parent = parser_1.findNodeAtLocation(root, path);
  1272. if (parent === void 0 && value !== void 0) {
  1273. if (typeof lastSegment === 'string') {
  1274. value = (_a = {}, _a[lastSegment] = value, _a);
  1275. }
  1276. else {
  1277. value = [value];
  1278. }
  1279. }
  1280. else {
  1281. break;
  1282. }
  1283. }
  1284. if (!parent) {
  1285. // empty document
  1286. if (value === void 0) { // delete
  1287. throw new Error('Can not delete in empty document');
  1288. }
  1289. return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options);
  1290. }
  1291. else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) {
  1292. var existing = parser_1.findNodeAtLocation(parent, [lastSegment]);
  1293. if (existing !== void 0) {
  1294. if (value === void 0) { // delete
  1295. if (!existing.parent) {
  1296. throw new Error('Malformed AST');
  1297. }
  1298. var propertyIndex = parent.children.indexOf(existing.parent);
  1299. var removeBegin = void 0;
  1300. var removeEnd = existing.parent.offset + existing.parent.length;
  1301. if (propertyIndex > 0) {
  1302. // remove the comma of the previous node
  1303. var previous = parent.children[propertyIndex - 1];
  1304. removeBegin = previous.offset + previous.length;
  1305. }
  1306. else {
  1307. removeBegin = parent.offset + 1;
  1308. if (parent.children.length > 1) {
  1309. // remove the comma of the next node
  1310. var next = parent.children[1];
  1311. removeEnd = next.offset;
  1312. }
  1313. }
  1314. return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, options);
  1315. }
  1316. else {
  1317. // set value of existing property
  1318. return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options);
  1319. }
  1320. }
  1321. else {
  1322. if (value === void 0) { // delete
  1323. return []; // property does not exist, nothing to do
  1324. }
  1325. var newProperty = JSON.stringify(lastSegment) + ": " + JSON.stringify(value);
  1326. var index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map(function (p) { return p.children[0].value; })) : parent.children.length;
  1327. var edit = void 0;
  1328. if (index > 0) {
  1329. var previous = parent.children[index - 1];
  1330. edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
  1331. }
  1332. else if (parent.children.length === 0) {
  1333. edit = { offset: parent.offset + 1, length: 0, content: newProperty };
  1334. }
  1335. else {
  1336. edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' };
  1337. }
  1338. return withFormatting(text, edit, options);
  1339. }
  1340. }
  1341. else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) {
  1342. var insertIndex = lastSegment;
  1343. if (insertIndex === -1) {
  1344. // Insert
  1345. var newProperty = "" + JSON.stringify(value);
  1346. var edit = void 0;
  1347. if (parent.children.length === 0) {
  1348. edit = { offset: parent.offset + 1, length: 0, content: newProperty };
  1349. }
  1350. else {
  1351. var previous = parent.children[parent.children.length - 1];
  1352. edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
  1353. }
  1354. return withFormatting(text, edit, options);
  1355. }
  1356. else if (value === void 0 && parent.children.length >= 0) {
  1357. // Removal
  1358. var removalIndex = lastSegment;
  1359. var toRemove = parent.children[removalIndex];
  1360. var edit = void 0;
  1361. if (parent.children.length === 1) {
  1362. // only item
  1363. edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' };
  1364. }
  1365. else if (parent.children.length - 1 === removalIndex) {
  1366. // last item
  1367. var previous = parent.children[removalIndex - 1];
  1368. var offset = previous.offset + previous.length;
  1369. var parentEndOffset = parent.offset + parent.length;
  1370. edit = { offset: offset, length: parentEndOffset - 2 - offset, content: '' };
  1371. }
  1372. else {
  1373. edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' };
  1374. }
  1375. return withFormatting(text, edit, options);
  1376. }
  1377. else if (value !== void 0) {
  1378. var edit = void 0;
  1379. var newProperty = "" + JSON.stringify(value);
  1380. if (!options.isArrayInsertion && parent.children.length > lastSegment) {
  1381. var toModify = parent.children[lastSegment];
  1382. edit = { offset: toModify.offset, length: toModify.length, content: newProperty };
  1383. }
  1384. else if (parent.children.length === 0 || lastSegment === 0) {
  1385. edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + ',' };
  1386. }
  1387. else {
  1388. var index = lastSegment > parent.children.length ? parent.children.length : lastSegment;
  1389. var previous = parent.children[index - 1];
  1390. edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
  1391. }
  1392. return withFormatting(text, edit, options);
  1393. }
  1394. else {
  1395. throw new Error("Can not " + (value === void 0 ? 'remove' : (options.isArrayInsertion ? 'insert' : 'modify')) + " Array index " + insertIndex + " as length is not sufficient");
  1396. }
  1397. }
  1398. else {
  1399. throw new Error("Can not add " + (typeof lastSegment !== 'number' ? 'index' : 'property') + " to parent of type " + parent.type);
  1400. }
  1401. }
  1402. exports.setProperty = setProperty;
  1403. function withFormatting(text, edit, options) {
  1404. if (!options.formattingOptions) {
  1405. return [edit];
  1406. }
  1407. // apply the edit
  1408. var newText = applyEdit(text, edit);
  1409. // format the new text
  1410. var begin = edit.offset;
  1411. var end = edit.offset + edit.content.length;
  1412. if (edit.length === 0 || edit.content.length === 0) { // insert or remove
  1413. while (begin > 0 && !format_1.isEOL(newText, begin - 1)) {
  1414. begin--;
  1415. }
  1416. while (end < newText.length && !format_1.isEOL(newText, end)) {
  1417. end++;
  1418. }
  1419. }
  1420. var edits = format_1.format(newText, { offset: begin, length: end - begin }, options.formattingOptions);
  1421. // apply the formatting edits and track the begin and end offsets of the changes
  1422. for (var i = edits.length - 1; i >= 0; i--) {
  1423. var edit_1 = edits[i];
  1424. newText = applyEdit(newText, edit_1);
  1425. begin = Math.min(begin, edit_1.offset);
  1426. end = Math.max(end, edit_1.offset + edit_1.length);
  1427. end += edit_1.content.length - edit_1.length;
  1428. }
  1429. // create a single edit with all changes
  1430. var editLength = text.length - (newText.length - end) - begin;
  1431. return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];
  1432. }
  1433. function applyEdit(text, edit) {
  1434. return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
  1435. }
  1436. exports.applyEdit = applyEdit;
  1437. function isWS(text, offset) {
  1438. return '\r\n \t'.indexOf(text.charAt(offset)) !== -1;
  1439. }
  1440. exports.isWS = isWS;
  1441. });
  1442. (function (factory) {
  1443. if (typeof module === "object" && typeof module.exports === "object") {
  1444. var v = factory(require, exports);
  1445. if (v !== undefined) module.exports = v;
  1446. }
  1447. else if (typeof define === "function" && define.amd) {
  1448. define('jsonc-parser/main',["require", "exports", "./impl/format", "./impl/edit", "./impl/scanner", "./impl/parser"], factory);
  1449. }
  1450. })(function (require, exports) {
  1451. /*---------------------------------------------------------------------------------------------
  1452. * Copyright (c) Microsoft Corporation. All rights reserved.
  1453. * Licensed under the MIT License. See License.txt in the project root for license information.
  1454. *--------------------------------------------------------------------------------------------*/
  1455. 'use strict';
  1456. Object.defineProperty(exports, "__esModule", { value: true });
  1457. exports.applyEdits = exports.modify = exports.format = exports.printParseErrorCode = exports.stripComments = exports.visit = exports.getNodeValue = exports.getNodePath = exports.findNodeAtOffset = exports.findNodeAtLocation = exports.parseTree = exports.parse = exports.getLocation = exports.createScanner = void 0;
  1458. var formatter = require("./impl/format");
  1459. var edit = require("./impl/edit");
  1460. var scanner = require("./impl/scanner");
  1461. var parser = require("./impl/parser");
  1462. /**
  1463. * Creates a JSON scanner on the given text.
  1464. * If ignoreTrivia is set, whitespaces or comments are ignored.
  1465. */
  1466. exports.createScanner = scanner.createScanner;
  1467. /**
  1468. * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.
  1469. */
  1470. exports.getLocation = parser.getLocation;
  1471. /**
  1472. * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
  1473. * Therefore, always check the errors list to find out if the input was valid.
  1474. */
  1475. exports.parse = parser.parse;
  1476. /**
  1477. * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
  1478. */
  1479. exports.parseTree = parser.parseTree;
  1480. /**
  1481. * Finds the node at the given path in a JSON DOM.
  1482. */
  1483. exports.findNodeAtLocation = parser.findNodeAtLocation;
  1484. /**
  1485. * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.
  1486. */
  1487. exports.findNodeAtOffset = parser.findNodeAtOffset;
  1488. /**
  1489. * Gets the JSON path of the given JSON DOM node
  1490. */
  1491. exports.getNodePath = parser.getNodePath;
  1492. /**
  1493. * Evaluates the JavaScript object of the given JSON DOM node
  1494. */
  1495. exports.getNodeValue = parser.getNodeValue;
  1496. /**
  1497. * Parses the given text and invokes the visitor functions for each object, array and literal reached.
  1498. */
  1499. exports.visit = parser.visit;
  1500. /**
  1501. * Takes JSON with JavaScript-style comments and remove
  1502. * them. Optionally replaces every none-newline character
  1503. * of comments with a replaceCharacter
  1504. */
  1505. exports.stripComments = parser.stripComments;
  1506. function printParseErrorCode(code) {
  1507. switch (code) {
  1508. case 1 /* InvalidSymbol */: return 'InvalidSymbol';
  1509. case 2 /* InvalidNumberFormat */: return 'InvalidNumberFormat';
  1510. case 3 /* PropertyNameExpected */: return 'PropertyNameExpected';
  1511. case 4 /* ValueExpected */: return 'ValueExpected';
  1512. case 5 /* ColonExpected */: return 'ColonExpected';
  1513. case 6 /* CommaExpected */: return 'CommaExpected';
  1514. case 7 /* CloseBraceExpected */: return 'CloseBraceExpected';
  1515. case 8 /* CloseBracketExpected */: return 'CloseBracketExpected';
  1516. case 9 /* EndOfFileExpected */: return 'EndOfFileExpected';
  1517. case 10 /* InvalidCommentToken */: return 'InvalidCommentToken';
  1518. case 11 /* UnexpectedEndOfComment */: return 'UnexpectedEndOfComment';
  1519. case 12 /* UnexpectedEndOfString */: return 'UnexpectedEndOfString';
  1520. case 13 /* UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber';
  1521. case 14 /* InvalidUnicode */: return 'InvalidUnicode';
  1522. case 15 /* InvalidEscapeCharacter */: return 'InvalidEscapeCharacter';
  1523. case 16 /* InvalidCharacter */: return 'InvalidCharacter';
  1524. }
  1525. return '<unknown ParseErrorCode>';
  1526. }
  1527. exports.printParseErrorCode = printParseErrorCode;
  1528. /**
  1529. * Computes the edits needed to format a JSON document.
  1530. *
  1531. * @param documentText The input text
  1532. * @param range The range to format or `undefined` to format the full content
  1533. * @param options The formatting options
  1534. * @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
  1535. * removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
  1536. * text in the original document. However, multiple edits can have
  1537. * the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
  1538. * To apply edits to an input, you can use `applyEdits`.
  1539. */
  1540. function format(documentText, range, options) {
  1541. return formatter.format(documentText, range, options);
  1542. }
  1543. exports.format = format;
  1544. /**
  1545. * Computes the edits needed to modify a value in the JSON document.
  1546. *
  1547. * @param documentText The input text
  1548. * @param path The path of the value to change. The path represents either to the document root, a property or an array item.
  1549. * If the path points to an non-existing property or item, it will be created.
  1550. * @param value The new value for the specified property or item. If the value is undefined,
  1551. * the property or item will be removed.
  1552. * @param options Options
  1553. * @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
  1554. * removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
  1555. * text in the original document. However, multiple edits can have
  1556. * the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
  1557. * To apply edits to an input, you can use `applyEdits`.
  1558. */
  1559. function modify(text, path, value, options) {
  1560. return edit.setProperty(text, path, value, options);
  1561. }
  1562. exports.modify = modify;
  1563. /**
  1564. * Applies edits to a input string.
  1565. */
  1566. function applyEdits(text, edits) {
  1567. for (var i = edits.length - 1; i >= 0; i--) {
  1568. text = edit.applyEdit(text, edits[i]);
  1569. }
  1570. return text;
  1571. }
  1572. exports.applyEdits = applyEdits;
  1573. });
  1574. define('jsonc-parser', ['jsonc-parser/main'], function (main) { return main; });
  1575. /*---------------------------------------------------------------------------------------------
  1576. * Copyright (c) Microsoft Corporation. All rights reserved.
  1577. * Licensed under the MIT License. See License.txt in the project root for license information.
  1578. *--------------------------------------------------------------------------------------------*/
  1579. (function (factory) {
  1580. if (typeof module === "object" && typeof module.exports === "object") {
  1581. var v = factory(require, exports);
  1582. if (v !== undefined) module.exports = v;
  1583. }
  1584. else if (typeof define === "function" && define.amd) {
  1585. define('vscode-json-languageservice/utils/objects',["require", "exports"], factory);
  1586. }
  1587. })(function (require, exports) {
  1588. "use strict";
  1589. Object.defineProperty(exports, "__esModule", { value: true });
  1590. exports.isString = exports.isBoolean = exports.isDefined = exports.isNumber = exports.equals = void 0;
  1591. function equals(one, other) {
  1592. if (one === other) {
  1593. return true;
  1594. }
  1595. if (one === null || one === undefined || other === null || other === undefined) {
  1596. return false;
  1597. }
  1598. if (typeof one !== typeof other) {
  1599. return false;
  1600. }
  1601. if (typeof one !== 'object') {
  1602. return false;
  1603. }
  1604. if ((Array.isArray(one)) !== (Array.isArray(other))) {
  1605. return false;
  1606. }
  1607. var i, key;
  1608. if (Array.isArray(one)) {
  1609. if (one.length !== other.length) {
  1610. return false;
  1611. }
  1612. for (i = 0; i < one.length; i++) {
  1613. if (!equals(one[i], other[i])) {
  1614. return false;
  1615. }
  1616. }
  1617. }
  1618. else {
  1619. var oneKeys = [];
  1620. for (key in one) {
  1621. oneKeys.push(key);
  1622. }
  1623. oneKeys.sort();
  1624. var otherKeys = [];
  1625. for (key in other) {
  1626. otherKeys.push(key);
  1627. }
  1628. otherKeys.sort();
  1629. if (!equals(oneKeys, otherKeys)) {
  1630. return false;
  1631. }
  1632. for (i = 0; i < oneKeys.length; i++) {
  1633. if (!equals(one[oneKeys[i]], other[oneKeys[i]])) {
  1634. return false;
  1635. }
  1636. }
  1637. }
  1638. return true;
  1639. }
  1640. exports.equals = equals;
  1641. function isNumber(val) {
  1642. return typeof val === 'number';
  1643. }
  1644. exports.isNumber = isNumber;
  1645. function isDefined(val) {
  1646. return typeof val !== 'undefined';
  1647. }
  1648. exports.isDefined = isDefined;
  1649. function isBoolean(val) {
  1650. return typeof val === 'boolean';
  1651. }
  1652. exports.isBoolean = isBoolean;
  1653. function isString(val) {
  1654. return typeof val === 'string';
  1655. }
  1656. exports.isString = isString;
  1657. });
  1658. /*---------------------------------------------------------------------------------------------
  1659. * Copyright (c) Microsoft Corporation. All rights reserved.
  1660. * Licensed under the MIT License. See License.txt in the project root for license information.
  1661. *--------------------------------------------------------------------------------------------*/
  1662. (function (factory) {
  1663. if (typeof module === "object" && typeof module.exports === "object") {
  1664. var v = factory(require, exports);
  1665. if (v !== undefined) module.exports = v;
  1666. }
  1667. else if (typeof define === "function" && define.amd) {
  1668. define('vscode-json-languageservice/utils/strings',["require", "exports"], factory);
  1669. }
  1670. })(function (require, exports) {
  1671. "use strict";
  1672. Object.defineProperty(exports, "__esModule", { value: true });
  1673. exports.extendedRegExp = exports.repeat = exports.convertSimple2RegExpPattern = exports.endsWith = exports.startsWith = void 0;
  1674. function startsWith(haystack, needle) {
  1675. if (haystack.length < needle.length) {
  1676. return false;
  1677. }
  1678. for (var i = 0; i < needle.length; i++) {
  1679. if (haystack[i] !== needle[i]) {
  1680. return false;
  1681. }
  1682. }
  1683. return true;
  1684. }
  1685. exports.startsWith = startsWith;
  1686. /**
  1687. * Determines if haystack ends with needle.
  1688. */
  1689. function endsWith(haystack, needle) {
  1690. var diff = haystack.length - needle.length;
  1691. if (diff > 0) {
  1692. return haystack.lastIndexOf(needle) === diff;
  1693. }
  1694. else if (diff === 0) {
  1695. return haystack === needle;
  1696. }
  1697. else {
  1698. return false;
  1699. }
  1700. }
  1701. exports.endsWith = endsWith;
  1702. function convertSimple2RegExpPattern(pattern) {
  1703. return pattern.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&').replace(/[\*]/g, '.*');
  1704. }
  1705. exports.convertSimple2RegExpPattern = convertSimple2RegExpPattern;
  1706. function repeat(value, count) {
  1707. var s = '';
  1708. while (count > 0) {
  1709. if ((count & 1) === 1) {
  1710. s += value;
  1711. }
  1712. value += value;
  1713. count = count >>> 1;
  1714. }
  1715. return s;
  1716. }
  1717. exports.repeat = repeat;
  1718. function extendedRegExp(pattern) {
  1719. if (startsWith(pattern, '(?i)')) {
  1720. return new RegExp(pattern.substring(4), 'i');
  1721. }
  1722. else {
  1723. return new RegExp(pattern);
  1724. }
  1725. }
  1726. exports.extendedRegExp = extendedRegExp;
  1727. });
  1728. (function (factory) {
  1729. if (typeof module === "object" && typeof module.exports === "object") {
  1730. var v = factory(require, exports);
  1731. if (v !== undefined) module.exports = v;
  1732. }
  1733. else if (typeof define === "function" && define.amd) {
  1734. define('vscode-languageserver-types/main',["require", "exports"], factory);
  1735. }
  1736. })(function (require, exports) {
  1737. /* --------------------------------------------------------------------------------------------
  1738. * Copyright (c) Microsoft Corporation. All rights reserved.
  1739. * Licensed under the MIT License. See License.txt in the project root for license information.
  1740. * ------------------------------------------------------------------------------------------ */
  1741. 'use strict';
  1742. Object.defineProperty(exports, "__esModule", { value: true });
  1743. exports.TextDocument = exports.EOL = exports.SelectionRange = exports.DocumentLink = exports.FormattingOptions = exports.CodeLens = exports.CodeAction = exports.CodeActionContext = exports.CodeActionKind = exports.DocumentSymbol = exports.SymbolInformation = exports.SymbolTag = exports.SymbolKind = exports.DocumentHighlight = exports.DocumentHighlightKind = exports.SignatureInformation = exports.ParameterInformation = exports.Hover = exports.MarkedString = exports.CompletionList = exports.CompletionItem = exports.InsertTextMode = exports.InsertReplaceEdit = exports.CompletionItemTag = exports.InsertTextFormat = exports.CompletionItemKind = exports.MarkupContent = exports.MarkupKind = exports.TextDocumentItem = exports.OptionalVersionedTextDocumentIdentifier = exports.VersionedTextDocumentIdentifier = exports.TextDocumentIdentifier = exports.WorkspaceChange = exports.WorkspaceEdit = exports.DeleteFile = exports.RenameFile = exports.CreateFile = exports.TextDocumentEdit = exports.AnnotatedTextEdit = exports.ChangeAnnotationIdentifier = exports.ChangeAnnotation = exports.TextEdit = exports.Command = exports.Diagnostic = exports.CodeDescription = exports.DiagnosticTag = exports.DiagnosticSeverity = exports.DiagnosticRelatedInformation = exports.FoldingRange = exports.FoldingRangeKind = exports.ColorPresentation = exports.ColorInformation = exports.Color = exports.LocationLink = exports.Location = exports.Range = exports.Position = exports.uinteger = exports.integer = void 0;
  1744. var integer;
  1745. (function (integer) {
  1746. integer.MIN_VALUE = -2147483648;
  1747. integer.MAX_VALUE = 2147483647;
  1748. })(integer = exports.integer || (exports.integer = {}));
  1749. var uinteger;
  1750. (function (uinteger) {
  1751. uinteger.MIN_VALUE = 0;
  1752. uinteger.MAX_VALUE = 2147483647;
  1753. })(uinteger = exports.uinteger || (exports.uinteger = {}));
  1754. /**
  1755. * The Position namespace provides helper functions to work with
  1756. * [Position](#Position) literals.
  1757. */
  1758. var Position;
  1759. (function (Position) {
  1760. /**
  1761. * Creates a new Position literal from the given line and character.
  1762. * @param line The position's line.
  1763. * @param character The position's character.
  1764. */
  1765. function create(line, character) {
  1766. if (line === Number.MAX_VALUE) {
  1767. line = uinteger.MAX_VALUE;
  1768. }
  1769. if (character === Number.MAX_VALUE) {
  1770. character = uinteger.MAX_VALUE;
  1771. }
  1772. return { line: line, character: character };
  1773. }
  1774. Position.create = create;
  1775. /**
  1776. * Checks whether the given literal conforms to the [Position](#Position) interface.
  1777. */
  1778. function is(value) {
  1779. var candidate = value;
  1780. return Is.objectLiteral(candidate) && Is.uinteger(candidate.line) && Is.uinteger(candidate.character);
  1781. }
  1782. Position.is = is;
  1783. })(Position = exports.Position || (exports.Position = {}));
  1784. /**
  1785. * The Range namespace provides helper functions to work with
  1786. * [Range](#Range) literals.
  1787. */
  1788. var Range;
  1789. (function (Range) {
  1790. function create(one, two, three, four) {
  1791. if (Is.uinteger(one) && Is.uinteger(two) && Is.uinteger(three) && Is.uinteger(four)) {
  1792. return { start: Position.create(one, two), end: Position.create(three, four) };
  1793. }
  1794. else if (Position.is(one) && Position.is(two)) {
  1795. return { start: one, end: two };
  1796. }
  1797. else {
  1798. throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
  1799. }
  1800. }
  1801. Range.create = create;
  1802. /**
  1803. * Checks whether the given literal conforms to the [Range](#Range) interface.
  1804. */
  1805. function is(value) {
  1806. var candidate = value;
  1807. return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
  1808. }
  1809. Range.is = is;
  1810. })(Range = exports.Range || (exports.Range = {}));
  1811. /**
  1812. * The Location namespace provides helper functions to work with
  1813. * [Location](#Location) literals.
  1814. */
  1815. var Location;
  1816. (function (Location) {
  1817. /**
  1818. * Creates a Location literal.
  1819. * @param uri The location's uri.
  1820. * @param range The location's range.
  1821. */
  1822. function create(uri, range) {
  1823. return { uri: uri, range: range };
  1824. }
  1825. Location.create = create;
  1826. /**
  1827. * Checks whether the given literal conforms to the [Location](#Location) interface.
  1828. */
  1829. function is(value) {
  1830. var candidate = value;
  1831. return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
  1832. }
  1833. Location.is = is;
  1834. })(Location = exports.Location || (exports.Location = {}));
  1835. /**
  1836. * The LocationLink namespace provides helper functions to work with
  1837. * [LocationLink](#LocationLink) literals.
  1838. */
  1839. var LocationLink;
  1840. (function (LocationLink) {
  1841. /**
  1842. * Creates a LocationLink literal.
  1843. * @param targetUri The definition's uri.
  1844. * @param targetRange The full range of the definition.
  1845. * @param targetSelectionRange The span of the symbol definition at the target.
  1846. * @param originSelectionRange The span of the symbol being defined in the originating source file.
  1847. */
  1848. function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
  1849. return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };
  1850. }
  1851. LocationLink.create = create;
  1852. /**
  1853. * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface.
  1854. */
  1855. function is(value) {
  1856. var candidate = value;
  1857. return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)
  1858. && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange))
  1859. && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
  1860. }
  1861. LocationLink.is = is;
  1862. })(LocationLink = exports.LocationLink || (exports.LocationLink = {}));
  1863. /**
  1864. * The Color namespace provides helper functions to work with
  1865. * [Color](#Color) literals.
  1866. */
  1867. var Color;
  1868. (function (Color) {
  1869. /**
  1870. * Creates a new Color literal.
  1871. */
  1872. function create(red, green, blue, alpha) {
  1873. return {
  1874. red: red,
  1875. green: green,
  1876. blue: blue,
  1877. alpha: alpha,
  1878. };
  1879. }
  1880. Color.create = create;
  1881. /**
  1882. * Checks whether the given literal conforms to the [Color](#Color) interface.
  1883. */
  1884. function is(value) {
  1885. var candidate = value;
  1886. return Is.numberRange(candidate.red, 0, 1)
  1887. && Is.numberRange(candidate.green, 0, 1)
  1888. && Is.numberRange(candidate.blue, 0, 1)
  1889. && Is.numberRange(candidate.alpha, 0, 1);
  1890. }
  1891. Color.is = is;
  1892. })(Color = exports.Color || (exports.Color = {}));
  1893. /**
  1894. * The ColorInformation namespace provides helper functions to work with
  1895. * [ColorInformation](#ColorInformation) literals.
  1896. */
  1897. var ColorInformation;
  1898. (function (ColorInformation) {
  1899. /**
  1900. * Creates a new ColorInformation literal.
  1901. */
  1902. function create(range, color) {
  1903. return {
  1904. range: range,
  1905. color: color,
  1906. };
  1907. }
  1908. ColorInformation.create = create;
  1909. /**
  1910. * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
  1911. */
  1912. function is(value) {
  1913. var candidate = value;
  1914. return Range.is(candidate.range) && Color.is(candidate.color);
  1915. }
  1916. ColorInformation.is = is;
  1917. })(ColorInformation = exports.ColorInformation || (exports.ColorInformation = {}));
  1918. /**
  1919. * The Color namespace provides helper functions to work with
  1920. * [ColorPresentation](#ColorPresentation) literals.
  1921. */
  1922. var ColorPresentation;
  1923. (function (ColorPresentation) {
  1924. /**
  1925. * Creates a new ColorInformation literal.
  1926. */
  1927. function create(label, textEdit, additionalTextEdits) {
  1928. return {
  1929. label: label,
  1930. textEdit: textEdit,
  1931. additionalTextEdits: additionalTextEdits,
  1932. };
  1933. }
  1934. ColorPresentation.create = create;
  1935. /**
  1936. * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
  1937. */
  1938. function is(value) {
  1939. var candidate = value;
  1940. return Is.string(candidate.label)
  1941. && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))
  1942. && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
  1943. }
  1944. ColorPresentation.is = is;
  1945. })(ColorPresentation = exports.ColorPresentation || (exports.ColorPresentation = {}));
  1946. /**
  1947. * Enum of known range kinds
  1948. */
  1949. var FoldingRangeKind;
  1950. (function (FoldingRangeKind) {
  1951. /**
  1952. * Folding range for a comment
  1953. */
  1954. FoldingRangeKind["Comment"] = "comment";
  1955. /**
  1956. * Folding range for a imports or includes
  1957. */
  1958. FoldingRangeKind["Imports"] = "imports";
  1959. /**
  1960. * Folding range for a region (e.g. `#region`)
  1961. */
  1962. FoldingRangeKind["Region"] = "region";
  1963. })(FoldingRangeKind = exports.FoldingRangeKind || (exports.FoldingRangeKind = {}));
  1964. /**
  1965. * The folding range namespace provides helper functions to work with
  1966. * [FoldingRange](#FoldingRange) literals.
  1967. */
  1968. var FoldingRange;
  1969. (function (FoldingRange) {
  1970. /**
  1971. * Creates a new FoldingRange literal.
  1972. */
  1973. function create(startLine, endLine, startCharacter, endCharacter, kind) {
  1974. var result = {
  1975. startLine: startLine,
  1976. endLine: endLine
  1977. };
  1978. if (Is.defined(startCharacter)) {
  1979. result.startCharacter = startCharacter;
  1980. }
  1981. if (Is.defined(endCharacter)) {
  1982. result.endCharacter = endCharacter;
  1983. }
  1984. if (Is.defined(kind)) {
  1985. result.kind = kind;
  1986. }
  1987. return result;
  1988. }
  1989. FoldingRange.create = create;
  1990. /**
  1991. * Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface.
  1992. */
  1993. function is(value) {
  1994. var candidate = value;
  1995. return Is.uinteger(candidate.startLine) && Is.uinteger(candidate.startLine)
  1996. && (Is.undefined(candidate.startCharacter) || Is.uinteger(candidate.startCharacter))
  1997. && (Is.undefined(candidate.endCharacter) || Is.uinteger(candidate.endCharacter))
  1998. && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
  1999. }
  2000. FoldingRange.is = is;
  2001. })(FoldingRange = exports.FoldingRange || (exports.FoldingRange = {}));
  2002. /**
  2003. * The DiagnosticRelatedInformation namespace provides helper functions to work with
  2004. * [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals.
  2005. */
  2006. var DiagnosticRelatedInformation;
  2007. (function (DiagnosticRelatedInformation) {
  2008. /**
  2009. * Creates a new DiagnosticRelatedInformation literal.
  2010. */
  2011. function create(location, message) {
  2012. return {
  2013. location: location,
  2014. message: message
  2015. };
  2016. }
  2017. DiagnosticRelatedInformation.create = create;
  2018. /**
  2019. * Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface.
  2020. */
  2021. function is(value) {
  2022. var candidate = value;
  2023. return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
  2024. }
  2025. DiagnosticRelatedInformation.is = is;
  2026. })(DiagnosticRelatedInformation = exports.DiagnosticRelatedInformation || (exports.DiagnosticRelatedInformation = {}));
  2027. /**
  2028. * The diagnostic's severity.
  2029. */
  2030. var DiagnosticSeverity;
  2031. (function (DiagnosticSeverity) {
  2032. /**
  2033. * Reports an error.
  2034. */
  2035. DiagnosticSeverity.Error = 1;
  2036. /**
  2037. * Reports a warning.
  2038. */
  2039. DiagnosticSeverity.Warning = 2;
  2040. /**
  2041. * Reports an information.
  2042. */
  2043. DiagnosticSeverity.Information = 3;
  2044. /**
  2045. * Reports a hint.
  2046. */
  2047. DiagnosticSeverity.Hint = 4;
  2048. })(DiagnosticSeverity = exports.DiagnosticSeverity || (exports.DiagnosticSeverity = {}));
  2049. /**
  2050. * The diagnostic tags.
  2051. *
  2052. * @since 3.15.0
  2053. */
  2054. var DiagnosticTag;
  2055. (function (DiagnosticTag) {
  2056. /**
  2057. * Unused or unnecessary code.
  2058. *
  2059. * Clients are allowed to render diagnostics with this tag faded out instead of having
  2060. * an error squiggle.
  2061. */
  2062. DiagnosticTag.Unnecessary = 1;
  2063. /**
  2064. * Deprecated or obsolete code.
  2065. *
  2066. * Clients are allowed to rendered diagnostics with this tag strike through.
  2067. */
  2068. DiagnosticTag.Deprecated = 2;
  2069. })(DiagnosticTag = exports.DiagnosticTag || (exports.DiagnosticTag = {}));
  2070. /**
  2071. * The CodeDescription namespace provides functions to deal with descriptions for diagnostic codes.
  2072. *
  2073. * @since 3.16.0
  2074. */
  2075. var CodeDescription;
  2076. (function (CodeDescription) {
  2077. function is(value) {
  2078. var candidate = value;
  2079. return candidate !== undefined && candidate !== null && Is.string(candidate.href);
  2080. }
  2081. CodeDescription.is = is;
  2082. })(CodeDescription = exports.CodeDescription || (exports.CodeDescription = {}));
  2083. /**
  2084. * The Diagnostic namespace provides helper functions to work with
  2085. * [Diagnostic](#Diagnostic) literals.
  2086. */
  2087. var Diagnostic;
  2088. (function (Diagnostic) {
  2089. /**
  2090. * Creates a new Diagnostic literal.
  2091. */
  2092. function create(range, message, severity, code, source, relatedInformation) {
  2093. var result = { range: range, message: message };
  2094. if (Is.defined(severity)) {
  2095. result.severity = severity;
  2096. }
  2097. if (Is.defined(code)) {
  2098. result.code = code;
  2099. }
  2100. if (Is.defined(source)) {
  2101. result.source = source;
  2102. }
  2103. if (Is.defined(relatedInformation)) {
  2104. result.relatedInformation = relatedInformation;
  2105. }
  2106. return result;
  2107. }
  2108. Diagnostic.create = create;
  2109. /**
  2110. * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface.
  2111. */
  2112. function is(value) {
  2113. var _a;
  2114. var candidate = value;
  2115. return Is.defined(candidate)
  2116. && Range.is(candidate.range)
  2117. && Is.string(candidate.message)
  2118. && (Is.number(candidate.severity) || Is.undefined(candidate.severity))
  2119. && (Is.integer(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))
  2120. && (Is.undefined(candidate.codeDescription) || (Is.string((_a = candidate.codeDescription) === null || _a === void 0 ? void 0 : _a.href)))
  2121. && (Is.string(candidate.source) || Is.undefined(candidate.source))
  2122. && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
  2123. }
  2124. Diagnostic.is = is;
  2125. })(Diagnostic = exports.Diagnostic || (exports.Diagnostic = {}));
  2126. /**
  2127. * The Command namespace provides helper functions to work with
  2128. * [Command](#Command) literals.
  2129. */
  2130. var Command;
  2131. (function (Command) {
  2132. /**
  2133. * Creates a new Command literal.
  2134. */
  2135. function create(title, command) {
  2136. var args = [];
  2137. for (var _i = 2; _i < arguments.length; _i++) {
  2138. args[_i - 2] = arguments[_i];
  2139. }
  2140. var result = { title: title, command: command };
  2141. if (Is.defined(args) && args.length > 0) {
  2142. result.arguments = args;
  2143. }
  2144. return result;
  2145. }
  2146. Command.create = create;
  2147. /**
  2148. * Checks whether the given literal conforms to the [Command](#Command) interface.
  2149. */
  2150. function is(value) {
  2151. var candidate = value;
  2152. return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
  2153. }
  2154. Command.is = is;
  2155. })(Command = exports.Command || (exports.Command = {}));
  2156. /**
  2157. * The TextEdit namespace provides helper function to create replace,
  2158. * insert and delete edits more easily.
  2159. */
  2160. var TextEdit;
  2161. (function (TextEdit) {
  2162. /**
  2163. * Creates a replace text edit.
  2164. * @param range The range of text to be replaced.
  2165. * @param newText The new text.
  2166. */
  2167. function replace(range, newText) {
  2168. return { range: range, newText: newText };
  2169. }
  2170. TextEdit.replace = replace;
  2171. /**
  2172. * Creates a insert text edit.
  2173. * @param position The position to insert the text at.
  2174. * @param newText The text to be inserted.
  2175. */
  2176. function insert(position, newText) {
  2177. return { range: { start: position, end: position }, newText: newText };
  2178. }
  2179. TextEdit.insert = insert;
  2180. /**
  2181. * Creates a delete text edit.
  2182. * @param range The range of text to be deleted.
  2183. */
  2184. function del(range) {
  2185. return { range: range, newText: '' };
  2186. }
  2187. TextEdit.del = del;
  2188. function is(value) {
  2189. var candidate = value;
  2190. return Is.objectLiteral(candidate)
  2191. && Is.string(candidate.newText)
  2192. && Range.is(candidate.range);
  2193. }
  2194. TextEdit.is = is;
  2195. })(TextEdit = exports.TextEdit || (exports.TextEdit = {}));
  2196. var ChangeAnnotation;
  2197. (function (ChangeAnnotation) {
  2198. function create(label, needsConfirmation, description) {
  2199. var result = { label: label };
  2200. if (needsConfirmation !== undefined) {
  2201. result.needsConfirmation = needsConfirmation;
  2202. }
  2203. if (description !== undefined) {
  2204. result.description = description;
  2205. }
  2206. return result;
  2207. }
  2208. ChangeAnnotation.create = create;
  2209. function is(value) {
  2210. var candidate = value;
  2211. return candidate !== undefined && Is.objectLiteral(candidate) && Is.string(candidate.label) &&
  2212. (Is.boolean(candidate.needsConfirmation) || candidate.needsConfirmation === undefined) &&
  2213. (Is.string(candidate.description) || candidate.description === undefined);
  2214. }
  2215. ChangeAnnotation.is = is;
  2216. })(ChangeAnnotation = exports.ChangeAnnotation || (exports.ChangeAnnotation = {}));
  2217. var ChangeAnnotationIdentifier;
  2218. (function (ChangeAnnotationIdentifier) {
  2219. function is(value) {
  2220. var candidate = value;
  2221. return typeof candidate === 'string';
  2222. }
  2223. ChangeAnnotationIdentifier.is = is;
  2224. })(ChangeAnnotationIdentifier = exports.ChangeAnnotationIdentifier || (exports.ChangeAnnotationIdentifier = {}));
  2225. var AnnotatedTextEdit;
  2226. (function (AnnotatedTextEdit) {
  2227. /**
  2228. * Creates an annotated replace text edit.
  2229. *
  2230. * @param range The range of text to be replaced.
  2231. * @param newText The new text.
  2232. * @param annotation The annotation.
  2233. */
  2234. function replace(range, newText, annotation) {
  2235. return { range: range, newText: newText, annotationId: annotation };
  2236. }
  2237. AnnotatedTextEdit.replace = replace;
  2238. /**
  2239. * Creates an annotated insert text edit.
  2240. *
  2241. * @param position The position to insert the text at.
  2242. * @param newText The text to be inserted.
  2243. * @param annotation The annotation.
  2244. */
  2245. function insert(position, newText, annotation) {
  2246. return { range: { start: position, end: position }, newText: newText, annotationId: annotation };
  2247. }
  2248. AnnotatedTextEdit.insert = insert;
  2249. /**
  2250. * Creates an annotated delete text edit.
  2251. *
  2252. * @param range The range of text to be deleted.
  2253. * @param annotation The annotation.
  2254. */
  2255. function del(range, annotation) {
  2256. return { range: range, newText: '', annotationId: annotation };
  2257. }
  2258. AnnotatedTextEdit.del = del;
  2259. function is(value) {
  2260. var candidate = value;
  2261. return TextEdit.is(candidate) && (ChangeAnnotation.is(candidate.annotationId) || ChangeAnnotationIdentifier.is(candidate.annotationId));
  2262. }
  2263. AnnotatedTextEdit.is = is;
  2264. })(AnnotatedTextEdit = exports.AnnotatedTextEdit || (exports.AnnotatedTextEdit = {}));
  2265. /**
  2266. * The TextDocumentEdit namespace provides helper function to create
  2267. * an edit that manipulates a text document.
  2268. */
  2269. var TextDocumentEdit;
  2270. (function (TextDocumentEdit) {
  2271. /**
  2272. * Creates a new `TextDocumentEdit`
  2273. */
  2274. function create(textDocument, edits) {
  2275. return { textDocument: textDocument, edits: edits };
  2276. }
  2277. TextDocumentEdit.create = create;
  2278. function is(value) {
  2279. var candidate = value;
  2280. return Is.defined(candidate)
  2281. && OptionalVersionedTextDocumentIdentifier.is(candidate.textDocument)
  2282. && Array.isArray(candidate.edits);
  2283. }
  2284. TextDocumentEdit.is = is;
  2285. })(TextDocumentEdit = exports.TextDocumentEdit || (exports.TextDocumentEdit = {}));
  2286. var CreateFile;
  2287. (function (CreateFile) {
  2288. function create(uri, options, annotation) {
  2289. var result = {
  2290. kind: 'create',
  2291. uri: uri
  2292. };
  2293. if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) {
  2294. result.options = options;
  2295. }
  2296. if (annotation !== undefined) {
  2297. result.annotationId = annotation;
  2298. }
  2299. return result;
  2300. }
  2301. CreateFile.create = create;
  2302. function is(value) {
  2303. var candidate = value;
  2304. return candidate && candidate.kind === 'create' && Is.string(candidate.uri) && (candidate.options === undefined ||
  2305. ((candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists)))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId));
  2306. }
  2307. CreateFile.is = is;
  2308. })(CreateFile = exports.CreateFile || (exports.CreateFile = {}));
  2309. var RenameFile;
  2310. (function (RenameFile) {
  2311. function create(oldUri, newUri, options, annotation) {
  2312. var result = {
  2313. kind: 'rename',
  2314. oldUri: oldUri,
  2315. newUri: newUri
  2316. };
  2317. if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) {
  2318. result.options = options;
  2319. }
  2320. if (annotation !== undefined) {
  2321. result.annotationId = annotation;
  2322. }
  2323. return result;
  2324. }
  2325. RenameFile.create = create;
  2326. function is(value) {
  2327. var candidate = value;
  2328. return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) && (candidate.options === undefined ||
  2329. ((candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists)))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId));
  2330. }
  2331. RenameFile.is = is;
  2332. })(RenameFile = exports.RenameFile || (exports.RenameFile = {}));
  2333. var DeleteFile;
  2334. (function (DeleteFile) {
  2335. function create(uri, options, annotation) {
  2336. var result = {
  2337. kind: 'delete',
  2338. uri: uri
  2339. };
  2340. if (options !== undefined && (options.recursive !== undefined || options.ignoreIfNotExists !== undefined)) {
  2341. result.options = options;
  2342. }
  2343. if (annotation !== undefined) {
  2344. result.annotationId = annotation;
  2345. }
  2346. return result;
  2347. }
  2348. DeleteFile.create = create;
  2349. function is(value) {
  2350. var candidate = value;
  2351. return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) && (candidate.options === undefined ||
  2352. ((candidate.options.recursive === undefined || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === undefined || Is.boolean(candidate.options.ignoreIfNotExists)))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId));
  2353. }
  2354. DeleteFile.is = is;
  2355. })(DeleteFile = exports.DeleteFile || (exports.DeleteFile = {}));
  2356. var WorkspaceEdit;
  2357. (function (WorkspaceEdit) {
  2358. function is(value) {
  2359. var candidate = value;
  2360. return candidate &&
  2361. (candidate.changes !== undefined || candidate.documentChanges !== undefined) &&
  2362. (candidate.documentChanges === undefined || candidate.documentChanges.every(function (change) {
  2363. if (Is.string(change.kind)) {
  2364. return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
  2365. }
  2366. else {
  2367. return TextDocumentEdit.is(change);
  2368. }
  2369. }));
  2370. }
  2371. WorkspaceEdit.is = is;
  2372. })(WorkspaceEdit = exports.WorkspaceEdit || (exports.WorkspaceEdit = {}));
  2373. var TextEditChangeImpl = /** @class */ (function () {
  2374. function TextEditChangeImpl(edits, changeAnnotations) {
  2375. this.edits = edits;
  2376. this.changeAnnotations = changeAnnotations;
  2377. }
  2378. TextEditChangeImpl.prototype.insert = function (position, newText, annotation) {
  2379. var edit;
  2380. var id;
  2381. if (annotation === undefined) {
  2382. edit = TextEdit.insert(position, newText);
  2383. }
  2384. else if (ChangeAnnotationIdentifier.is(annotation)) {
  2385. id = annotation;
  2386. edit = AnnotatedTextEdit.insert(position, newText, annotation);
  2387. }
  2388. else {
  2389. this.assertChangeAnnotations(this.changeAnnotations);
  2390. id = this.changeAnnotations.manage(annotation);
  2391. edit = AnnotatedTextEdit.insert(position, newText, id);
  2392. }
  2393. this.edits.push(edit);
  2394. if (id !== undefined) {
  2395. return id;
  2396. }
  2397. };
  2398. TextEditChangeImpl.prototype.replace = function (range, newText, annotation) {
  2399. var edit;
  2400. var id;
  2401. if (annotation === undefined) {
  2402. edit = TextEdit.replace(range, newText);
  2403. }
  2404. else if (ChangeAnnotationIdentifier.is(annotation)) {
  2405. id = annotation;
  2406. edit = AnnotatedTextEdit.replace(range, newText, annotation);
  2407. }
  2408. else {
  2409. this.assertChangeAnnotations(this.changeAnnotations);
  2410. id = this.changeAnnotations.manage(annotation);
  2411. edit = AnnotatedTextEdit.replace(range, newText, id);
  2412. }
  2413. this.edits.push(edit);
  2414. if (id !== undefined) {
  2415. return id;
  2416. }
  2417. };
  2418. TextEditChangeImpl.prototype.delete = function (range, annotation) {
  2419. var edit;
  2420. var id;
  2421. if (annotation === undefined) {
  2422. edit = TextEdit.del(range);
  2423. }
  2424. else if (ChangeAnnotationIdentifier.is(annotation)) {
  2425. id = annotation;
  2426. edit = AnnotatedTextEdit.del(range, annotation);
  2427. }
  2428. else {
  2429. this.assertChangeAnnotations(this.changeAnnotations);
  2430. id = this.changeAnnotations.manage(annotation);
  2431. edit = AnnotatedTextEdit.del(range, id);
  2432. }
  2433. this.edits.push(edit);
  2434. if (id !== undefined) {
  2435. return id;
  2436. }
  2437. };
  2438. TextEditChangeImpl.prototype.add = function (edit) {
  2439. this.edits.push(edit);
  2440. };
  2441. TextEditChangeImpl.prototype.all = function () {
  2442. return this.edits;
  2443. };
  2444. TextEditChangeImpl.prototype.clear = function () {
  2445. this.edits.splice(0, this.edits.length);
  2446. };
  2447. TextEditChangeImpl.prototype.assertChangeAnnotations = function (value) {
  2448. if (value === undefined) {
  2449. throw new Error("Text edit change is not configured to manage change annotations.");
  2450. }
  2451. };
  2452. return TextEditChangeImpl;
  2453. }());
  2454. /**
  2455. * A helper class
  2456. */
  2457. var ChangeAnnotations = /** @class */ (function () {
  2458. function ChangeAnnotations(annotations) {
  2459. this._annotations = annotations === undefined ? Object.create(null) : annotations;
  2460. this._counter = 0;
  2461. this._size = 0;
  2462. }
  2463. ChangeAnnotations.prototype.all = function () {
  2464. return this._annotations;
  2465. };
  2466. Object.defineProperty(ChangeAnnotations.prototype, "size", {
  2467. get: function () {
  2468. return this._size;
  2469. },
  2470. enumerable: false,
  2471. configurable: true
  2472. });
  2473. ChangeAnnotations.prototype.manage = function (idOrAnnotation, annotation) {
  2474. var id;
  2475. if (ChangeAnnotationIdentifier.is(idOrAnnotation)) {
  2476. id = idOrAnnotation;
  2477. }
  2478. else {
  2479. id = this.nextId();
  2480. annotation = idOrAnnotation;
  2481. }
  2482. if (this._annotations[id] !== undefined) {
  2483. throw new Error("Id " + id + " is already in use.");
  2484. }
  2485. if (annotation === undefined) {
  2486. throw new Error("No annotation provided for id " + id);
  2487. }
  2488. this._annotations[id] = annotation;
  2489. this._size++;
  2490. return id;
  2491. };
  2492. ChangeAnnotations.prototype.nextId = function () {
  2493. this._counter++;
  2494. return this._counter.toString();
  2495. };
  2496. return ChangeAnnotations;
  2497. }());
  2498. /**
  2499. * A workspace change helps constructing changes to a workspace.
  2500. */
  2501. var WorkspaceChange = /** @class */ (function () {
  2502. function WorkspaceChange(workspaceEdit) {
  2503. var _this = this;
  2504. this._textEditChanges = Object.create(null);
  2505. if (workspaceEdit !== undefined) {
  2506. this._workspaceEdit = workspaceEdit;
  2507. if (workspaceEdit.documentChanges) {
  2508. this._changeAnnotations = new ChangeAnnotations(workspaceEdit.changeAnnotations);
  2509. workspaceEdit.changeAnnotations = this._changeAnnotations.all();
  2510. workspaceEdit.documentChanges.forEach(function (change) {
  2511. if (TextDocumentEdit.is(change)) {
  2512. var textEditChange = new TextEditChangeImpl(change.edits, _this._changeAnnotations);
  2513. _this._textEditChanges[change.textDocument.uri] = textEditChange;
  2514. }
  2515. });
  2516. }
  2517. else if (workspaceEdit.changes) {
  2518. Object.keys(workspaceEdit.changes).forEach(function (key) {
  2519. var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
  2520. _this._textEditChanges[key] = textEditChange;
  2521. });
  2522. }
  2523. }
  2524. else {
  2525. this._workspaceEdit = {};
  2526. }
  2527. }
  2528. Object.defineProperty(WorkspaceChange.prototype, "edit", {
  2529. /**
  2530. * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal
  2531. * use to be returned from a workspace edit operation like rename.
  2532. */
  2533. get: function () {
  2534. this.initDocumentChanges();
  2535. if (this._changeAnnotations !== undefined) {
  2536. if (this._changeAnnotations.size === 0) {
  2537. this._workspaceEdit.changeAnnotations = undefined;
  2538. }
  2539. else {
  2540. this._workspaceEdit.changeAnnotations = this._changeAnnotations.all();
  2541. }
  2542. }
  2543. return this._workspaceEdit;
  2544. },
  2545. enumerable: false,
  2546. configurable: true
  2547. });
  2548. WorkspaceChange.prototype.getTextEditChange = function (key) {
  2549. if (OptionalVersionedTextDocumentIdentifier.is(key)) {
  2550. this.initDocumentChanges();
  2551. if (this._workspaceEdit.documentChanges === undefined) {
  2552. throw new Error('Workspace edit is not configured for document changes.');
  2553. }
  2554. var textDocument = { uri: key.uri, version: key.version };
  2555. var result = this._textEditChanges[textDocument.uri];
  2556. if (!result) {
  2557. var edits = [];
  2558. var textDocumentEdit = {
  2559. textDocument: textDocument,
  2560. edits: edits
  2561. };
  2562. this._workspaceEdit.documentChanges.push(textDocumentEdit);
  2563. result = new TextEditChangeImpl(edits, this._changeAnnotations);
  2564. this._textEditChanges[textDocument.uri] = result;
  2565. }
  2566. return result;
  2567. }
  2568. else {
  2569. this.initChanges();
  2570. if (this._workspaceEdit.changes === undefined) {
  2571. throw new Error('Workspace edit is not configured for normal text edit changes.');
  2572. }
  2573. var result = this._textEditChanges[key];
  2574. if (!result) {
  2575. var edits = [];
  2576. this._workspaceEdit.changes[key] = edits;
  2577. result = new TextEditChangeImpl(edits);
  2578. this._textEditChanges[key] = result;
  2579. }
  2580. return result;
  2581. }
  2582. };
  2583. WorkspaceChange.prototype.initDocumentChanges = function () {
  2584. if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) {
  2585. this._changeAnnotations = new ChangeAnnotations();
  2586. this._workspaceEdit.documentChanges = [];
  2587. this._workspaceEdit.changeAnnotations = this._changeAnnotations.all();
  2588. }
  2589. };
  2590. WorkspaceChange.prototype.initChanges = function () {
  2591. if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) {
  2592. this._workspaceEdit.changes = Object.create(null);
  2593. }
  2594. };
  2595. WorkspaceChange.prototype.createFile = function (uri, optionsOrAnnotation, options) {
  2596. this.initDocumentChanges();
  2597. if (this._workspaceEdit.documentChanges === undefined) {
  2598. throw new Error('Workspace edit is not configured for document changes.');
  2599. }
  2600. var annotation;
  2601. if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
  2602. annotation = optionsOrAnnotation;
  2603. }
  2604. else {
  2605. options = optionsOrAnnotation;
  2606. }
  2607. var operation;
  2608. var id;
  2609. if (annotation === undefined) {
  2610. operation = CreateFile.create(uri, options);
  2611. }
  2612. else {
  2613. id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
  2614. operation = CreateFile.create(uri, options, id);
  2615. }
  2616. this._workspaceEdit.documentChanges.push(operation);
  2617. if (id !== undefined) {
  2618. return id;
  2619. }
  2620. };
  2621. WorkspaceChange.prototype.renameFile = function (oldUri, newUri, optionsOrAnnotation, options) {
  2622. this.initDocumentChanges();
  2623. if (this._workspaceEdit.documentChanges === undefined) {
  2624. throw new Error('Workspace edit is not configured for document changes.');
  2625. }
  2626. var annotation;
  2627. if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
  2628. annotation = optionsOrAnnotation;
  2629. }
  2630. else {
  2631. options = optionsOrAnnotation;
  2632. }
  2633. var operation;
  2634. var id;
  2635. if (annotation === undefined) {
  2636. operation = RenameFile.create(oldUri, newUri, options);
  2637. }
  2638. else {
  2639. id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
  2640. operation = RenameFile.create(oldUri, newUri, options, id);
  2641. }
  2642. this._workspaceEdit.documentChanges.push(operation);
  2643. if (id !== undefined) {
  2644. return id;
  2645. }
  2646. };
  2647. WorkspaceChange.prototype.deleteFile = function (uri, optionsOrAnnotation, options) {
  2648. this.initDocumentChanges();
  2649. if (this._workspaceEdit.documentChanges === undefined) {
  2650. throw new Error('Workspace edit is not configured for document changes.');
  2651. }
  2652. var annotation;
  2653. if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
  2654. annotation = optionsOrAnnotation;
  2655. }
  2656. else {
  2657. options = optionsOrAnnotation;
  2658. }
  2659. var operation;
  2660. var id;
  2661. if (annotation === undefined) {
  2662. operation = DeleteFile.create(uri, options);
  2663. }
  2664. else {
  2665. id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
  2666. operation = DeleteFile.create(uri, options, id);
  2667. }
  2668. this._workspaceEdit.documentChanges.push(operation);
  2669. if (id !== undefined) {
  2670. return id;
  2671. }
  2672. };
  2673. return WorkspaceChange;
  2674. }());
  2675. exports.WorkspaceChange = WorkspaceChange;
  2676. /**
  2677. * The TextDocumentIdentifier namespace provides helper functions to work with
  2678. * [TextDocumentIdentifier](#TextDocumentIdentifier) literals.
  2679. */
  2680. var TextDocumentIdentifier;
  2681. (function (TextDocumentIdentifier) {
  2682. /**
  2683. * Creates a new TextDocumentIdentifier literal.
  2684. * @param uri The document's uri.
  2685. */
  2686. function create(uri) {
  2687. return { uri: uri };
  2688. }
  2689. TextDocumentIdentifier.create = create;
  2690. /**
  2691. * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface.
  2692. */
  2693. function is(value) {
  2694. var candidate = value;
  2695. return Is.defined(candidate) && Is.string(candidate.uri);
  2696. }
  2697. TextDocumentIdentifier.is = is;
  2698. })(TextDocumentIdentifier = exports.TextDocumentIdentifier || (exports.TextDocumentIdentifier = {}));
  2699. /**
  2700. * The VersionedTextDocumentIdentifier namespace provides helper functions to work with
  2701. * [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals.
  2702. */
  2703. var VersionedTextDocumentIdentifier;
  2704. (function (VersionedTextDocumentIdentifier) {
  2705. /**
  2706. * Creates a new VersionedTextDocumentIdentifier literal.
  2707. * @param uri The document's uri.
  2708. * @param uri The document's text.
  2709. */
  2710. function create(uri, version) {
  2711. return { uri: uri, version: version };
  2712. }
  2713. VersionedTextDocumentIdentifier.create = create;
  2714. /**
  2715. * Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface.
  2716. */
  2717. function is(value) {
  2718. var candidate = value;
  2719. return Is.defined(candidate) && Is.string(candidate.uri) && Is.integer(candidate.version);
  2720. }
  2721. VersionedTextDocumentIdentifier.is = is;
  2722. })(VersionedTextDocumentIdentifier = exports.VersionedTextDocumentIdentifier || (exports.VersionedTextDocumentIdentifier = {}));
  2723. /**
  2724. * The OptionalVersionedTextDocumentIdentifier namespace provides helper functions to work with
  2725. * [OptionalVersionedTextDocumentIdentifier](#OptionalVersionedTextDocumentIdentifier) literals.
  2726. */
  2727. var OptionalVersionedTextDocumentIdentifier;
  2728. (function (OptionalVersionedTextDocumentIdentifier) {
  2729. /**
  2730. * Creates a new OptionalVersionedTextDocumentIdentifier literal.
  2731. * @param uri The document's uri.
  2732. * @param uri The document's text.
  2733. */
  2734. function create(uri, version) {
  2735. return { uri: uri, version: version };
  2736. }
  2737. OptionalVersionedTextDocumentIdentifier.create = create;
  2738. /**
  2739. * Checks whether the given literal conforms to the [OptionalVersionedTextDocumentIdentifier](#OptionalVersionedTextDocumentIdentifier) interface.
  2740. */
  2741. function is(value) {
  2742. var candidate = value;
  2743. return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.integer(candidate.version));
  2744. }
  2745. OptionalVersionedTextDocumentIdentifier.is = is;
  2746. })(OptionalVersionedTextDocumentIdentifier = exports.OptionalVersionedTextDocumentIdentifier || (exports.OptionalVersionedTextDocumentIdentifier = {}));
  2747. /**
  2748. * The TextDocumentItem namespace provides helper functions to work with
  2749. * [TextDocumentItem](#TextDocumentItem) literals.
  2750. */
  2751. var TextDocumentItem;
  2752. (function (TextDocumentItem) {
  2753. /**
  2754. * Creates a new TextDocumentItem literal.
  2755. * @param uri The document's uri.
  2756. * @param languageId The document's language identifier.
  2757. * @param version The document's version number.
  2758. * @param text The document's text.
  2759. */
  2760. function create(uri, languageId, version, text) {
  2761. return { uri: uri, languageId: languageId, version: version, text: text };
  2762. }
  2763. TextDocumentItem.create = create;
  2764. /**
  2765. * Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface.
  2766. */
  2767. function is(value) {
  2768. var candidate = value;
  2769. return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.integer(candidate.version) && Is.string(candidate.text);
  2770. }
  2771. TextDocumentItem.is = is;
  2772. })(TextDocumentItem = exports.TextDocumentItem || (exports.TextDocumentItem = {}));
  2773. /**
  2774. * Describes the content type that a client supports in various
  2775. * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
  2776. *
  2777. * Please note that `MarkupKinds` must not start with a `$`. This kinds
  2778. * are reserved for internal usage.
  2779. */
  2780. var MarkupKind;
  2781. (function (MarkupKind) {
  2782. /**
  2783. * Plain text is supported as a content format
  2784. */
  2785. MarkupKind.PlainText = 'plaintext';
  2786. /**
  2787. * Markdown is supported as a content format
  2788. */
  2789. MarkupKind.Markdown = 'markdown';
  2790. })(MarkupKind = exports.MarkupKind || (exports.MarkupKind = {}));
  2791. (function (MarkupKind) {
  2792. /**
  2793. * Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type.
  2794. */
  2795. function is(value) {
  2796. var candidate = value;
  2797. return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;
  2798. }
  2799. MarkupKind.is = is;
  2800. })(MarkupKind = exports.MarkupKind || (exports.MarkupKind = {}));
  2801. var MarkupContent;
  2802. (function (MarkupContent) {
  2803. /**
  2804. * Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface.
  2805. */
  2806. function is(value) {
  2807. var candidate = value;
  2808. return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
  2809. }
  2810. MarkupContent.is = is;
  2811. })(MarkupContent = exports.MarkupContent || (exports.MarkupContent = {}));
  2812. /**
  2813. * The kind of a completion entry.
  2814. */
  2815. var CompletionItemKind;
  2816. (function (CompletionItemKind) {
  2817. CompletionItemKind.Text = 1;
  2818. CompletionItemKind.Method = 2;
  2819. CompletionItemKind.Function = 3;
  2820. CompletionItemKind.Constructor = 4;
  2821. CompletionItemKind.Field = 5;
  2822. CompletionItemKind.Variable = 6;
  2823. CompletionItemKind.Class = 7;
  2824. CompletionItemKind.Interface = 8;
  2825. CompletionItemKind.Module = 9;
  2826. CompletionItemKind.Property = 10;
  2827. CompletionItemKind.Unit = 11;
  2828. CompletionItemKind.Value = 12;
  2829. CompletionItemKind.Enum = 13;
  2830. CompletionItemKind.Keyword = 14;
  2831. CompletionItemKind.Snippet = 15;
  2832. CompletionItemKind.Color = 16;
  2833. CompletionItemKind.File = 17;
  2834. CompletionItemKind.Reference = 18;
  2835. CompletionItemKind.Folder = 19;
  2836. CompletionItemKind.EnumMember = 20;
  2837. CompletionItemKind.Constant = 21;
  2838. CompletionItemKind.Struct = 22;
  2839. CompletionItemKind.Event = 23;
  2840. CompletionItemKind.Operator = 24;
  2841. CompletionItemKind.TypeParameter = 25;
  2842. })(CompletionItemKind = exports.CompletionItemKind || (exports.CompletionItemKind = {}));
  2843. /**
  2844. * Defines whether the insert text in a completion item should be interpreted as
  2845. * plain text or a snippet.
  2846. */
  2847. var InsertTextFormat;
  2848. (function (InsertTextFormat) {
  2849. /**
  2850. * The primary text to be inserted is treated as a plain string.
  2851. */
  2852. InsertTextFormat.PlainText = 1;
  2853. /**
  2854. * The primary text to be inserted is treated as a snippet.
  2855. *
  2856. * A snippet can define tab stops and placeholders with `$1`, `$2`
  2857. * and `${3:foo}`. `$0` defines the final tab stop, it defaults to
  2858. * the end of the snippet. Placeholders with equal identifiers are linked,
  2859. * that is typing in one will update others too.
  2860. *
  2861. * See also: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#snippet_syntax
  2862. */
  2863. InsertTextFormat.Snippet = 2;
  2864. })(InsertTextFormat = exports.InsertTextFormat || (exports.InsertTextFormat = {}));
  2865. /**
  2866. * Completion item tags are extra annotations that tweak the rendering of a completion
  2867. * item.
  2868. *
  2869. * @since 3.15.0
  2870. */
  2871. var CompletionItemTag;
  2872. (function (CompletionItemTag) {
  2873. /**
  2874. * Render a completion as obsolete, usually using a strike-out.
  2875. */
  2876. CompletionItemTag.Deprecated = 1;
  2877. })(CompletionItemTag = exports.CompletionItemTag || (exports.CompletionItemTag = {}));
  2878. /**
  2879. * The InsertReplaceEdit namespace provides functions to deal with insert / replace edits.
  2880. *
  2881. * @since 3.16.0
  2882. */
  2883. var InsertReplaceEdit;
  2884. (function (InsertReplaceEdit) {
  2885. /**
  2886. * Creates a new insert / replace edit
  2887. */
  2888. function create(newText, insert, replace) {
  2889. return { newText: newText, insert: insert, replace: replace };
  2890. }
  2891. InsertReplaceEdit.create = create;
  2892. /**
  2893. * Checks whether the given literal conforms to the [InsertReplaceEdit](#InsertReplaceEdit) interface.
  2894. */
  2895. function is(value) {
  2896. var candidate = value;
  2897. return candidate && Is.string(candidate.newText) && Range.is(candidate.insert) && Range.is(candidate.replace);
  2898. }
  2899. InsertReplaceEdit.is = is;
  2900. })(InsertReplaceEdit = exports.InsertReplaceEdit || (exports.InsertReplaceEdit = {}));
  2901. /**
  2902. * How whitespace and indentation is handled during completion
  2903. * item insertion.
  2904. *
  2905. * @since 3.16.0
  2906. */
  2907. var InsertTextMode;
  2908. (function (InsertTextMode) {
  2909. /**
  2910. * The insertion or replace strings is taken as it is. If the
  2911. * value is multi line the lines below the cursor will be
  2912. * inserted using the indentation defined in the string value.
  2913. * The client will not apply any kind of adjustments to the
  2914. * string.
  2915. */
  2916. InsertTextMode.asIs = 1;
  2917. /**
  2918. * The editor adjusts leading whitespace of new lines so that
  2919. * they match the indentation up to the cursor of the line for
  2920. * which the item is accepted.
  2921. *
  2922. * Consider a line like this: <2tabs><cursor><3tabs>foo. Accepting a
  2923. * multi line completion item is indented using 2 tabs and all
  2924. * following lines inserted will be indented using 2 tabs as well.
  2925. */
  2926. InsertTextMode.adjustIndentation = 2;
  2927. })(InsertTextMode = exports.InsertTextMode || (exports.InsertTextMode = {}));
  2928. /**
  2929. * The CompletionItem namespace provides functions to deal with
  2930. * completion items.
  2931. */
  2932. var CompletionItem;
  2933. (function (CompletionItem) {
  2934. /**
  2935. * Create a completion item and seed it with a label.
  2936. * @param label The completion item's label
  2937. */
  2938. function create(label) {
  2939. return { label: label };
  2940. }
  2941. CompletionItem.create = create;
  2942. })(CompletionItem = exports.CompletionItem || (exports.CompletionItem = {}));
  2943. /**
  2944. * The CompletionList namespace provides functions to deal with
  2945. * completion lists.
  2946. */
  2947. var CompletionList;
  2948. (function (CompletionList) {
  2949. /**
  2950. * Creates a new completion list.
  2951. *
  2952. * @param items The completion items.
  2953. * @param isIncomplete The list is not complete.
  2954. */
  2955. function create(items, isIncomplete) {
  2956. return { items: items ? items : [], isIncomplete: !!isIncomplete };
  2957. }
  2958. CompletionList.create = create;
  2959. })(CompletionList = exports.CompletionList || (exports.CompletionList = {}));
  2960. var MarkedString;
  2961. (function (MarkedString) {
  2962. /**
  2963. * Creates a marked string from plain text.
  2964. *
  2965. * @param plainText The plain text.
  2966. */
  2967. function fromPlainText(plainText) {
  2968. return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
  2969. }
  2970. MarkedString.fromPlainText = fromPlainText;
  2971. /**
  2972. * Checks whether the given value conforms to the [MarkedString](#MarkedString) type.
  2973. */
  2974. function is(value) {
  2975. var candidate = value;
  2976. return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));
  2977. }
  2978. MarkedString.is = is;
  2979. })(MarkedString = exports.MarkedString || (exports.MarkedString = {}));
  2980. var Hover;
  2981. (function (Hover) {
  2982. /**
  2983. * Checks whether the given value conforms to the [Hover](#Hover) interface.
  2984. */
  2985. function is(value) {
  2986. var candidate = value;
  2987. return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||
  2988. MarkedString.is(candidate.contents) ||
  2989. Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === undefined || Range.is(value.range));
  2990. }
  2991. Hover.is = is;
  2992. })(Hover = exports.Hover || (exports.Hover = {}));
  2993. /**
  2994. * The ParameterInformation namespace provides helper functions to work with
  2995. * [ParameterInformation](#ParameterInformation) literals.
  2996. */
  2997. var ParameterInformation;
  2998. (function (ParameterInformation) {
  2999. /**
  3000. * Creates a new parameter information literal.
  3001. *
  3002. * @param label A label string.
  3003. * @param documentation A doc string.
  3004. */
  3005. function create(label, documentation) {
  3006. return documentation ? { label: label, documentation: documentation } : { label: label };
  3007. }
  3008. ParameterInformation.create = create;
  3009. })(ParameterInformation = exports.ParameterInformation || (exports.ParameterInformation = {}));
  3010. /**
  3011. * The SignatureInformation namespace provides helper functions to work with
  3012. * [SignatureInformation](#SignatureInformation) literals.
  3013. */
  3014. var SignatureInformation;
  3015. (function (SignatureInformation) {
  3016. function create(label, documentation) {
  3017. var parameters = [];
  3018. for (var _i = 2; _i < arguments.length; _i++) {
  3019. parameters[_i - 2] = arguments[_i];
  3020. }
  3021. var result = { label: label };
  3022. if (Is.defined(documentation)) {
  3023. result.documentation = documentation;
  3024. }
  3025. if (Is.defined(parameters)) {
  3026. result.parameters = parameters;
  3027. }
  3028. else {
  3029. result.parameters = [];
  3030. }
  3031. return result;
  3032. }
  3033. SignatureInformation.create = create;
  3034. })(SignatureInformation = exports.SignatureInformation || (exports.SignatureInformation = {}));
  3035. /**
  3036. * A document highlight kind.
  3037. */
  3038. var DocumentHighlightKind;
  3039. (function (DocumentHighlightKind) {
  3040. /**
  3041. * A textual occurrence.
  3042. */
  3043. DocumentHighlightKind.Text = 1;
  3044. /**
  3045. * Read-access of a symbol, like reading a variable.
  3046. */
  3047. DocumentHighlightKind.Read = 2;
  3048. /**
  3049. * Write-access of a symbol, like writing to a variable.
  3050. */
  3051. DocumentHighlightKind.Write = 3;
  3052. })(DocumentHighlightKind = exports.DocumentHighlightKind || (exports.DocumentHighlightKind = {}));
  3053. /**
  3054. * DocumentHighlight namespace to provide helper functions to work with
  3055. * [DocumentHighlight](#DocumentHighlight) literals.
  3056. */
  3057. var DocumentHighlight;
  3058. (function (DocumentHighlight) {
  3059. /**
  3060. * Create a DocumentHighlight object.
  3061. * @param range The range the highlight applies to.
  3062. */
  3063. function create(range, kind) {
  3064. var result = { range: range };
  3065. if (Is.number(kind)) {
  3066. result.kind = kind;
  3067. }
  3068. return result;
  3069. }
  3070. DocumentHighlight.create = create;
  3071. })(DocumentHighlight = exports.DocumentHighlight || (exports.DocumentHighlight = {}));
  3072. /**
  3073. * A symbol kind.
  3074. */
  3075. var SymbolKind;
  3076. (function (SymbolKind) {
  3077. SymbolKind.File = 1;
  3078. SymbolKind.Module = 2;
  3079. SymbolKind.Namespace = 3;
  3080. SymbolKind.Package = 4;
  3081. SymbolKind.Class = 5;
  3082. SymbolKind.Method = 6;
  3083. SymbolKind.Property = 7;
  3084. SymbolKind.Field = 8;
  3085. SymbolKind.Constructor = 9;
  3086. SymbolKind.Enum = 10;
  3087. SymbolKind.Interface = 11;
  3088. SymbolKind.Function = 12;
  3089. SymbolKind.Variable = 13;
  3090. SymbolKind.Constant = 14;
  3091. SymbolKind.String = 15;
  3092. SymbolKind.Number = 16;
  3093. SymbolKind.Boolean = 17;
  3094. SymbolKind.Array = 18;
  3095. SymbolKind.Object = 19;
  3096. SymbolKind.Key = 20;
  3097. SymbolKind.Null = 21;
  3098. SymbolKind.EnumMember = 22;
  3099. SymbolKind.Struct = 23;
  3100. SymbolKind.Event = 24;
  3101. SymbolKind.Operator = 25;
  3102. SymbolKind.TypeParameter = 26;
  3103. })(SymbolKind = exports.SymbolKind || (exports.SymbolKind = {}));
  3104. /**
  3105. * Symbol tags are extra annotations that tweak the rendering of a symbol.
  3106. * @since 3.16
  3107. */
  3108. var SymbolTag;
  3109. (function (SymbolTag) {
  3110. /**
  3111. * Render a symbol as obsolete, usually using a strike-out.
  3112. */
  3113. SymbolTag.Deprecated = 1;
  3114. })(SymbolTag = exports.SymbolTag || (exports.SymbolTag = {}));
  3115. var SymbolInformation;
  3116. (function (SymbolInformation) {
  3117. /**
  3118. * Creates a new symbol information literal.
  3119. *
  3120. * @param name The name of the symbol.
  3121. * @param kind The kind of the symbol.
  3122. * @param range The range of the location of the symbol.
  3123. * @param uri The resource of the location of symbol, defaults to the current document.
  3124. * @param containerName The name of the symbol containing the symbol.
  3125. */
  3126. function create(name, kind, range, uri, containerName) {
  3127. var result = {
  3128. name: name,
  3129. kind: kind,
  3130. location: { uri: uri, range: range }
  3131. };
  3132. if (containerName) {
  3133. result.containerName = containerName;
  3134. }
  3135. return result;
  3136. }
  3137. SymbolInformation.create = create;
  3138. })(SymbolInformation = exports.SymbolInformation || (exports.SymbolInformation = {}));
  3139. var DocumentSymbol;
  3140. (function (DocumentSymbol) {
  3141. /**
  3142. * Creates a new symbol information literal.
  3143. *
  3144. * @param name The name of the symbol.
  3145. * @param detail The detail of the symbol.
  3146. * @param kind The kind of the symbol.
  3147. * @param range The range of the symbol.
  3148. * @param selectionRange The selectionRange of the symbol.
  3149. * @param children Children of the symbol.
  3150. */
  3151. function create(name, detail, kind, range, selectionRange, children) {
  3152. var result = {
  3153. name: name,
  3154. detail: detail,
  3155. kind: kind,
  3156. range: range,
  3157. selectionRange: selectionRange
  3158. };
  3159. if (children !== undefined) {
  3160. result.children = children;
  3161. }
  3162. return result;
  3163. }
  3164. DocumentSymbol.create = create;
  3165. /**
  3166. * Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface.
  3167. */
  3168. function is(value) {
  3169. var candidate = value;
  3170. return candidate &&
  3171. Is.string(candidate.name) && Is.number(candidate.kind) &&
  3172. Range.is(candidate.range) && Range.is(candidate.selectionRange) &&
  3173. (candidate.detail === undefined || Is.string(candidate.detail)) &&
  3174. (candidate.deprecated === undefined || Is.boolean(candidate.deprecated)) &&
  3175. (candidate.children === undefined || Array.isArray(candidate.children)) &&
  3176. (candidate.tags === undefined || Array.isArray(candidate.tags));
  3177. }
  3178. DocumentSymbol.is = is;
  3179. })(DocumentSymbol = exports.DocumentSymbol || (exports.DocumentSymbol = {}));
  3180. /**
  3181. * A set of predefined code action kinds
  3182. */
  3183. var CodeActionKind;
  3184. (function (CodeActionKind) {
  3185. /**
  3186. * Empty kind.
  3187. */
  3188. CodeActionKind.Empty = '';
  3189. /**
  3190. * Base kind for quickfix actions: 'quickfix'
  3191. */
  3192. CodeActionKind.QuickFix = 'quickfix';
  3193. /**
  3194. * Base kind for refactoring actions: 'refactor'
  3195. */
  3196. CodeActionKind.Refactor = 'refactor';
  3197. /**
  3198. * Base kind for refactoring extraction actions: 'refactor.extract'
  3199. *
  3200. * Example extract actions:
  3201. *
  3202. * - Extract method
  3203. * - Extract function
  3204. * - Extract variable
  3205. * - Extract interface from class
  3206. * - ...
  3207. */
  3208. CodeActionKind.RefactorExtract = 'refactor.extract';
  3209. /**
  3210. * Base kind for refactoring inline actions: 'refactor.inline'
  3211. *
  3212. * Example inline actions:
  3213. *
  3214. * - Inline function
  3215. * - Inline variable
  3216. * - Inline constant
  3217. * - ...
  3218. */
  3219. CodeActionKind.RefactorInline = 'refactor.inline';
  3220. /**
  3221. * Base kind for refactoring rewrite actions: 'refactor.rewrite'
  3222. *
  3223. * Example rewrite actions:
  3224. *
  3225. * - Convert JavaScript function to class
  3226. * - Add or remove parameter
  3227. * - Encapsulate field
  3228. * - Make method static
  3229. * - Move method to base class
  3230. * - ...
  3231. */
  3232. CodeActionKind.RefactorRewrite = 'refactor.rewrite';
  3233. /**
  3234. * Base kind for source actions: `source`
  3235. *
  3236. * Source code actions apply to the entire file.
  3237. */
  3238. CodeActionKind.Source = 'source';
  3239. /**
  3240. * Base kind for an organize imports source action: `source.organizeImports`
  3241. */
  3242. CodeActionKind.SourceOrganizeImports = 'source.organizeImports';
  3243. /**
  3244. * Base kind for auto-fix source actions: `source.fixAll`.
  3245. *
  3246. * Fix all actions automatically fix errors that have a clear fix that do not require user input.
  3247. * They should not suppress errors or perform unsafe fixes such as generating new types or classes.
  3248. *
  3249. * @since 3.15.0
  3250. */
  3251. CodeActionKind.SourceFixAll = 'source.fixAll';
  3252. })(CodeActionKind = exports.CodeActionKind || (exports.CodeActionKind = {}));
  3253. /**
  3254. * The CodeActionContext namespace provides helper functions to work with
  3255. * [CodeActionContext](#CodeActionContext) literals.
  3256. */
  3257. var CodeActionContext;
  3258. (function (CodeActionContext) {
  3259. /**
  3260. * Creates a new CodeActionContext literal.
  3261. */
  3262. function create(diagnostics, only) {
  3263. var result = { diagnostics: diagnostics };
  3264. if (only !== undefined && only !== null) {
  3265. result.only = only;
  3266. }
  3267. return result;
  3268. }
  3269. CodeActionContext.create = create;
  3270. /**
  3271. * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface.
  3272. */
  3273. function is(value) {
  3274. var candidate = value;
  3275. return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === undefined || Is.typedArray(candidate.only, Is.string));
  3276. }
  3277. CodeActionContext.is = is;
  3278. })(CodeActionContext = exports.CodeActionContext || (exports.CodeActionContext = {}));
  3279. var CodeAction;
  3280. (function (CodeAction) {
  3281. function create(title, kindOrCommandOrEdit, kind) {
  3282. var result = { title: title };
  3283. var checkKind = true;
  3284. if (typeof kindOrCommandOrEdit === 'string') {
  3285. checkKind = false;
  3286. result.kind = kindOrCommandOrEdit;
  3287. }
  3288. else if (Command.is(kindOrCommandOrEdit)) {
  3289. result.command = kindOrCommandOrEdit;
  3290. }
  3291. else {
  3292. result.edit = kindOrCommandOrEdit;
  3293. }
  3294. if (checkKind && kind !== undefined) {
  3295. result.kind = kind;
  3296. }
  3297. return result;
  3298. }
  3299. CodeAction.create = create;
  3300. function is(value) {
  3301. var candidate = value;
  3302. return candidate && Is.string(candidate.title) &&
  3303. (candidate.diagnostics === undefined || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&
  3304. (candidate.kind === undefined || Is.string(candidate.kind)) &&
  3305. (candidate.edit !== undefined || candidate.command !== undefined) &&
  3306. (candidate.command === undefined || Command.is(candidate.command)) &&
  3307. (candidate.isPreferred === undefined || Is.boolean(candidate.isPreferred)) &&
  3308. (candidate.edit === undefined || WorkspaceEdit.is(candidate.edit));
  3309. }
  3310. CodeAction.is = is;
  3311. })(CodeAction = exports.CodeAction || (exports.CodeAction = {}));
  3312. /**
  3313. * The CodeLens namespace provides helper functions to work with
  3314. * [CodeLens](#CodeLens) literals.
  3315. */
  3316. var CodeLens;
  3317. (function (CodeLens) {
  3318. /**
  3319. * Creates a new CodeLens literal.
  3320. */
  3321. function create(range, data) {
  3322. var result = { range: range };
  3323. if (Is.defined(data)) {
  3324. result.data = data;
  3325. }
  3326. return result;
  3327. }
  3328. CodeLens.create = create;
  3329. /**
  3330. * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface.
  3331. */
  3332. function is(value) {
  3333. var candidate = value;
  3334. return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
  3335. }
  3336. CodeLens.is = is;
  3337. })(CodeLens = exports.CodeLens || (exports.CodeLens = {}));
  3338. /**
  3339. * The FormattingOptions namespace provides helper functions to work with
  3340. * [FormattingOptions](#FormattingOptions) literals.
  3341. */
  3342. var FormattingOptions;
  3343. (function (FormattingOptions) {
  3344. /**
  3345. * Creates a new FormattingOptions literal.
  3346. */
  3347. function create(tabSize, insertSpaces) {
  3348. return { tabSize: tabSize, insertSpaces: insertSpaces };
  3349. }
  3350. FormattingOptions.create = create;
  3351. /**
  3352. * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface.
  3353. */
  3354. function is(value) {
  3355. var candidate = value;
  3356. return Is.defined(candidate) && Is.uinteger(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
  3357. }
  3358. FormattingOptions.is = is;
  3359. })(FormattingOptions = exports.FormattingOptions || (exports.FormattingOptions = {}));
  3360. /**
  3361. * The DocumentLink namespace provides helper functions to work with
  3362. * [DocumentLink](#DocumentLink) literals.
  3363. */
  3364. var DocumentLink;
  3365. (function (DocumentLink) {
  3366. /**
  3367. * Creates a new DocumentLink literal.
  3368. */
  3369. function create(range, target, data) {
  3370. return { range: range, target: target, data: data };
  3371. }
  3372. DocumentLink.create = create;
  3373. /**
  3374. * Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface.
  3375. */
  3376. function is(value) {
  3377. var candidate = value;
  3378. return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
  3379. }
  3380. DocumentLink.is = is;
  3381. })(DocumentLink = exports.DocumentLink || (exports.DocumentLink = {}));
  3382. /**
  3383. * The SelectionRange namespace provides helper function to work with
  3384. * SelectionRange literals.
  3385. */
  3386. var SelectionRange;
  3387. (function (SelectionRange) {
  3388. /**
  3389. * Creates a new SelectionRange
  3390. * @param range the range.
  3391. * @param parent an optional parent.
  3392. */
  3393. function create(range, parent) {
  3394. return { range: range, parent: parent };
  3395. }
  3396. SelectionRange.create = create;
  3397. function is(value) {
  3398. var candidate = value;
  3399. return candidate !== undefined && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));
  3400. }
  3401. SelectionRange.is = is;
  3402. })(SelectionRange = exports.SelectionRange || (exports.SelectionRange = {}));
  3403. exports.EOL = ['\n', '\r\n', '\r'];
  3404. /**
  3405. * @deprecated Use the text document from the new vscode-languageserver-textdocument package.
  3406. */
  3407. var TextDocument;
  3408. (function (TextDocument) {
  3409. /**
  3410. * Creates a new ITextDocument literal from the given uri and content.
  3411. * @param uri The document's uri.
  3412. * @param languageId The document's language Id.
  3413. * @param content The document's content.
  3414. */
  3415. function create(uri, languageId, version, content) {
  3416. return new FullTextDocument(uri, languageId, version, content);
  3417. }
  3418. TextDocument.create = create;
  3419. /**
  3420. * Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface.
  3421. */
  3422. function is(value) {
  3423. var candidate = value;
  3424. return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.uinteger(candidate.lineCount)
  3425. && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
  3426. }
  3427. TextDocument.is = is;
  3428. function applyEdits(document, edits) {
  3429. var text = document.getText();
  3430. var sortedEdits = mergeSort(edits, function (a, b) {
  3431. var diff = a.range.start.line - b.range.start.line;
  3432. if (diff === 0) {
  3433. return a.range.start.character - b.range.start.character;
  3434. }
  3435. return diff;
  3436. });
  3437. var lastModifiedOffset = text.length;
  3438. for (var i = sortedEdits.length - 1; i >= 0; i--) {
  3439. var e = sortedEdits[i];
  3440. var startOffset = document.offsetAt(e.range.start);
  3441. var endOffset = document.offsetAt(e.range.end);
  3442. if (endOffset <= lastModifiedOffset) {
  3443. text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
  3444. }
  3445. else {
  3446. throw new Error('Overlapping edit');
  3447. }
  3448. lastModifiedOffset = startOffset;
  3449. }
  3450. return text;
  3451. }
  3452. TextDocument.applyEdits = applyEdits;
  3453. function mergeSort(data, compare) {
  3454. if (data.length <= 1) {
  3455. // sorted
  3456. return data;
  3457. }
  3458. var p = (data.length / 2) | 0;
  3459. var left = data.slice(0, p);
  3460. var right = data.slice(p);
  3461. mergeSort(left, compare);
  3462. mergeSort(right, compare);
  3463. var leftIdx = 0;
  3464. var rightIdx = 0;
  3465. var i = 0;
  3466. while (leftIdx < left.length && rightIdx < right.length) {
  3467. var ret = compare(left[leftIdx], right[rightIdx]);
  3468. if (ret <= 0) {
  3469. // smaller_equal -> take left to preserve order
  3470. data[i++] = left[leftIdx++];
  3471. }
  3472. else {
  3473. // greater -> take right
  3474. data[i++] = right[rightIdx++];
  3475. }
  3476. }
  3477. while (leftIdx < left.length) {
  3478. data[i++] = left[leftIdx++];
  3479. }
  3480. while (rightIdx < right.length) {
  3481. data[i++] = right[rightIdx++];
  3482. }
  3483. return data;
  3484. }
  3485. })(TextDocument = exports.TextDocument || (exports.TextDocument = {}));
  3486. /**
  3487. * @deprecated Use the text document from the new vscode-languageserver-textdocument package.
  3488. */
  3489. var FullTextDocument = /** @class */ (function () {
  3490. function FullTextDocument(uri, languageId, version, content) {
  3491. this._uri = uri;
  3492. this._languageId = languageId;
  3493. this._version = version;
  3494. this._content = content;
  3495. this._lineOffsets = undefined;
  3496. }
  3497. Object.defineProperty(FullTextDocument.prototype, "uri", {
  3498. get: function () {
  3499. return this._uri;
  3500. },
  3501. enumerable: false,
  3502. configurable: true
  3503. });
  3504. Object.defineProperty(FullTextDocument.prototype, "languageId", {
  3505. get: function () {
  3506. return this._languageId;
  3507. },
  3508. enumerable: false,
  3509. configurable: true
  3510. });
  3511. Object.defineProperty(FullTextDocument.prototype, "version", {
  3512. get: function () {
  3513. return this._version;
  3514. },
  3515. enumerable: false,
  3516. configurable: true
  3517. });
  3518. FullTextDocument.prototype.getText = function (range) {
  3519. if (range) {
  3520. var start = this.offsetAt(range.start);
  3521. var end = this.offsetAt(range.end);
  3522. return this._content.substring(start, end);
  3523. }
  3524. return this._content;
  3525. };
  3526. FullTextDocument.prototype.update = function (event, version) {
  3527. this._content = event.text;
  3528. this._version = version;
  3529. this._lineOffsets = undefined;
  3530. };
  3531. FullTextDocument.prototype.getLineOffsets = function () {
  3532. if (this._lineOffsets === undefined) {
  3533. var lineOffsets = [];
  3534. var text = this._content;
  3535. var isLineStart = true;
  3536. for (var i = 0; i < text.length; i++) {
  3537. if (isLineStart) {
  3538. lineOffsets.push(i);
  3539. isLineStart = false;
  3540. }
  3541. var ch = text.charAt(i);
  3542. isLineStart = (ch === '\r' || ch === '\n');
  3543. if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {
  3544. i++;
  3545. }
  3546. }
  3547. if (isLineStart && text.length > 0) {
  3548. lineOffsets.push(text.length);
  3549. }
  3550. this._lineOffsets = lineOffsets;
  3551. }
  3552. return this._lineOffsets;
  3553. };
  3554. FullTextDocument.prototype.positionAt = function (offset) {
  3555. offset = Math.max(Math.min(offset, this._content.length), 0);
  3556. var lineOffsets = this.getLineOffsets();
  3557. var low = 0, high = lineOffsets.length;
  3558. if (high === 0) {
  3559. return Position.create(0, offset);
  3560. }
  3561. while (low < high) {
  3562. var mid = Math.floor((low + high) / 2);
  3563. if (lineOffsets[mid] > offset) {
  3564. high = mid;
  3565. }
  3566. else {
  3567. low = mid + 1;
  3568. }
  3569. }
  3570. // low is the least x for which the line offset is larger than the current offset
  3571. // or array.length if no line offset is larger than the current offset
  3572. var line = low - 1;
  3573. return Position.create(line, offset - lineOffsets[line]);
  3574. };
  3575. FullTextDocument.prototype.offsetAt = function (position) {
  3576. var lineOffsets = this.getLineOffsets();
  3577. if (position.line >= lineOffsets.length) {
  3578. return this._content.length;
  3579. }
  3580. else if (position.line < 0) {
  3581. return 0;
  3582. }
  3583. var lineOffset = lineOffsets[position.line];
  3584. var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
  3585. return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
  3586. };
  3587. Object.defineProperty(FullTextDocument.prototype, "lineCount", {
  3588. get: function () {
  3589. return this.getLineOffsets().length;
  3590. },
  3591. enumerable: false,
  3592. configurable: true
  3593. });
  3594. return FullTextDocument;
  3595. }());
  3596. var Is;
  3597. (function (Is) {
  3598. var toString = Object.prototype.toString;
  3599. function defined(value) {
  3600. return typeof value !== 'undefined';
  3601. }
  3602. Is.defined = defined;
  3603. function undefined(value) {
  3604. return typeof value === 'undefined';
  3605. }
  3606. Is.undefined = undefined;
  3607. function boolean(value) {
  3608. return value === true || value === false;
  3609. }
  3610. Is.boolean = boolean;
  3611. function string(value) {
  3612. return toString.call(value) === '[object String]';
  3613. }
  3614. Is.string = string;
  3615. function number(value) {
  3616. return toString.call(value) === '[object Number]';
  3617. }
  3618. Is.number = number;
  3619. function numberRange(value, min, max) {
  3620. return toString.call(value) === '[object Number]' && min <= value && value <= max;
  3621. }
  3622. Is.numberRange = numberRange;
  3623. function integer(value) {
  3624. return toString.call(value) === '[object Number]' && -2147483648 <= value && value <= 2147483647;
  3625. }
  3626. Is.integer = integer;
  3627. function uinteger(value) {
  3628. return toString.call(value) === '[object Number]' && 0 <= value && value <= 2147483647;
  3629. }
  3630. Is.uinteger = uinteger;
  3631. function func(value) {
  3632. return toString.call(value) === '[object Function]';
  3633. }
  3634. Is.func = func;
  3635. function objectLiteral(value) {
  3636. // Strictly speaking class instances pass this check as well. Since the LSP
  3637. // doesn't use classes we ignore this for now. If we do we need to add something
  3638. // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
  3639. return value !== null && typeof value === 'object';
  3640. }
  3641. Is.objectLiteral = objectLiteral;
  3642. function typedArray(value, check) {
  3643. return Array.isArray(value) && value.every(check);
  3644. }
  3645. Is.typedArray = typedArray;
  3646. })(Is || (Is = {}));
  3647. });
  3648. //# sourceMappingURL=main.js.map;
  3649. define('vscode-languageserver-types', ['vscode-languageserver-types/main'], function (main) { return main; });
  3650. (function (factory) {
  3651. if (typeof module === "object" && typeof module.exports === "object") {
  3652. var v = factory(require, exports);
  3653. if (v !== undefined) module.exports = v;
  3654. }
  3655. else if (typeof define === "function" && define.amd) {
  3656. define('vscode-languageserver-textdocument/main',["require", "exports"], factory);
  3657. }
  3658. })(function (require, exports) {
  3659. /* --------------------------------------------------------------------------------------------
  3660. * Copyright (c) Microsoft Corporation. All rights reserved.
  3661. * Licensed under the MIT License. See License.txt in the project root for license information.
  3662. * ------------------------------------------------------------------------------------------ */
  3663. 'use strict';
  3664. Object.defineProperty(exports, "__esModule", { value: true });
  3665. var FullTextDocument = /** @class */ (function () {
  3666. function FullTextDocument(uri, languageId, version, content) {
  3667. this._uri = uri;
  3668. this._languageId = languageId;
  3669. this._version = version;
  3670. this._content = content;
  3671. this._lineOffsets = undefined;
  3672. }
  3673. Object.defineProperty(FullTextDocument.prototype, "uri", {
  3674. get: function () {
  3675. return this._uri;
  3676. },
  3677. enumerable: true,
  3678. configurable: true
  3679. });
  3680. Object.defineProperty(FullTextDocument.prototype, "languageId", {
  3681. get: function () {
  3682. return this._languageId;
  3683. },
  3684. enumerable: true,
  3685. configurable: true
  3686. });
  3687. Object.defineProperty(FullTextDocument.prototype, "version", {
  3688. get: function () {
  3689. return this._version;
  3690. },
  3691. enumerable: true,
  3692. configurable: true
  3693. });
  3694. FullTextDocument.prototype.getText = function (range) {
  3695. if (range) {
  3696. var start = this.offsetAt(range.start);
  3697. var end = this.offsetAt(range.end);
  3698. return this._content.substring(start, end);
  3699. }
  3700. return this._content;
  3701. };
  3702. FullTextDocument.prototype.update = function (changes, version) {
  3703. for (var _i = 0, changes_1 = changes; _i < changes_1.length; _i++) {
  3704. var change = changes_1[_i];
  3705. if (FullTextDocument.isIncremental(change)) {
  3706. // makes sure start is before end
  3707. var range = getWellformedRange(change.range);
  3708. // update content
  3709. var startOffset = this.offsetAt(range.start);
  3710. var endOffset = this.offsetAt(range.end);
  3711. this._content = this._content.substring(0, startOffset) + change.text + this._content.substring(endOffset, this._content.length);
  3712. // update the offsets
  3713. var startLine = Math.max(range.start.line, 0);
  3714. var endLine = Math.max(range.end.line, 0);
  3715. var lineOffsets = this._lineOffsets;
  3716. var addedLineOffsets = computeLineOffsets(change.text, false, startOffset);
  3717. if (endLine - startLine === addedLineOffsets.length) {
  3718. for (var i = 0, len = addedLineOffsets.length; i < len; i++) {
  3719. lineOffsets[i + startLine + 1] = addedLineOffsets[i];
  3720. }
  3721. }
  3722. else {
  3723. if (addedLineOffsets.length < 10000) {
  3724. lineOffsets.splice.apply(lineOffsets, [startLine + 1, endLine - startLine].concat(addedLineOffsets));
  3725. }
  3726. else { // avoid too many arguments for splice
  3727. this._lineOffsets = lineOffsets = lineOffsets.slice(0, startLine + 1).concat(addedLineOffsets, lineOffsets.slice(endLine + 1));
  3728. }
  3729. }
  3730. var diff = change.text.length - (endOffset - startOffset);
  3731. if (diff !== 0) {
  3732. for (var i = startLine + 1 + addedLineOffsets.length, len = lineOffsets.length; i < len; i++) {
  3733. lineOffsets[i] = lineOffsets[i] + diff;
  3734. }
  3735. }
  3736. }
  3737. else if (FullTextDocument.isFull(change)) {
  3738. this._content = change.text;
  3739. this._lineOffsets = undefined;
  3740. }
  3741. else {
  3742. throw new Error('Unknown change event received');
  3743. }
  3744. }
  3745. this._version = version;
  3746. };
  3747. FullTextDocument.prototype.getLineOffsets = function () {
  3748. if (this._lineOffsets === undefined) {
  3749. this._lineOffsets = computeLineOffsets(this._content, true);
  3750. }
  3751. return this._lineOffsets;
  3752. };
  3753. FullTextDocument.prototype.positionAt = function (offset) {
  3754. offset = Math.max(Math.min(offset, this._content.length), 0);
  3755. var lineOffsets = this.getLineOffsets();
  3756. var low = 0, high = lineOffsets.length;
  3757. if (high === 0) {
  3758. return { line: 0, character: offset };
  3759. }
  3760. while (low < high) {
  3761. var mid = Math.floor((low + high) / 2);
  3762. if (lineOffsets[mid] > offset) {
  3763. high = mid;
  3764. }
  3765. else {
  3766. low = mid + 1;
  3767. }
  3768. }
  3769. // low is the least x for which the line offset is larger than the current offset
  3770. // or array.length if no line offset is larger than the current offset
  3771. var line = low - 1;
  3772. return { line: line, character: offset - lineOffsets[line] };
  3773. };
  3774. FullTextDocument.prototype.offsetAt = function (position) {
  3775. var lineOffsets = this.getLineOffsets();
  3776. if (position.line >= lineOffsets.length) {
  3777. return this._content.length;
  3778. }
  3779. else if (position.line < 0) {
  3780. return 0;
  3781. }
  3782. var lineOffset = lineOffsets[position.line];
  3783. var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
  3784. return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
  3785. };
  3786. Object.defineProperty(FullTextDocument.prototype, "lineCount", {
  3787. get: function () {
  3788. return this.getLineOffsets().length;
  3789. },
  3790. enumerable: true,
  3791. configurable: true
  3792. });
  3793. FullTextDocument.isIncremental = function (event) {
  3794. var candidate = event;
  3795. return candidate !== undefined && candidate !== null &&
  3796. typeof candidate.text === 'string' && candidate.range !== undefined &&
  3797. (candidate.rangeLength === undefined || typeof candidate.rangeLength === 'number');
  3798. };
  3799. FullTextDocument.isFull = function (event) {
  3800. var candidate = event;
  3801. return candidate !== undefined && candidate !== null &&
  3802. typeof candidate.text === 'string' && candidate.range === undefined && candidate.rangeLength === undefined;
  3803. };
  3804. return FullTextDocument;
  3805. }());
  3806. var TextDocument;
  3807. (function (TextDocument) {
  3808. /**
  3809. * Creates a new text document.
  3810. *
  3811. * @param uri The document's uri.
  3812. * @param languageId The document's language Id.
  3813. * @param version The document's initial version number.
  3814. * @param content The document's content.
  3815. */
  3816. function create(uri, languageId, version, content) {
  3817. return new FullTextDocument(uri, languageId, version, content);
  3818. }
  3819. TextDocument.create = create;
  3820. /**
  3821. * Updates a TextDocument by modifing its content.
  3822. *
  3823. * @param document the document to update. Only documents created by TextDocument.create are valid inputs.
  3824. * @param changes the changes to apply to the document.
  3825. * @returns The updated TextDocument. Note: That's the same document instance passed in as first parameter.
  3826. *
  3827. */
  3828. function update(document, changes, version) {
  3829. if (document instanceof FullTextDocument) {
  3830. document.update(changes, version);
  3831. return document;
  3832. }
  3833. else {
  3834. throw new Error('TextDocument.update: document must be created by TextDocument.create');
  3835. }
  3836. }
  3837. TextDocument.update = update;
  3838. function applyEdits(document, edits) {
  3839. var text = document.getText();
  3840. var sortedEdits = mergeSort(edits.map(getWellformedEdit), function (a, b) {
  3841. var diff = a.range.start.line - b.range.start.line;
  3842. if (diff === 0) {
  3843. return a.range.start.character - b.range.start.character;
  3844. }
  3845. return diff;
  3846. });
  3847. var lastModifiedOffset = 0;
  3848. var spans = [];
  3849. for (var _i = 0, sortedEdits_1 = sortedEdits; _i < sortedEdits_1.length; _i++) {
  3850. var e = sortedEdits_1[_i];
  3851. var startOffset = document.offsetAt(e.range.start);
  3852. if (startOffset < lastModifiedOffset) {
  3853. throw new Error('Overlapping edit');
  3854. }
  3855. else if (startOffset > lastModifiedOffset) {
  3856. spans.push(text.substring(lastModifiedOffset, startOffset));
  3857. }
  3858. if (e.newText.length) {
  3859. spans.push(e.newText);
  3860. }
  3861. lastModifiedOffset = document.offsetAt(e.range.end);
  3862. }
  3863. spans.push(text.substr(lastModifiedOffset));
  3864. return spans.join('');
  3865. }
  3866. TextDocument.applyEdits = applyEdits;
  3867. })(TextDocument = exports.TextDocument || (exports.TextDocument = {}));
  3868. function mergeSort(data, compare) {
  3869. if (data.length <= 1) {
  3870. // sorted
  3871. return data;
  3872. }
  3873. var p = (data.length / 2) | 0;
  3874. var left = data.slice(0, p);
  3875. var right = data.slice(p);
  3876. mergeSort(left, compare);
  3877. mergeSort(right, compare);
  3878. var leftIdx = 0;
  3879. var rightIdx = 0;
  3880. var i = 0;
  3881. while (leftIdx < left.length && rightIdx < right.length) {
  3882. var ret = compare(left[leftIdx], right[rightIdx]);
  3883. if (ret <= 0) {
  3884. // smaller_equal -> take left to preserve order
  3885. data[i++] = left[leftIdx++];
  3886. }
  3887. else {
  3888. // greater -> take right
  3889. data[i++] = right[rightIdx++];
  3890. }
  3891. }
  3892. while (leftIdx < left.length) {
  3893. data[i++] = left[leftIdx++];
  3894. }
  3895. while (rightIdx < right.length) {
  3896. data[i++] = right[rightIdx++];
  3897. }
  3898. return data;
  3899. }
  3900. function computeLineOffsets(text, isAtLineStart, textOffset) {
  3901. if (textOffset === void 0) { textOffset = 0; }
  3902. var result = isAtLineStart ? [textOffset] : [];
  3903. for (var i = 0; i < text.length; i++) {
  3904. var ch = text.charCodeAt(i);
  3905. if (ch === 13 /* CarriageReturn */ || ch === 10 /* LineFeed */) {
  3906. if (ch === 13 /* CarriageReturn */ && i + 1 < text.length && text.charCodeAt(i + 1) === 10 /* LineFeed */) {
  3907. i++;
  3908. }
  3909. result.push(textOffset + i + 1);
  3910. }
  3911. }
  3912. return result;
  3913. }
  3914. function getWellformedRange(range) {
  3915. var start = range.start;
  3916. var end = range.end;
  3917. if (start.line > end.line || (start.line === end.line && start.character > end.character)) {
  3918. return { start: end, end: start };
  3919. }
  3920. return range;
  3921. }
  3922. function getWellformedEdit(textEdit) {
  3923. var range = getWellformedRange(textEdit.range);
  3924. if (range !== textEdit.range) {
  3925. return { newText: textEdit.newText, range: range };
  3926. }
  3927. return textEdit;
  3928. }
  3929. });
  3930. define('vscode-languageserver-textdocument', ['vscode-languageserver-textdocument/main'], function (main) { return main; });
  3931. /*---------------------------------------------------------------------------------------------
  3932. * Copyright (c) Microsoft Corporation. All rights reserved.
  3933. * Licensed under the MIT License. See License.txt in the project root for license information.
  3934. *--------------------------------------------------------------------------------------------*/
  3935. (function (factory) {
  3936. if (typeof module === "object" && typeof module.exports === "object") {
  3937. var v = factory(require, exports);
  3938. if (v !== undefined) module.exports = v;
  3939. }
  3940. else if (typeof define === "function" && define.amd) {
  3941. define('vscode-json-languageservice/jsonLanguageTypes',["require", "exports", "vscode-languageserver-types", "vscode-languageserver-textdocument"], factory);
  3942. }
  3943. })(function (require, exports) {
  3944. "use strict";
  3945. Object.defineProperty(exports, "__esModule", { value: true });
  3946. exports.ClientCapabilities = exports.ErrorCode = exports.DocumentHighlightKind = exports.VersionedTextDocumentIdentifier = exports.TextDocumentEdit = exports.CodeActionKind = exports.TextEdit = exports.WorkspaceEdit = exports.DocumentLink = exports.DocumentHighlight = exports.CodeAction = exports.Command = exports.CodeActionContext = exports.MarkedString = exports.Hover = exports.Location = exports.DocumentSymbol = exports.SymbolKind = exports.SymbolInformation = exports.InsertTextFormat = exports.CompletionItemTag = exports.CompletionList = exports.CompletionItemKind = exports.CompletionItem = exports.DiagnosticSeverity = exports.Diagnostic = exports.SelectionRange = exports.FoldingRangeKind = exports.FoldingRange = exports.ColorPresentation = exports.ColorInformation = exports.Color = exports.MarkupKind = exports.MarkupContent = exports.Position = exports.Range = exports.TextDocument = void 0;
  3947. var vscode_languageserver_types_1 = require("vscode-languageserver-types");
  3948. Object.defineProperty(exports, "Range", { enumerable: true, get: function () { return vscode_languageserver_types_1.Range; } });
  3949. Object.defineProperty(exports, "Position", { enumerable: true, get: function () { return vscode_languageserver_types_1.Position; } });
  3950. Object.defineProperty(exports, "MarkupContent", { enumerable: true, get: function () { return vscode_languageserver_types_1.MarkupContent; } });
  3951. Object.defineProperty(exports, "MarkupKind", { enumerable: true, get: function () { return vscode_languageserver_types_1.MarkupKind; } });
  3952. Object.defineProperty(exports, "Color", { enumerable: true, get: function () { return vscode_languageserver_types_1.Color; } });
  3953. Object.defineProperty(exports, "ColorInformation", { enumerable: true, get: function () { return vscode_languageserver_types_1.ColorInformation; } });
  3954. Object.defineProperty(exports, "ColorPresentation", { enumerable: true, get: function () { return vscode_languageserver_types_1.ColorPresentation; } });
  3955. Object.defineProperty(exports, "FoldingRange", { enumerable: true, get: function () { return vscode_languageserver_types_1.FoldingRange; } });
  3956. Object.defineProperty(exports, "FoldingRangeKind", { enumerable: true, get: function () { return vscode_languageserver_types_1.FoldingRangeKind; } });
  3957. Object.defineProperty(exports, "SelectionRange", { enumerable: true, get: function () { return vscode_languageserver_types_1.SelectionRange; } });
  3958. Object.defineProperty(exports, "Diagnostic", { enumerable: true, get: function () { return vscode_languageserver_types_1.Diagnostic; } });
  3959. Object.defineProperty(exports, "DiagnosticSeverity", { enumerable: true, get: function () { return vscode_languageserver_types_1.DiagnosticSeverity; } });
  3960. Object.defineProperty(exports, "CompletionItem", { enumerable: true, get: function () { return vscode_languageserver_types_1.CompletionItem; } });
  3961. Object.defineProperty(exports, "CompletionItemKind", { enumerable: true, get: function () { return vscode_languageserver_types_1.CompletionItemKind; } });
  3962. Object.defineProperty(exports, "CompletionList", { enumerable: true, get: function () { return vscode_languageserver_types_1.CompletionList; } });
  3963. Object.defineProperty(exports, "CompletionItemTag", { enumerable: true, get: function () { return vscode_languageserver_types_1.CompletionItemTag; } });
  3964. Object.defineProperty(exports, "InsertTextFormat", { enumerable: true, get: function () { return vscode_languageserver_types_1.InsertTextFormat; } });
  3965. Object.defineProperty(exports, "SymbolInformation", { enumerable: true, get: function () { return vscode_languageserver_types_1.SymbolInformation; } });
  3966. Object.defineProperty(exports, "SymbolKind", { enumerable: true, get: function () { return vscode_languageserver_types_1.SymbolKind; } });
  3967. Object.defineProperty(exports, "DocumentSymbol", { enumerable: true, get: function () { return vscode_languageserver_types_1.DocumentSymbol; } });
  3968. Object.defineProperty(exports, "Location", { enumerable: true, get: function () { return vscode_languageserver_types_1.Location; } });
  3969. Object.defineProperty(exports, "Hover", { enumerable: true, get: function () { return vscode_languageserver_types_1.Hover; } });
  3970. Object.defineProperty(exports, "MarkedString", { enumerable: true, get: function () { return vscode_languageserver_types_1.MarkedString; } });
  3971. Object.defineProperty(exports, "CodeActionContext", { enumerable: true, get: function () { return vscode_languageserver_types_1.CodeActionContext; } });
  3972. Object.defineProperty(exports, "Command", { enumerable: true, get: function () { return vscode_languageserver_types_1.Command; } });
  3973. Object.defineProperty(exports, "CodeAction", { enumerable: true, get: function () { return vscode_languageserver_types_1.CodeAction; } });
  3974. Object.defineProperty(exports, "DocumentHighlight", { enumerable: true, get: function () { return vscode_languageserver_types_1.DocumentHighlight; } });
  3975. Object.defineProperty(exports, "DocumentLink", { enumerable: true, get: function () { return vscode_languageserver_types_1.DocumentLink; } });
  3976. Object.defineProperty(exports, "WorkspaceEdit", { enumerable: true, get: function () { return vscode_languageserver_types_1.WorkspaceEdit; } });
  3977. Object.defineProperty(exports, "TextEdit", { enumerable: true, get: function () { return vscode_languageserver_types_1.TextEdit; } });
  3978. Object.defineProperty(exports, "CodeActionKind", { enumerable: true, get: function () { return vscode_languageserver_types_1.CodeActionKind; } });
  3979. Object.defineProperty(exports, "TextDocumentEdit", { enumerable: true, get: function () { return vscode_languageserver_types_1.TextDocumentEdit; } });
  3980. Object.defineProperty(exports, "VersionedTextDocumentIdentifier", { enumerable: true, get: function () { return vscode_languageserver_types_1.VersionedTextDocumentIdentifier; } });
  3981. Object.defineProperty(exports, "DocumentHighlightKind", { enumerable: true, get: function () { return vscode_languageserver_types_1.DocumentHighlightKind; } });
  3982. var vscode_languageserver_textdocument_1 = require("vscode-languageserver-textdocument");
  3983. Object.defineProperty(exports, "TextDocument", { enumerable: true, get: function () { return vscode_languageserver_textdocument_1.TextDocument; } });
  3984. /**
  3985. * Error codes used by diagnostics
  3986. */
  3987. var ErrorCode;
  3988. (function (ErrorCode) {
  3989. ErrorCode[ErrorCode["Undefined"] = 0] = "Undefined";
  3990. ErrorCode[ErrorCode["EnumValueMismatch"] = 1] = "EnumValueMismatch";
  3991. ErrorCode[ErrorCode["Deprecated"] = 2] = "Deprecated";
  3992. ErrorCode[ErrorCode["UnexpectedEndOfComment"] = 257] = "UnexpectedEndOfComment";
  3993. ErrorCode[ErrorCode["UnexpectedEndOfString"] = 258] = "UnexpectedEndOfString";
  3994. ErrorCode[ErrorCode["UnexpectedEndOfNumber"] = 259] = "UnexpectedEndOfNumber";
  3995. ErrorCode[ErrorCode["InvalidUnicode"] = 260] = "InvalidUnicode";
  3996. ErrorCode[ErrorCode["InvalidEscapeCharacter"] = 261] = "InvalidEscapeCharacter";
  3997. ErrorCode[ErrorCode["InvalidCharacter"] = 262] = "InvalidCharacter";
  3998. ErrorCode[ErrorCode["PropertyExpected"] = 513] = "PropertyExpected";
  3999. ErrorCode[ErrorCode["CommaExpected"] = 514] = "CommaExpected";
  4000. ErrorCode[ErrorCode["ColonExpected"] = 515] = "ColonExpected";
  4001. ErrorCode[ErrorCode["ValueExpected"] = 516] = "ValueExpected";
  4002. ErrorCode[ErrorCode["CommaOrCloseBacketExpected"] = 517] = "CommaOrCloseBacketExpected";
  4003. ErrorCode[ErrorCode["CommaOrCloseBraceExpected"] = 518] = "CommaOrCloseBraceExpected";
  4004. ErrorCode[ErrorCode["TrailingComma"] = 519] = "TrailingComma";
  4005. ErrorCode[ErrorCode["DuplicateKey"] = 520] = "DuplicateKey";
  4006. ErrorCode[ErrorCode["CommentNotPermitted"] = 521] = "CommentNotPermitted";
  4007. ErrorCode[ErrorCode["SchemaResolveError"] = 768] = "SchemaResolveError";
  4008. })(ErrorCode = exports.ErrorCode || (exports.ErrorCode = {}));
  4009. var ClientCapabilities;
  4010. (function (ClientCapabilities) {
  4011. ClientCapabilities.LATEST = {
  4012. textDocument: {
  4013. completion: {
  4014. completionItem: {
  4015. documentationFormat: [vscode_languageserver_types_1.MarkupKind.Markdown, vscode_languageserver_types_1.MarkupKind.PlainText],
  4016. commitCharactersSupport: true
  4017. }
  4018. }
  4019. }
  4020. };
  4021. })(ClientCapabilities = exports.ClientCapabilities || (exports.ClientCapabilities = {}));
  4022. });
  4023. /*---------------------------------------------------------------------------------------------
  4024. * Copyright (c) Microsoft Corporation. All rights reserved.
  4025. * Licensed under the MIT License. See License.txt in the project root for license information.
  4026. *--------------------------------------------------------------------------------------------*/
  4027. define('vscode-nls/vscode-nls',["require", "exports"], function (require, exports) {
  4028. "use strict";
  4029. Object.defineProperty(exports, "__esModule", { value: true });
  4030. exports.config = exports.loadMessageBundle = void 0;
  4031. function format(message, args) {
  4032. var result;
  4033. if (args.length === 0) {
  4034. result = message;
  4035. }
  4036. else {
  4037. result = message.replace(/\{(\d+)\}/g, function (match, rest) {
  4038. var index = rest[0];
  4039. return typeof args[index] !== 'undefined' ? args[index] : match;
  4040. });
  4041. }
  4042. return result;
  4043. }
  4044. function localize(key, message) {
  4045. var args = [];
  4046. for (var _i = 2; _i < arguments.length; _i++) {
  4047. args[_i - 2] = arguments[_i];
  4048. }
  4049. return format(message, args);
  4050. }
  4051. function loadMessageBundle(file) {
  4052. return localize;
  4053. }
  4054. exports.loadMessageBundle = loadMessageBundle;
  4055. function config(opt) {
  4056. return loadMessageBundle;
  4057. }
  4058. exports.config = config;
  4059. });
  4060. define('vscode-nls', ['vscode-nls/vscode-nls'], function (main) { return main; });
  4061. /*---------------------------------------------------------------------------------------------
  4062. * Copyright (c) Microsoft Corporation. All rights reserved.
  4063. * Licensed under the MIT License. See License.txt in the project root for license information.
  4064. *--------------------------------------------------------------------------------------------*/
  4065. var __extends = (this && this.__extends) || (function () {
  4066. var extendStatics = function (d, b) {
  4067. extendStatics = Object.setPrototypeOf ||
  4068. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4069. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  4070. return extendStatics(d, b);
  4071. };
  4072. return function (d, b) {
  4073. if (typeof b !== "function" && b !== null)
  4074. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  4075. extendStatics(d, b);
  4076. function __() { this.constructor = d; }
  4077. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4078. };
  4079. })();
  4080. (function (factory) {
  4081. if (typeof module === "object" && typeof module.exports === "object") {
  4082. var v = factory(require, exports);
  4083. if (v !== undefined) module.exports = v;
  4084. }
  4085. else if (typeof define === "function" && define.amd) {
  4086. define('vscode-json-languageservice/parser/jsonParser',["require", "exports", "jsonc-parser", "../utils/objects", "../utils/strings", "../jsonLanguageTypes", "vscode-nls"], factory);
  4087. }
  4088. })(function (require, exports) {
  4089. "use strict";
  4090. Object.defineProperty(exports, "__esModule", { value: true });
  4091. exports.parse = exports.JSONDocument = exports.contains = exports.getNodePath = exports.getNodeValue = exports.newJSONDocument = exports.ValidationResult = exports.EnumMatch = exports.asSchema = exports.ObjectASTNodeImpl = exports.PropertyASTNodeImpl = exports.StringASTNodeImpl = exports.NumberASTNodeImpl = exports.ArrayASTNodeImpl = exports.BooleanASTNodeImpl = exports.NullASTNodeImpl = exports.ASTNodeImpl = void 0;
  4092. var Json = require("jsonc-parser");
  4093. var objects_1 = require("../utils/objects");
  4094. var strings_1 = require("../utils/strings");
  4095. var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
  4096. var nls = require("vscode-nls");
  4097. var localize = nls.loadMessageBundle();
  4098. var formats = {
  4099. 'color-hex': { errorMessage: localize('colorHexFormatWarning', 'Invalid color format. Use #RGB, #RGBA, #RRGGBB or #RRGGBBAA.'), pattern: /^#([0-9A-Fa-f]{3,4}|([0-9A-Fa-f]{2}){3,4})$/ },
  4100. 'date-time': { errorMessage: localize('dateTimeFormatWarning', 'String is not a RFC3339 date-time.'), pattern: /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(Z|(\+|-)([01][0-9]|2[0-3]):([0-5][0-9]))$/i },
  4101. 'date': { errorMessage: localize('dateFormatWarning', 'String is not a RFC3339 date.'), pattern: /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/i },
  4102. 'time': { errorMessage: localize('timeFormatWarning', 'String is not a RFC3339 time.'), pattern: /^([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(Z|(\+|-)([01][0-9]|2[0-3]):([0-5][0-9]))$/i },
  4103. 'email': { errorMessage: localize('emailFormatWarning', 'String is not an e-mail address.'), pattern: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ }
  4104. };
  4105. var ASTNodeImpl = /** @class */ (function () {
  4106. function ASTNodeImpl(parent, offset, length) {
  4107. if (length === void 0) { length = 0; }
  4108. this.offset = offset;
  4109. this.length = length;
  4110. this.parent = parent;
  4111. }
  4112. Object.defineProperty(ASTNodeImpl.prototype, "children", {
  4113. get: function () {
  4114. return [];
  4115. },
  4116. enumerable: false,
  4117. configurable: true
  4118. });
  4119. ASTNodeImpl.prototype.toString = function () {
  4120. return 'type: ' + this.type + ' (' + this.offset + '/' + this.length + ')' + (this.parent ? ' parent: {' + this.parent.toString() + '}' : '');
  4121. };
  4122. return ASTNodeImpl;
  4123. }());
  4124. exports.ASTNodeImpl = ASTNodeImpl;
  4125. var NullASTNodeImpl = /** @class */ (function (_super) {
  4126. __extends(NullASTNodeImpl, _super);
  4127. function NullASTNodeImpl(parent, offset) {
  4128. var _this = _super.call(this, parent, offset) || this;
  4129. _this.type = 'null';
  4130. _this.value = null;
  4131. return _this;
  4132. }
  4133. return NullASTNodeImpl;
  4134. }(ASTNodeImpl));
  4135. exports.NullASTNodeImpl = NullASTNodeImpl;
  4136. var BooleanASTNodeImpl = /** @class */ (function (_super) {
  4137. __extends(BooleanASTNodeImpl, _super);
  4138. function BooleanASTNodeImpl(parent, boolValue, offset) {
  4139. var _this = _super.call(this, parent, offset) || this;
  4140. _this.type = 'boolean';
  4141. _this.value = boolValue;
  4142. return _this;
  4143. }
  4144. return BooleanASTNodeImpl;
  4145. }(ASTNodeImpl));
  4146. exports.BooleanASTNodeImpl = BooleanASTNodeImpl;
  4147. var ArrayASTNodeImpl = /** @class */ (function (_super) {
  4148. __extends(ArrayASTNodeImpl, _super);
  4149. function ArrayASTNodeImpl(parent, offset) {
  4150. var _this = _super.call(this, parent, offset) || this;
  4151. _this.type = 'array';
  4152. _this.items = [];
  4153. return _this;
  4154. }
  4155. Object.defineProperty(ArrayASTNodeImpl.prototype, "children", {
  4156. get: function () {
  4157. return this.items;
  4158. },
  4159. enumerable: false,
  4160. configurable: true
  4161. });
  4162. return ArrayASTNodeImpl;
  4163. }(ASTNodeImpl));
  4164. exports.ArrayASTNodeImpl = ArrayASTNodeImpl;
  4165. var NumberASTNodeImpl = /** @class */ (function (_super) {
  4166. __extends(NumberASTNodeImpl, _super);
  4167. function NumberASTNodeImpl(parent, offset) {
  4168. var _this = _super.call(this, parent, offset) || this;
  4169. _this.type = 'number';
  4170. _this.isInteger = true;
  4171. _this.value = Number.NaN;
  4172. return _this;
  4173. }
  4174. return NumberASTNodeImpl;
  4175. }(ASTNodeImpl));
  4176. exports.NumberASTNodeImpl = NumberASTNodeImpl;
  4177. var StringASTNodeImpl = /** @class */ (function (_super) {
  4178. __extends(StringASTNodeImpl, _super);
  4179. function StringASTNodeImpl(parent, offset, length) {
  4180. var _this = _super.call(this, parent, offset, length) || this;
  4181. _this.type = 'string';
  4182. _this.value = '';
  4183. return _this;
  4184. }
  4185. return StringASTNodeImpl;
  4186. }(ASTNodeImpl));
  4187. exports.StringASTNodeImpl = StringASTNodeImpl;
  4188. var PropertyASTNodeImpl = /** @class */ (function (_super) {
  4189. __extends(PropertyASTNodeImpl, _super);
  4190. function PropertyASTNodeImpl(parent, offset, keyNode) {
  4191. var _this = _super.call(this, parent, offset) || this;
  4192. _this.type = 'property';
  4193. _this.colonOffset = -1;
  4194. _this.keyNode = keyNode;
  4195. return _this;
  4196. }
  4197. Object.defineProperty(PropertyASTNodeImpl.prototype, "children", {
  4198. get: function () {
  4199. return this.valueNode ? [this.keyNode, this.valueNode] : [this.keyNode];
  4200. },
  4201. enumerable: false,
  4202. configurable: true
  4203. });
  4204. return PropertyASTNodeImpl;
  4205. }(ASTNodeImpl));
  4206. exports.PropertyASTNodeImpl = PropertyASTNodeImpl;
  4207. var ObjectASTNodeImpl = /** @class */ (function (_super) {
  4208. __extends(ObjectASTNodeImpl, _super);
  4209. function ObjectASTNodeImpl(parent, offset) {
  4210. var _this = _super.call(this, parent, offset) || this;
  4211. _this.type = 'object';
  4212. _this.properties = [];
  4213. return _this;
  4214. }
  4215. Object.defineProperty(ObjectASTNodeImpl.prototype, "children", {
  4216. get: function () {
  4217. return this.properties;
  4218. },
  4219. enumerable: false,
  4220. configurable: true
  4221. });
  4222. return ObjectASTNodeImpl;
  4223. }(ASTNodeImpl));
  4224. exports.ObjectASTNodeImpl = ObjectASTNodeImpl;
  4225. function asSchema(schema) {
  4226. if (objects_1.isBoolean(schema)) {
  4227. return schema ? {} : { "not": {} };
  4228. }
  4229. return schema;
  4230. }
  4231. exports.asSchema = asSchema;
  4232. var EnumMatch;
  4233. (function (EnumMatch) {
  4234. EnumMatch[EnumMatch["Key"] = 0] = "Key";
  4235. EnumMatch[EnumMatch["Enum"] = 1] = "Enum";
  4236. })(EnumMatch = exports.EnumMatch || (exports.EnumMatch = {}));
  4237. var SchemaCollector = /** @class */ (function () {
  4238. function SchemaCollector(focusOffset, exclude) {
  4239. if (focusOffset === void 0) { focusOffset = -1; }
  4240. this.focusOffset = focusOffset;
  4241. this.exclude = exclude;
  4242. this.schemas = [];
  4243. }
  4244. SchemaCollector.prototype.add = function (schema) {
  4245. this.schemas.push(schema);
  4246. };
  4247. SchemaCollector.prototype.merge = function (other) {
  4248. Array.prototype.push.apply(this.schemas, other.schemas);
  4249. };
  4250. SchemaCollector.prototype.include = function (node) {
  4251. return (this.focusOffset === -1 || contains(node, this.focusOffset)) && (node !== this.exclude);
  4252. };
  4253. SchemaCollector.prototype.newSub = function () {
  4254. return new SchemaCollector(-1, this.exclude);
  4255. };
  4256. return SchemaCollector;
  4257. }());
  4258. var NoOpSchemaCollector = /** @class */ (function () {
  4259. function NoOpSchemaCollector() {
  4260. }
  4261. Object.defineProperty(NoOpSchemaCollector.prototype, "schemas", {
  4262. get: function () { return []; },
  4263. enumerable: false,
  4264. configurable: true
  4265. });
  4266. NoOpSchemaCollector.prototype.add = function (schema) { };
  4267. NoOpSchemaCollector.prototype.merge = function (other) { };
  4268. NoOpSchemaCollector.prototype.include = function (node) { return true; };
  4269. NoOpSchemaCollector.prototype.newSub = function () { return this; };
  4270. NoOpSchemaCollector.instance = new NoOpSchemaCollector();
  4271. return NoOpSchemaCollector;
  4272. }());
  4273. var ValidationResult = /** @class */ (function () {
  4274. function ValidationResult() {
  4275. this.problems = [];
  4276. this.propertiesMatches = 0;
  4277. this.propertiesValueMatches = 0;
  4278. this.primaryValueMatches = 0;
  4279. this.enumValueMatch = false;
  4280. this.enumValues = undefined;
  4281. }
  4282. ValidationResult.prototype.hasProblems = function () {
  4283. return !!this.problems.length;
  4284. };
  4285. ValidationResult.prototype.mergeAll = function (validationResults) {
  4286. for (var _i = 0, validationResults_1 = validationResults; _i < validationResults_1.length; _i++) {
  4287. var validationResult = validationResults_1[_i];
  4288. this.merge(validationResult);
  4289. }
  4290. };
  4291. ValidationResult.prototype.merge = function (validationResult) {
  4292. this.problems = this.problems.concat(validationResult.problems);
  4293. };
  4294. ValidationResult.prototype.mergeEnumValues = function (validationResult) {
  4295. if (!this.enumValueMatch && !validationResult.enumValueMatch && this.enumValues && validationResult.enumValues) {
  4296. this.enumValues = this.enumValues.concat(validationResult.enumValues);
  4297. for (var _i = 0, _a = this.problems; _i < _a.length; _i++) {
  4298. var error = _a[_i];
  4299. if (error.code === jsonLanguageTypes_1.ErrorCode.EnumValueMismatch) {
  4300. error.message = localize('enumWarning', 'Value is not accepted. Valid values: {0}.', this.enumValues.map(function (v) { return JSON.stringify(v); }).join(', '));
  4301. }
  4302. }
  4303. }
  4304. };
  4305. ValidationResult.prototype.mergePropertyMatch = function (propertyValidationResult) {
  4306. this.merge(propertyValidationResult);
  4307. this.propertiesMatches++;
  4308. if (propertyValidationResult.enumValueMatch || !propertyValidationResult.hasProblems() && propertyValidationResult.propertiesMatches) {
  4309. this.propertiesValueMatches++;
  4310. }
  4311. if (propertyValidationResult.enumValueMatch && propertyValidationResult.enumValues && propertyValidationResult.enumValues.length === 1) {
  4312. this.primaryValueMatches++;
  4313. }
  4314. };
  4315. ValidationResult.prototype.compare = function (other) {
  4316. var hasProblems = this.hasProblems();
  4317. if (hasProblems !== other.hasProblems()) {
  4318. return hasProblems ? -1 : 1;
  4319. }
  4320. if (this.enumValueMatch !== other.enumValueMatch) {
  4321. return other.enumValueMatch ? -1 : 1;
  4322. }
  4323. if (this.primaryValueMatches !== other.primaryValueMatches) {
  4324. return this.primaryValueMatches - other.primaryValueMatches;
  4325. }
  4326. if (this.propertiesValueMatches !== other.propertiesValueMatches) {
  4327. return this.propertiesValueMatches - other.propertiesValueMatches;
  4328. }
  4329. return this.propertiesMatches - other.propertiesMatches;
  4330. };
  4331. return ValidationResult;
  4332. }());
  4333. exports.ValidationResult = ValidationResult;
  4334. function newJSONDocument(root, diagnostics) {
  4335. if (diagnostics === void 0) { diagnostics = []; }
  4336. return new JSONDocument(root, diagnostics, []);
  4337. }
  4338. exports.newJSONDocument = newJSONDocument;
  4339. function getNodeValue(node) {
  4340. return Json.getNodeValue(node);
  4341. }
  4342. exports.getNodeValue = getNodeValue;
  4343. function getNodePath(node) {
  4344. return Json.getNodePath(node);
  4345. }
  4346. exports.getNodePath = getNodePath;
  4347. function contains(node, offset, includeRightBound) {
  4348. if (includeRightBound === void 0) { includeRightBound = false; }
  4349. return offset >= node.offset && offset < (node.offset + node.length) || includeRightBound && offset === (node.offset + node.length);
  4350. }
  4351. exports.contains = contains;
  4352. var JSONDocument = /** @class */ (function () {
  4353. function JSONDocument(root, syntaxErrors, comments) {
  4354. if (syntaxErrors === void 0) { syntaxErrors = []; }
  4355. if (comments === void 0) { comments = []; }
  4356. this.root = root;
  4357. this.syntaxErrors = syntaxErrors;
  4358. this.comments = comments;
  4359. }
  4360. JSONDocument.prototype.getNodeFromOffset = function (offset, includeRightBound) {
  4361. if (includeRightBound === void 0) { includeRightBound = false; }
  4362. if (this.root) {
  4363. return Json.findNodeAtOffset(this.root, offset, includeRightBound);
  4364. }
  4365. return undefined;
  4366. };
  4367. JSONDocument.prototype.visit = function (visitor) {
  4368. if (this.root) {
  4369. var doVisit_1 = function (node) {
  4370. var ctn = visitor(node);
  4371. var children = node.children;
  4372. if (Array.isArray(children)) {
  4373. for (var i = 0; i < children.length && ctn; i++) {
  4374. ctn = doVisit_1(children[i]);
  4375. }
  4376. }
  4377. return ctn;
  4378. };
  4379. doVisit_1(this.root);
  4380. }
  4381. };
  4382. JSONDocument.prototype.validate = function (textDocument, schema, severity) {
  4383. if (severity === void 0) { severity = jsonLanguageTypes_1.DiagnosticSeverity.Warning; }
  4384. if (this.root && schema) {
  4385. var validationResult = new ValidationResult();
  4386. validate(this.root, schema, validationResult, NoOpSchemaCollector.instance);
  4387. return validationResult.problems.map(function (p) {
  4388. var _a;
  4389. var range = jsonLanguageTypes_1.Range.create(textDocument.positionAt(p.location.offset), textDocument.positionAt(p.location.offset + p.location.length));
  4390. return jsonLanguageTypes_1.Diagnostic.create(range, p.message, (_a = p.severity) !== null && _a !== void 0 ? _a : severity, p.code);
  4391. });
  4392. }
  4393. return undefined;
  4394. };
  4395. JSONDocument.prototype.getMatchingSchemas = function (schema, focusOffset, exclude) {
  4396. if (focusOffset === void 0) { focusOffset = -1; }
  4397. var matchingSchemas = new SchemaCollector(focusOffset, exclude);
  4398. if (this.root && schema) {
  4399. validate(this.root, schema, new ValidationResult(), matchingSchemas);
  4400. }
  4401. return matchingSchemas.schemas;
  4402. };
  4403. return JSONDocument;
  4404. }());
  4405. exports.JSONDocument = JSONDocument;
  4406. function validate(n, schema, validationResult, matchingSchemas) {
  4407. if (!n || !matchingSchemas.include(n)) {
  4408. return;
  4409. }
  4410. var node = n;
  4411. switch (node.type) {
  4412. case 'object':
  4413. _validateObjectNode(node, schema, validationResult, matchingSchemas);
  4414. break;
  4415. case 'array':
  4416. _validateArrayNode(node, schema, validationResult, matchingSchemas);
  4417. break;
  4418. case 'string':
  4419. _validateStringNode(node, schema, validationResult, matchingSchemas);
  4420. break;
  4421. case 'number':
  4422. _validateNumberNode(node, schema, validationResult, matchingSchemas);
  4423. break;
  4424. case 'property':
  4425. return validate(node.valueNode, schema, validationResult, matchingSchemas);
  4426. }
  4427. _validateNode();
  4428. matchingSchemas.add({ node: node, schema: schema });
  4429. function _validateNode() {
  4430. function matchesType(type) {
  4431. return node.type === type || (type === 'integer' && node.type === 'number' && node.isInteger);
  4432. }
  4433. if (Array.isArray(schema.type)) {
  4434. if (!schema.type.some(matchesType)) {
  4435. validationResult.problems.push({
  4436. location: { offset: node.offset, length: node.length },
  4437. message: schema.errorMessage || localize('typeArrayMismatchWarning', 'Incorrect type. Expected one of {0}.', schema.type.join(', '))
  4438. });
  4439. }
  4440. }
  4441. else if (schema.type) {
  4442. if (!matchesType(schema.type)) {
  4443. validationResult.problems.push({
  4444. location: { offset: node.offset, length: node.length },
  4445. message: schema.errorMessage || localize('typeMismatchWarning', 'Incorrect type. Expected "{0}".', schema.type)
  4446. });
  4447. }
  4448. }
  4449. if (Array.isArray(schema.allOf)) {
  4450. for (var _i = 0, _a = schema.allOf; _i < _a.length; _i++) {
  4451. var subSchemaRef = _a[_i];
  4452. validate(node, asSchema(subSchemaRef), validationResult, matchingSchemas);
  4453. }
  4454. }
  4455. var notSchema = asSchema(schema.not);
  4456. if (notSchema) {
  4457. var subValidationResult = new ValidationResult();
  4458. var subMatchingSchemas = matchingSchemas.newSub();
  4459. validate(node, notSchema, subValidationResult, subMatchingSchemas);
  4460. if (!subValidationResult.hasProblems()) {
  4461. validationResult.problems.push({
  4462. location: { offset: node.offset, length: node.length },
  4463. message: localize('notSchemaWarning', "Matches a schema that is not allowed.")
  4464. });
  4465. }
  4466. for (var _b = 0, _c = subMatchingSchemas.schemas; _b < _c.length; _b++) {
  4467. var ms = _c[_b];
  4468. ms.inverted = !ms.inverted;
  4469. matchingSchemas.add(ms);
  4470. }
  4471. }
  4472. var testAlternatives = function (alternatives, maxOneMatch) {
  4473. var matches = [];
  4474. // remember the best match that is used for error messages
  4475. var bestMatch = undefined;
  4476. for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) {
  4477. var subSchemaRef = alternatives_1[_i];
  4478. var subSchema = asSchema(subSchemaRef);
  4479. var subValidationResult = new ValidationResult();
  4480. var subMatchingSchemas = matchingSchemas.newSub();
  4481. validate(node, subSchema, subValidationResult, subMatchingSchemas);
  4482. if (!subValidationResult.hasProblems()) {
  4483. matches.push(subSchema);
  4484. }
  4485. if (!bestMatch) {
  4486. bestMatch = { schema: subSchema, validationResult: subValidationResult, matchingSchemas: subMatchingSchemas };
  4487. }
  4488. else {
  4489. if (!maxOneMatch && !subValidationResult.hasProblems() && !bestMatch.validationResult.hasProblems()) {
  4490. // no errors, both are equally good matches
  4491. bestMatch.matchingSchemas.merge(subMatchingSchemas);
  4492. bestMatch.validationResult.propertiesMatches += subValidationResult.propertiesMatches;
  4493. bestMatch.validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches;
  4494. }
  4495. else {
  4496. var compareResult = subValidationResult.compare(bestMatch.validationResult);
  4497. if (compareResult > 0) {
  4498. // our node is the best matching so far
  4499. bestMatch = { schema: subSchema, validationResult: subValidationResult, matchingSchemas: subMatchingSchemas };
  4500. }
  4501. else if (compareResult === 0) {
  4502. // there's already a best matching but we are as good
  4503. bestMatch.matchingSchemas.merge(subMatchingSchemas);
  4504. bestMatch.validationResult.mergeEnumValues(subValidationResult);
  4505. }
  4506. }
  4507. }
  4508. }
  4509. if (matches.length > 1 && maxOneMatch) {
  4510. validationResult.problems.push({
  4511. location: { offset: node.offset, length: 1 },
  4512. message: localize('oneOfWarning', "Matches multiple schemas when only one must validate.")
  4513. });
  4514. }
  4515. if (bestMatch) {
  4516. validationResult.merge(bestMatch.validationResult);
  4517. validationResult.propertiesMatches += bestMatch.validationResult.propertiesMatches;
  4518. validationResult.propertiesValueMatches += bestMatch.validationResult.propertiesValueMatches;
  4519. matchingSchemas.merge(bestMatch.matchingSchemas);
  4520. }
  4521. return matches.length;
  4522. };
  4523. if (Array.isArray(schema.anyOf)) {
  4524. testAlternatives(schema.anyOf, false);
  4525. }
  4526. if (Array.isArray(schema.oneOf)) {
  4527. testAlternatives(schema.oneOf, true);
  4528. }
  4529. var testBranch = function (schema) {
  4530. var subValidationResult = new ValidationResult();
  4531. var subMatchingSchemas = matchingSchemas.newSub();
  4532. validate(node, asSchema(schema), subValidationResult, subMatchingSchemas);
  4533. validationResult.merge(subValidationResult);
  4534. validationResult.propertiesMatches += subValidationResult.propertiesMatches;
  4535. validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches;
  4536. matchingSchemas.merge(subMatchingSchemas);
  4537. };
  4538. var testCondition = function (ifSchema, thenSchema, elseSchema) {
  4539. var subSchema = asSchema(ifSchema);
  4540. var subValidationResult = new ValidationResult();
  4541. var subMatchingSchemas = matchingSchemas.newSub();
  4542. validate(node, subSchema, subValidationResult, subMatchingSchemas);
  4543. matchingSchemas.merge(subMatchingSchemas);
  4544. if (!subValidationResult.hasProblems()) {
  4545. if (thenSchema) {
  4546. testBranch(thenSchema);
  4547. }
  4548. }
  4549. else if (elseSchema) {
  4550. testBranch(elseSchema);
  4551. }
  4552. };
  4553. var ifSchema = asSchema(schema.if);
  4554. if (ifSchema) {
  4555. testCondition(ifSchema, asSchema(schema.then), asSchema(schema.else));
  4556. }
  4557. if (Array.isArray(schema.enum)) {
  4558. var val = getNodeValue(node);
  4559. var enumValueMatch = false;
  4560. for (var _d = 0, _e = schema.enum; _d < _e.length; _d++) {
  4561. var e = _e[_d];
  4562. if (objects_1.equals(val, e)) {
  4563. enumValueMatch = true;
  4564. break;
  4565. }
  4566. }
  4567. validationResult.enumValues = schema.enum;
  4568. validationResult.enumValueMatch = enumValueMatch;
  4569. if (!enumValueMatch) {
  4570. validationResult.problems.push({
  4571. location: { offset: node.offset, length: node.length },
  4572. code: jsonLanguageTypes_1.ErrorCode.EnumValueMismatch,
  4573. message: schema.errorMessage || localize('enumWarning', 'Value is not accepted. Valid values: {0}.', schema.enum.map(function (v) { return JSON.stringify(v); }).join(', '))
  4574. });
  4575. }
  4576. }
  4577. if (objects_1.isDefined(schema.const)) {
  4578. var val = getNodeValue(node);
  4579. if (!objects_1.equals(val, schema.const)) {
  4580. validationResult.problems.push({
  4581. location: { offset: node.offset, length: node.length },
  4582. code: jsonLanguageTypes_1.ErrorCode.EnumValueMismatch,
  4583. message: schema.errorMessage || localize('constWarning', 'Value must be {0}.', JSON.stringify(schema.const))
  4584. });
  4585. validationResult.enumValueMatch = false;
  4586. }
  4587. else {
  4588. validationResult.enumValueMatch = true;
  4589. }
  4590. validationResult.enumValues = [schema.const];
  4591. }
  4592. if (schema.deprecationMessage && node.parent) {
  4593. validationResult.problems.push({
  4594. location: { offset: node.parent.offset, length: node.parent.length },
  4595. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4596. message: schema.deprecationMessage,
  4597. code: jsonLanguageTypes_1.ErrorCode.Deprecated
  4598. });
  4599. }
  4600. }
  4601. function _validateNumberNode(node, schema, validationResult, matchingSchemas) {
  4602. var val = node.value;
  4603. function normalizeFloats(float) {
  4604. var _a;
  4605. var parts = /^(-?\d+)(?:\.(\d+))?(?:e([-+]\d+))?$/.exec(float.toString());
  4606. return parts && {
  4607. value: Number(parts[1] + (parts[2] || '')),
  4608. multiplier: (((_a = parts[2]) === null || _a === void 0 ? void 0 : _a.length) || 0) - (parseInt(parts[3]) || 0)
  4609. };
  4610. }
  4611. ;
  4612. if (objects_1.isNumber(schema.multipleOf)) {
  4613. var remainder = -1;
  4614. if (Number.isInteger(schema.multipleOf)) {
  4615. remainder = val % schema.multipleOf;
  4616. }
  4617. else {
  4618. var normMultipleOf = normalizeFloats(schema.multipleOf);
  4619. var normValue = normalizeFloats(val);
  4620. if (normMultipleOf && normValue) {
  4621. var multiplier = Math.pow(10, Math.abs(normValue.multiplier - normMultipleOf.multiplier));
  4622. if (normValue.multiplier < normMultipleOf.multiplier) {
  4623. normValue.value *= multiplier;
  4624. }
  4625. else {
  4626. normMultipleOf.value *= multiplier;
  4627. }
  4628. remainder = normValue.value % normMultipleOf.value;
  4629. }
  4630. }
  4631. if (remainder !== 0) {
  4632. validationResult.problems.push({
  4633. location: { offset: node.offset, length: node.length },
  4634. message: localize('multipleOfWarning', 'Value is not divisible by {0}.', schema.multipleOf)
  4635. });
  4636. }
  4637. }
  4638. function getExclusiveLimit(limit, exclusive) {
  4639. if (objects_1.isNumber(exclusive)) {
  4640. return exclusive;
  4641. }
  4642. if (objects_1.isBoolean(exclusive) && exclusive) {
  4643. return limit;
  4644. }
  4645. return undefined;
  4646. }
  4647. function getLimit(limit, exclusive) {
  4648. if (!objects_1.isBoolean(exclusive) || !exclusive) {
  4649. return limit;
  4650. }
  4651. return undefined;
  4652. }
  4653. var exclusiveMinimum = getExclusiveLimit(schema.minimum, schema.exclusiveMinimum);
  4654. if (objects_1.isNumber(exclusiveMinimum) && val <= exclusiveMinimum) {
  4655. validationResult.problems.push({
  4656. location: { offset: node.offset, length: node.length },
  4657. message: localize('exclusiveMinimumWarning', 'Value is below the exclusive minimum of {0}.', exclusiveMinimum)
  4658. });
  4659. }
  4660. var exclusiveMaximum = getExclusiveLimit(schema.maximum, schema.exclusiveMaximum);
  4661. if (objects_1.isNumber(exclusiveMaximum) && val >= exclusiveMaximum) {
  4662. validationResult.problems.push({
  4663. location: { offset: node.offset, length: node.length },
  4664. message: localize('exclusiveMaximumWarning', 'Value is above the exclusive maximum of {0}.', exclusiveMaximum)
  4665. });
  4666. }
  4667. var minimum = getLimit(schema.minimum, schema.exclusiveMinimum);
  4668. if (objects_1.isNumber(minimum) && val < minimum) {
  4669. validationResult.problems.push({
  4670. location: { offset: node.offset, length: node.length },
  4671. message: localize('minimumWarning', 'Value is below the minimum of {0}.', minimum)
  4672. });
  4673. }
  4674. var maximum = getLimit(schema.maximum, schema.exclusiveMaximum);
  4675. if (objects_1.isNumber(maximum) && val > maximum) {
  4676. validationResult.problems.push({
  4677. location: { offset: node.offset, length: node.length },
  4678. message: localize('maximumWarning', 'Value is above the maximum of {0}.', maximum)
  4679. });
  4680. }
  4681. }
  4682. function _validateStringNode(node, schema, validationResult, matchingSchemas) {
  4683. if (objects_1.isNumber(schema.minLength) && node.value.length < schema.minLength) {
  4684. validationResult.problems.push({
  4685. location: { offset: node.offset, length: node.length },
  4686. message: localize('minLengthWarning', 'String is shorter than the minimum length of {0}.', schema.minLength)
  4687. });
  4688. }
  4689. if (objects_1.isNumber(schema.maxLength) && node.value.length > schema.maxLength) {
  4690. validationResult.problems.push({
  4691. location: { offset: node.offset, length: node.length },
  4692. message: localize('maxLengthWarning', 'String is longer than the maximum length of {0}.', schema.maxLength)
  4693. });
  4694. }
  4695. if (objects_1.isString(schema.pattern)) {
  4696. var regex = strings_1.extendedRegExp(schema.pattern);
  4697. if (!regex.test(node.value)) {
  4698. validationResult.problems.push({
  4699. location: { offset: node.offset, length: node.length },
  4700. message: schema.patternErrorMessage || schema.errorMessage || localize('patternWarning', 'String does not match the pattern of "{0}".', schema.pattern)
  4701. });
  4702. }
  4703. }
  4704. if (schema.format) {
  4705. switch (schema.format) {
  4706. case 'uri':
  4707. case 'uri-reference':
  4708. {
  4709. var errorMessage = void 0;
  4710. if (!node.value) {
  4711. errorMessage = localize('uriEmpty', 'URI expected.');
  4712. }
  4713. else {
  4714. var match = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/.exec(node.value);
  4715. if (!match) {
  4716. errorMessage = localize('uriMissing', 'URI is expected.');
  4717. }
  4718. else if (!match[2] && schema.format === 'uri') {
  4719. errorMessage = localize('uriSchemeMissing', 'URI with a scheme is expected.');
  4720. }
  4721. }
  4722. if (errorMessage) {
  4723. validationResult.problems.push({
  4724. location: { offset: node.offset, length: node.length },
  4725. message: schema.patternErrorMessage || schema.errorMessage || localize('uriFormatWarning', 'String is not a URI: {0}', errorMessage)
  4726. });
  4727. }
  4728. }
  4729. break;
  4730. case 'color-hex':
  4731. case 'date-time':
  4732. case 'date':
  4733. case 'time':
  4734. case 'email':
  4735. var format = formats[schema.format];
  4736. if (!node.value || !format.pattern.exec(node.value)) {
  4737. validationResult.problems.push({
  4738. location: { offset: node.offset, length: node.length },
  4739. message: schema.patternErrorMessage || schema.errorMessage || format.errorMessage
  4740. });
  4741. }
  4742. default:
  4743. }
  4744. }
  4745. }
  4746. function _validateArrayNode(node, schema, validationResult, matchingSchemas) {
  4747. if (Array.isArray(schema.items)) {
  4748. var subSchemas = schema.items;
  4749. for (var index = 0; index < subSchemas.length; index++) {
  4750. var subSchemaRef = subSchemas[index];
  4751. var subSchema = asSchema(subSchemaRef);
  4752. var itemValidationResult = new ValidationResult();
  4753. var item = node.items[index];
  4754. if (item) {
  4755. validate(item, subSchema, itemValidationResult, matchingSchemas);
  4756. validationResult.mergePropertyMatch(itemValidationResult);
  4757. }
  4758. else if (node.items.length >= subSchemas.length) {
  4759. validationResult.propertiesValueMatches++;
  4760. }
  4761. }
  4762. if (node.items.length > subSchemas.length) {
  4763. if (typeof schema.additionalItems === 'object') {
  4764. for (var i = subSchemas.length; i < node.items.length; i++) {
  4765. var itemValidationResult = new ValidationResult();
  4766. validate(node.items[i], schema.additionalItems, itemValidationResult, matchingSchemas);
  4767. validationResult.mergePropertyMatch(itemValidationResult);
  4768. }
  4769. }
  4770. else if (schema.additionalItems === false) {
  4771. validationResult.problems.push({
  4772. location: { offset: node.offset, length: node.length },
  4773. message: localize('additionalItemsWarning', 'Array has too many items according to schema. Expected {0} or fewer.', subSchemas.length)
  4774. });
  4775. }
  4776. }
  4777. }
  4778. else {
  4779. var itemSchema = asSchema(schema.items);
  4780. if (itemSchema) {
  4781. for (var _i = 0, _a = node.items; _i < _a.length; _i++) {
  4782. var item = _a[_i];
  4783. var itemValidationResult = new ValidationResult();
  4784. validate(item, itemSchema, itemValidationResult, matchingSchemas);
  4785. validationResult.mergePropertyMatch(itemValidationResult);
  4786. }
  4787. }
  4788. }
  4789. var containsSchema = asSchema(schema.contains);
  4790. if (containsSchema) {
  4791. var doesContain = node.items.some(function (item) {
  4792. var itemValidationResult = new ValidationResult();
  4793. validate(item, containsSchema, itemValidationResult, NoOpSchemaCollector.instance);
  4794. return !itemValidationResult.hasProblems();
  4795. });
  4796. if (!doesContain) {
  4797. validationResult.problems.push({
  4798. location: { offset: node.offset, length: node.length },
  4799. message: schema.errorMessage || localize('requiredItemMissingWarning', 'Array does not contain required item.')
  4800. });
  4801. }
  4802. }
  4803. if (objects_1.isNumber(schema.minItems) && node.items.length < schema.minItems) {
  4804. validationResult.problems.push({
  4805. location: { offset: node.offset, length: node.length },
  4806. message: localize('minItemsWarning', 'Array has too few items. Expected {0} or more.', schema.minItems)
  4807. });
  4808. }
  4809. if (objects_1.isNumber(schema.maxItems) && node.items.length > schema.maxItems) {
  4810. validationResult.problems.push({
  4811. location: { offset: node.offset, length: node.length },
  4812. message: localize('maxItemsWarning', 'Array has too many items. Expected {0} or fewer.', schema.maxItems)
  4813. });
  4814. }
  4815. if (schema.uniqueItems === true) {
  4816. var values_1 = getNodeValue(node);
  4817. var duplicates = values_1.some(function (value, index) {
  4818. return index !== values_1.lastIndexOf(value);
  4819. });
  4820. if (duplicates) {
  4821. validationResult.problems.push({
  4822. location: { offset: node.offset, length: node.length },
  4823. message: localize('uniqueItemsWarning', 'Array has duplicate items.')
  4824. });
  4825. }
  4826. }
  4827. }
  4828. function _validateObjectNode(node, schema, validationResult, matchingSchemas) {
  4829. var seenKeys = Object.create(null);
  4830. var unprocessedProperties = [];
  4831. for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
  4832. var propertyNode = _a[_i];
  4833. var key = propertyNode.keyNode.value;
  4834. seenKeys[key] = propertyNode.valueNode;
  4835. unprocessedProperties.push(key);
  4836. }
  4837. if (Array.isArray(schema.required)) {
  4838. for (var _b = 0, _c = schema.required; _b < _c.length; _b++) {
  4839. var propertyName = _c[_b];
  4840. if (!seenKeys[propertyName]) {
  4841. var keyNode = node.parent && node.parent.type === 'property' && node.parent.keyNode;
  4842. var location = keyNode ? { offset: keyNode.offset, length: keyNode.length } : { offset: node.offset, length: 1 };
  4843. validationResult.problems.push({
  4844. location: location,
  4845. message: localize('MissingRequiredPropWarning', 'Missing property "{0}".', propertyName)
  4846. });
  4847. }
  4848. }
  4849. }
  4850. var propertyProcessed = function (prop) {
  4851. var index = unprocessedProperties.indexOf(prop);
  4852. while (index >= 0) {
  4853. unprocessedProperties.splice(index, 1);
  4854. index = unprocessedProperties.indexOf(prop);
  4855. }
  4856. };
  4857. if (schema.properties) {
  4858. for (var _d = 0, _e = Object.keys(schema.properties); _d < _e.length; _d++) {
  4859. var propertyName = _e[_d];
  4860. propertyProcessed(propertyName);
  4861. var propertySchema = schema.properties[propertyName];
  4862. var child = seenKeys[propertyName];
  4863. if (child) {
  4864. if (objects_1.isBoolean(propertySchema)) {
  4865. if (!propertySchema) {
  4866. var propertyNode = child.parent;
  4867. validationResult.problems.push({
  4868. location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
  4869. message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
  4870. });
  4871. }
  4872. else {
  4873. validationResult.propertiesMatches++;
  4874. validationResult.propertiesValueMatches++;
  4875. }
  4876. }
  4877. else {
  4878. var propertyValidationResult = new ValidationResult();
  4879. validate(child, propertySchema, propertyValidationResult, matchingSchemas);
  4880. validationResult.mergePropertyMatch(propertyValidationResult);
  4881. }
  4882. }
  4883. }
  4884. }
  4885. if (schema.patternProperties) {
  4886. for (var _f = 0, _g = Object.keys(schema.patternProperties); _f < _g.length; _f++) {
  4887. var propertyPattern = _g[_f];
  4888. var regex = strings_1.extendedRegExp(propertyPattern);
  4889. for (var _h = 0, _j = unprocessedProperties.slice(0); _h < _j.length; _h++) {
  4890. var propertyName = _j[_h];
  4891. if (regex.test(propertyName)) {
  4892. propertyProcessed(propertyName);
  4893. var child = seenKeys[propertyName];
  4894. if (child) {
  4895. var propertySchema = schema.patternProperties[propertyPattern];
  4896. if (objects_1.isBoolean(propertySchema)) {
  4897. if (!propertySchema) {
  4898. var propertyNode = child.parent;
  4899. validationResult.problems.push({
  4900. location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
  4901. message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
  4902. });
  4903. }
  4904. else {
  4905. validationResult.propertiesMatches++;
  4906. validationResult.propertiesValueMatches++;
  4907. }
  4908. }
  4909. else {
  4910. var propertyValidationResult = new ValidationResult();
  4911. validate(child, propertySchema, propertyValidationResult, matchingSchemas);
  4912. validationResult.mergePropertyMatch(propertyValidationResult);
  4913. }
  4914. }
  4915. }
  4916. }
  4917. }
  4918. }
  4919. if (typeof schema.additionalProperties === 'object') {
  4920. for (var _k = 0, unprocessedProperties_1 = unprocessedProperties; _k < unprocessedProperties_1.length; _k++) {
  4921. var propertyName = unprocessedProperties_1[_k];
  4922. var child = seenKeys[propertyName];
  4923. if (child) {
  4924. var propertyValidationResult = new ValidationResult();
  4925. validate(child, schema.additionalProperties, propertyValidationResult, matchingSchemas);
  4926. validationResult.mergePropertyMatch(propertyValidationResult);
  4927. }
  4928. }
  4929. }
  4930. else if (schema.additionalProperties === false) {
  4931. if (unprocessedProperties.length > 0) {
  4932. for (var _l = 0, unprocessedProperties_2 = unprocessedProperties; _l < unprocessedProperties_2.length; _l++) {
  4933. var propertyName = unprocessedProperties_2[_l];
  4934. var child = seenKeys[propertyName];
  4935. if (child) {
  4936. var propertyNode = child.parent;
  4937. validationResult.problems.push({
  4938. location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
  4939. message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
  4940. });
  4941. }
  4942. }
  4943. }
  4944. }
  4945. if (objects_1.isNumber(schema.maxProperties)) {
  4946. if (node.properties.length > schema.maxProperties) {
  4947. validationResult.problems.push({
  4948. location: { offset: node.offset, length: node.length },
  4949. message: localize('MaxPropWarning', 'Object has more properties than limit of {0}.', schema.maxProperties)
  4950. });
  4951. }
  4952. }
  4953. if (objects_1.isNumber(schema.minProperties)) {
  4954. if (node.properties.length < schema.minProperties) {
  4955. validationResult.problems.push({
  4956. location: { offset: node.offset, length: node.length },
  4957. message: localize('MinPropWarning', 'Object has fewer properties than the required number of {0}', schema.minProperties)
  4958. });
  4959. }
  4960. }
  4961. if (schema.dependencies) {
  4962. for (var _m = 0, _o = Object.keys(schema.dependencies); _m < _o.length; _m++) {
  4963. var key = _o[_m];
  4964. var prop = seenKeys[key];
  4965. if (prop) {
  4966. var propertyDep = schema.dependencies[key];
  4967. if (Array.isArray(propertyDep)) {
  4968. for (var _p = 0, propertyDep_1 = propertyDep; _p < propertyDep_1.length; _p++) {
  4969. var requiredProp = propertyDep_1[_p];
  4970. if (!seenKeys[requiredProp]) {
  4971. validationResult.problems.push({
  4972. location: { offset: node.offset, length: node.length },
  4973. message: localize('RequiredDependentPropWarning', 'Object is missing property {0} required by property {1}.', requiredProp, key)
  4974. });
  4975. }
  4976. else {
  4977. validationResult.propertiesValueMatches++;
  4978. }
  4979. }
  4980. }
  4981. else {
  4982. var propertySchema = asSchema(propertyDep);
  4983. if (propertySchema) {
  4984. var propertyValidationResult = new ValidationResult();
  4985. validate(node, propertySchema, propertyValidationResult, matchingSchemas);
  4986. validationResult.mergePropertyMatch(propertyValidationResult);
  4987. }
  4988. }
  4989. }
  4990. }
  4991. }
  4992. var propertyNames = asSchema(schema.propertyNames);
  4993. if (propertyNames) {
  4994. for (var _q = 0, _r = node.properties; _q < _r.length; _q++) {
  4995. var f = _r[_q];
  4996. var key = f.keyNode;
  4997. if (key) {
  4998. validate(key, propertyNames, validationResult, NoOpSchemaCollector.instance);
  4999. }
  5000. }
  5001. }
  5002. }
  5003. }
  5004. function parse(textDocument, config) {
  5005. var problems = [];
  5006. var lastProblemOffset = -1;
  5007. var text = textDocument.getText();
  5008. var scanner = Json.createScanner(text, false);
  5009. var commentRanges = config && config.collectComments ? [] : undefined;
  5010. function _scanNext() {
  5011. while (true) {
  5012. var token_1 = scanner.scan();
  5013. _checkScanError();
  5014. switch (token_1) {
  5015. case 12 /* LineCommentTrivia */:
  5016. case 13 /* BlockCommentTrivia */:
  5017. if (Array.isArray(commentRanges)) {
  5018. commentRanges.push(jsonLanguageTypes_1.Range.create(textDocument.positionAt(scanner.getTokenOffset()), textDocument.positionAt(scanner.getTokenOffset() + scanner.getTokenLength())));
  5019. }
  5020. break;
  5021. case 15 /* Trivia */:
  5022. case 14 /* LineBreakTrivia */:
  5023. break;
  5024. default:
  5025. return token_1;
  5026. }
  5027. }
  5028. }
  5029. function _accept(token) {
  5030. if (scanner.getToken() === token) {
  5031. _scanNext();
  5032. return true;
  5033. }
  5034. return false;
  5035. }
  5036. function _errorAtRange(message, code, startOffset, endOffset, severity) {
  5037. if (severity === void 0) { severity = jsonLanguageTypes_1.DiagnosticSeverity.Error; }
  5038. if (problems.length === 0 || startOffset !== lastProblemOffset) {
  5039. var range = jsonLanguageTypes_1.Range.create(textDocument.positionAt(startOffset), textDocument.positionAt(endOffset));
  5040. problems.push(jsonLanguageTypes_1.Diagnostic.create(range, message, severity, code, textDocument.languageId));
  5041. lastProblemOffset = startOffset;
  5042. }
  5043. }
  5044. function _error(message, code, node, skipUntilAfter, skipUntil) {
  5045. if (node === void 0) { node = undefined; }
  5046. if (skipUntilAfter === void 0) { skipUntilAfter = []; }
  5047. if (skipUntil === void 0) { skipUntil = []; }
  5048. var start = scanner.getTokenOffset();
  5049. var end = scanner.getTokenOffset() + scanner.getTokenLength();
  5050. if (start === end && start > 0) {
  5051. start--;
  5052. while (start > 0 && /\s/.test(text.charAt(start))) {
  5053. start--;
  5054. }
  5055. end = start + 1;
  5056. }
  5057. _errorAtRange(message, code, start, end);
  5058. if (node) {
  5059. _finalize(node, false);
  5060. }
  5061. if (skipUntilAfter.length + skipUntil.length > 0) {
  5062. var token_2 = scanner.getToken();
  5063. while (token_2 !== 17 /* EOF */) {
  5064. if (skipUntilAfter.indexOf(token_2) !== -1) {
  5065. _scanNext();
  5066. break;
  5067. }
  5068. else if (skipUntil.indexOf(token_2) !== -1) {
  5069. break;
  5070. }
  5071. token_2 = _scanNext();
  5072. }
  5073. }
  5074. return node;
  5075. }
  5076. function _checkScanError() {
  5077. switch (scanner.getTokenError()) {
  5078. case 4 /* InvalidUnicode */:
  5079. _error(localize('InvalidUnicode', 'Invalid unicode sequence in string.'), jsonLanguageTypes_1.ErrorCode.InvalidUnicode);
  5080. return true;
  5081. case 5 /* InvalidEscapeCharacter */:
  5082. _error(localize('InvalidEscapeCharacter', 'Invalid escape character in string.'), jsonLanguageTypes_1.ErrorCode.InvalidEscapeCharacter);
  5083. return true;
  5084. case 3 /* UnexpectedEndOfNumber */:
  5085. _error(localize('UnexpectedEndOfNumber', 'Unexpected end of number.'), jsonLanguageTypes_1.ErrorCode.UnexpectedEndOfNumber);
  5086. return true;
  5087. case 1 /* UnexpectedEndOfComment */:
  5088. _error(localize('UnexpectedEndOfComment', 'Unexpected end of comment.'), jsonLanguageTypes_1.ErrorCode.UnexpectedEndOfComment);
  5089. return true;
  5090. case 2 /* UnexpectedEndOfString */:
  5091. _error(localize('UnexpectedEndOfString', 'Unexpected end of string.'), jsonLanguageTypes_1.ErrorCode.UnexpectedEndOfString);
  5092. return true;
  5093. case 6 /* InvalidCharacter */:
  5094. _error(localize('InvalidCharacter', 'Invalid characters in string. Control characters must be escaped.'), jsonLanguageTypes_1.ErrorCode.InvalidCharacter);
  5095. return true;
  5096. }
  5097. return false;
  5098. }
  5099. function _finalize(node, scanNext) {
  5100. node.length = scanner.getTokenOffset() + scanner.getTokenLength() - node.offset;
  5101. if (scanNext) {
  5102. _scanNext();
  5103. }
  5104. return node;
  5105. }
  5106. function _parseArray(parent) {
  5107. if (scanner.getToken() !== 3 /* OpenBracketToken */) {
  5108. return undefined;
  5109. }
  5110. var node = new ArrayASTNodeImpl(parent, scanner.getTokenOffset());
  5111. _scanNext(); // consume OpenBracketToken
  5112. var count = 0;
  5113. var needsComma = false;
  5114. while (scanner.getToken() !== 4 /* CloseBracketToken */ && scanner.getToken() !== 17 /* EOF */) {
  5115. if (scanner.getToken() === 5 /* CommaToken */) {
  5116. if (!needsComma) {
  5117. _error(localize('ValueExpected', 'Value expected'), jsonLanguageTypes_1.ErrorCode.ValueExpected);
  5118. }
  5119. var commaOffset = scanner.getTokenOffset();
  5120. _scanNext(); // consume comma
  5121. if (scanner.getToken() === 4 /* CloseBracketToken */) {
  5122. if (needsComma) {
  5123. _errorAtRange(localize('TrailingComma', 'Trailing comma'), jsonLanguageTypes_1.ErrorCode.TrailingComma, commaOffset, commaOffset + 1);
  5124. }
  5125. continue;
  5126. }
  5127. }
  5128. else if (needsComma) {
  5129. _error(localize('ExpectedComma', 'Expected comma'), jsonLanguageTypes_1.ErrorCode.CommaExpected);
  5130. }
  5131. var item = _parseValue(node);
  5132. if (!item) {
  5133. _error(localize('PropertyExpected', 'Value expected'), jsonLanguageTypes_1.ErrorCode.ValueExpected, undefined, [], [4 /* CloseBracketToken */, 5 /* CommaToken */]);
  5134. }
  5135. else {
  5136. node.items.push(item);
  5137. }
  5138. needsComma = true;
  5139. }
  5140. if (scanner.getToken() !== 4 /* CloseBracketToken */) {
  5141. return _error(localize('ExpectedCloseBracket', 'Expected comma or closing bracket'), jsonLanguageTypes_1.ErrorCode.CommaOrCloseBacketExpected, node);
  5142. }
  5143. return _finalize(node, true);
  5144. }
  5145. var keyPlaceholder = new StringASTNodeImpl(undefined, 0, 0);
  5146. function _parseProperty(parent, keysSeen) {
  5147. var node = new PropertyASTNodeImpl(parent, scanner.getTokenOffset(), keyPlaceholder);
  5148. var key = _parseString(node);
  5149. if (!key) {
  5150. if (scanner.getToken() === 16 /* Unknown */) {
  5151. // give a more helpful error message
  5152. _error(localize('DoubleQuotesExpected', 'Property keys must be doublequoted'), jsonLanguageTypes_1.ErrorCode.Undefined);
  5153. var keyNode = new StringASTNodeImpl(node, scanner.getTokenOffset(), scanner.getTokenLength());
  5154. keyNode.value = scanner.getTokenValue();
  5155. key = keyNode;
  5156. _scanNext(); // consume Unknown
  5157. }
  5158. else {
  5159. return undefined;
  5160. }
  5161. }
  5162. node.keyNode = key;
  5163. var seen = keysSeen[key.value];
  5164. if (seen) {
  5165. _errorAtRange(localize('DuplicateKeyWarning', "Duplicate object key"), jsonLanguageTypes_1.ErrorCode.DuplicateKey, node.keyNode.offset, node.keyNode.offset + node.keyNode.length, jsonLanguageTypes_1.DiagnosticSeverity.Warning);
  5166. if (typeof seen === 'object') {
  5167. _errorAtRange(localize('DuplicateKeyWarning', "Duplicate object key"), jsonLanguageTypes_1.ErrorCode.DuplicateKey, seen.keyNode.offset, seen.keyNode.offset + seen.keyNode.length, jsonLanguageTypes_1.DiagnosticSeverity.Warning);
  5168. }
  5169. keysSeen[key.value] = true; // if the same key is duplicate again, avoid duplicate error reporting
  5170. }
  5171. else {
  5172. keysSeen[key.value] = node;
  5173. }
  5174. if (scanner.getToken() === 6 /* ColonToken */) {
  5175. node.colonOffset = scanner.getTokenOffset();
  5176. _scanNext(); // consume ColonToken
  5177. }
  5178. else {
  5179. _error(localize('ColonExpected', 'Colon expected'), jsonLanguageTypes_1.ErrorCode.ColonExpected);
  5180. if (scanner.getToken() === 10 /* StringLiteral */ && textDocument.positionAt(key.offset + key.length).line < textDocument.positionAt(scanner.getTokenOffset()).line) {
  5181. node.length = key.length;
  5182. return node;
  5183. }
  5184. }
  5185. var value = _parseValue(node);
  5186. if (!value) {
  5187. return _error(localize('ValueExpected', 'Value expected'), jsonLanguageTypes_1.ErrorCode.ValueExpected, node, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  5188. }
  5189. node.valueNode = value;
  5190. node.length = value.offset + value.length - node.offset;
  5191. return node;
  5192. }
  5193. function _parseObject(parent) {
  5194. if (scanner.getToken() !== 1 /* OpenBraceToken */) {
  5195. return undefined;
  5196. }
  5197. var node = new ObjectASTNodeImpl(parent, scanner.getTokenOffset());
  5198. var keysSeen = Object.create(null);
  5199. _scanNext(); // consume OpenBraceToken
  5200. var needsComma = false;
  5201. while (scanner.getToken() !== 2 /* CloseBraceToken */ && scanner.getToken() !== 17 /* EOF */) {
  5202. if (scanner.getToken() === 5 /* CommaToken */) {
  5203. if (!needsComma) {
  5204. _error(localize('PropertyExpected', 'Property expected'), jsonLanguageTypes_1.ErrorCode.PropertyExpected);
  5205. }
  5206. var commaOffset = scanner.getTokenOffset();
  5207. _scanNext(); // consume comma
  5208. if (scanner.getToken() === 2 /* CloseBraceToken */) {
  5209. if (needsComma) {
  5210. _errorAtRange(localize('TrailingComma', 'Trailing comma'), jsonLanguageTypes_1.ErrorCode.TrailingComma, commaOffset, commaOffset + 1);
  5211. }
  5212. continue;
  5213. }
  5214. }
  5215. else if (needsComma) {
  5216. _error(localize('ExpectedComma', 'Expected comma'), jsonLanguageTypes_1.ErrorCode.CommaExpected);
  5217. }
  5218. var property = _parseProperty(node, keysSeen);
  5219. if (!property) {
  5220. _error(localize('PropertyExpected', 'Property expected'), jsonLanguageTypes_1.ErrorCode.PropertyExpected, undefined, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  5221. }
  5222. else {
  5223. node.properties.push(property);
  5224. }
  5225. needsComma = true;
  5226. }
  5227. if (scanner.getToken() !== 2 /* CloseBraceToken */) {
  5228. return _error(localize('ExpectedCloseBrace', 'Expected comma or closing brace'), jsonLanguageTypes_1.ErrorCode.CommaOrCloseBraceExpected, node);
  5229. }
  5230. return _finalize(node, true);
  5231. }
  5232. function _parseString(parent) {
  5233. if (scanner.getToken() !== 10 /* StringLiteral */) {
  5234. return undefined;
  5235. }
  5236. var node = new StringASTNodeImpl(parent, scanner.getTokenOffset());
  5237. node.value = scanner.getTokenValue();
  5238. return _finalize(node, true);
  5239. }
  5240. function _parseNumber(parent) {
  5241. if (scanner.getToken() !== 11 /* NumericLiteral */) {
  5242. return undefined;
  5243. }
  5244. var node = new NumberASTNodeImpl(parent, scanner.getTokenOffset());
  5245. if (scanner.getTokenError() === 0 /* None */) {
  5246. var tokenValue = scanner.getTokenValue();
  5247. try {
  5248. var numberValue = JSON.parse(tokenValue);
  5249. if (!objects_1.isNumber(numberValue)) {
  5250. return _error(localize('InvalidNumberFormat', 'Invalid number format.'), jsonLanguageTypes_1.ErrorCode.Undefined, node);
  5251. }
  5252. node.value = numberValue;
  5253. }
  5254. catch (e) {
  5255. return _error(localize('InvalidNumberFormat', 'Invalid number format.'), jsonLanguageTypes_1.ErrorCode.Undefined, node);
  5256. }
  5257. node.isInteger = tokenValue.indexOf('.') === -1;
  5258. }
  5259. return _finalize(node, true);
  5260. }
  5261. function _parseLiteral(parent) {
  5262. var node;
  5263. switch (scanner.getToken()) {
  5264. case 7 /* NullKeyword */:
  5265. return _finalize(new NullASTNodeImpl(parent, scanner.getTokenOffset()), true);
  5266. case 8 /* TrueKeyword */:
  5267. return _finalize(new BooleanASTNodeImpl(parent, true, scanner.getTokenOffset()), true);
  5268. case 9 /* FalseKeyword */:
  5269. return _finalize(new BooleanASTNodeImpl(parent, false, scanner.getTokenOffset()), true);
  5270. default:
  5271. return undefined;
  5272. }
  5273. }
  5274. function _parseValue(parent) {
  5275. return _parseArray(parent) || _parseObject(parent) || _parseString(parent) || _parseNumber(parent) || _parseLiteral(parent);
  5276. }
  5277. var _root = undefined;
  5278. var token = _scanNext();
  5279. if (token !== 17 /* EOF */) {
  5280. _root = _parseValue(_root);
  5281. if (!_root) {
  5282. _error(localize('Invalid symbol', 'Expected a JSON object, array or literal.'), jsonLanguageTypes_1.ErrorCode.Undefined);
  5283. }
  5284. else if (scanner.getToken() !== 17 /* EOF */) {
  5285. _error(localize('End of file expected', 'End of file expected.'), jsonLanguageTypes_1.ErrorCode.Undefined);
  5286. }
  5287. }
  5288. return new JSONDocument(_root, problems, commentRanges);
  5289. }
  5290. exports.parse = parse;
  5291. });
  5292. /*---------------------------------------------------------------------------------------------
  5293. * Copyright (c) Microsoft Corporation. All rights reserved.
  5294. * Licensed under the MIT License. See License.txt in the project root for license information.
  5295. *--------------------------------------------------------------------------------------------*/
  5296. (function (factory) {
  5297. if (typeof module === "object" && typeof module.exports === "object") {
  5298. var v = factory(require, exports);
  5299. if (v !== undefined) module.exports = v;
  5300. }
  5301. else if (typeof define === "function" && define.amd) {
  5302. define('vscode-json-languageservice/utils/json',["require", "exports"], factory);
  5303. }
  5304. })(function (require, exports) {
  5305. "use strict";
  5306. Object.defineProperty(exports, "__esModule", { value: true });
  5307. exports.stringifyObject = void 0;
  5308. function stringifyObject(obj, indent, stringifyLiteral) {
  5309. if (obj !== null && typeof obj === 'object') {
  5310. var newIndent = indent + '\t';
  5311. if (Array.isArray(obj)) {
  5312. if (obj.length === 0) {
  5313. return '[]';
  5314. }
  5315. var result = '[\n';
  5316. for (var i = 0; i < obj.length; i++) {
  5317. result += newIndent + stringifyObject(obj[i], newIndent, stringifyLiteral);
  5318. if (i < obj.length - 1) {
  5319. result += ',';
  5320. }
  5321. result += '\n';
  5322. }
  5323. result += indent + ']';
  5324. return result;
  5325. }
  5326. else {
  5327. var keys = Object.keys(obj);
  5328. if (keys.length === 0) {
  5329. return '{}';
  5330. }
  5331. var result = '{\n';
  5332. for (var i = 0; i < keys.length; i++) {
  5333. var key = keys[i];
  5334. result += newIndent + JSON.stringify(key) + ': ' + stringifyObject(obj[key], newIndent, stringifyLiteral);
  5335. if (i < keys.length - 1) {
  5336. result += ',';
  5337. }
  5338. result += '\n';
  5339. }
  5340. result += indent + '}';
  5341. return result;
  5342. }
  5343. }
  5344. return stringifyLiteral(obj);
  5345. }
  5346. exports.stringifyObject = stringifyObject;
  5347. });
  5348. /*---------------------------------------------------------------------------------------------
  5349. * Copyright (c) Microsoft Corporation. All rights reserved.
  5350. * Licensed under the MIT License. See License.txt in the project root for license information.
  5351. *--------------------------------------------------------------------------------------------*/
  5352. (function (factory) {
  5353. if (typeof module === "object" && typeof module.exports === "object") {
  5354. var v = factory(require, exports);
  5355. if (v !== undefined) module.exports = v;
  5356. }
  5357. else if (typeof define === "function" && define.amd) {
  5358. define('vscode-json-languageservice/services/jsonCompletion',["require", "exports", "../parser/jsonParser", "jsonc-parser", "../utils/json", "../utils/strings", "../utils/objects", "../jsonLanguageTypes", "vscode-nls"], factory);
  5359. }
  5360. })(function (require, exports) {
  5361. "use strict";
  5362. Object.defineProperty(exports, "__esModule", { value: true });
  5363. exports.JSONCompletion = void 0;
  5364. var Parser = require("../parser/jsonParser");
  5365. var Json = require("jsonc-parser");
  5366. var json_1 = require("../utils/json");
  5367. var strings_1 = require("../utils/strings");
  5368. var objects_1 = require("../utils/objects");
  5369. var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
  5370. var nls = require("vscode-nls");
  5371. var localize = nls.loadMessageBundle();
  5372. var valueCommitCharacters = [',', '}', ']'];
  5373. var propertyCommitCharacters = [':'];
  5374. var JSONCompletion = /** @class */ (function () {
  5375. function JSONCompletion(schemaService, contributions, promiseConstructor, clientCapabilities) {
  5376. if (contributions === void 0) { contributions = []; }
  5377. if (promiseConstructor === void 0) { promiseConstructor = Promise; }
  5378. if (clientCapabilities === void 0) { clientCapabilities = {}; }
  5379. this.schemaService = schemaService;
  5380. this.contributions = contributions;
  5381. this.promiseConstructor = promiseConstructor;
  5382. this.clientCapabilities = clientCapabilities;
  5383. }
  5384. JSONCompletion.prototype.doResolve = function (item) {
  5385. for (var i = this.contributions.length - 1; i >= 0; i--) {
  5386. var resolveCompletion = this.contributions[i].resolveCompletion;
  5387. if (resolveCompletion) {
  5388. var resolver = resolveCompletion(item);
  5389. if (resolver) {
  5390. return resolver;
  5391. }
  5392. }
  5393. }
  5394. return this.promiseConstructor.resolve(item);
  5395. };
  5396. JSONCompletion.prototype.doComplete = function (document, position, doc) {
  5397. var _this = this;
  5398. var result = {
  5399. items: [],
  5400. isIncomplete: false
  5401. };
  5402. var text = document.getText();
  5403. var offset = document.offsetAt(position);
  5404. var node = doc.getNodeFromOffset(offset, true);
  5405. if (this.isInComment(document, node ? node.offset : 0, offset)) {
  5406. return Promise.resolve(result);
  5407. }
  5408. if (node && (offset === node.offset + node.length) && offset > 0) {
  5409. var ch = text[offset - 1];
  5410. if (node.type === 'object' && ch === '}' || node.type === 'array' && ch === ']') {
  5411. // after ] or }
  5412. node = node.parent;
  5413. }
  5414. }
  5415. var currentWord = this.getCurrentWord(document, offset);
  5416. var overwriteRange;
  5417. if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
  5418. overwriteRange = jsonLanguageTypes_1.Range.create(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
  5419. }
  5420. else {
  5421. var overwriteStart = offset - currentWord.length;
  5422. if (overwriteStart > 0 && text[overwriteStart - 1] === '"') {
  5423. overwriteStart--;
  5424. }
  5425. overwriteRange = jsonLanguageTypes_1.Range.create(document.positionAt(overwriteStart), position);
  5426. }
  5427. var supportsCommitCharacters = false; //this.doesSupportsCommitCharacters(); disabled for now, waiting for new API: https://github.com/microsoft/vscode/issues/42544
  5428. var proposed = {};
  5429. var collector = {
  5430. add: function (suggestion) {
  5431. var label = suggestion.label;
  5432. var existing = proposed[label];
  5433. if (!existing) {
  5434. label = label.replace(/[\n]/g, '↵');
  5435. if (label.length > 60) {
  5436. var shortendedLabel = label.substr(0, 57).trim() + '...';
  5437. if (!proposed[shortendedLabel]) {
  5438. label = shortendedLabel;
  5439. }
  5440. }
  5441. if (overwriteRange && suggestion.insertText !== undefined) {
  5442. suggestion.textEdit = jsonLanguageTypes_1.TextEdit.replace(overwriteRange, suggestion.insertText);
  5443. }
  5444. if (supportsCommitCharacters) {
  5445. suggestion.commitCharacters = suggestion.kind === jsonLanguageTypes_1.CompletionItemKind.Property ? propertyCommitCharacters : valueCommitCharacters;
  5446. }
  5447. suggestion.label = label;
  5448. proposed[label] = suggestion;
  5449. result.items.push(suggestion);
  5450. }
  5451. else {
  5452. if (!existing.documentation) {
  5453. existing.documentation = suggestion.documentation;
  5454. }
  5455. if (!existing.detail) {
  5456. existing.detail = suggestion.detail;
  5457. }
  5458. }
  5459. },
  5460. setAsIncomplete: function () {
  5461. result.isIncomplete = true;
  5462. },
  5463. error: function (message) {
  5464. console.error(message);
  5465. },
  5466. log: function (message) {
  5467. console.log(message);
  5468. },
  5469. getNumberOfProposals: function () {
  5470. return result.items.length;
  5471. }
  5472. };
  5473. return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
  5474. var collectionPromises = [];
  5475. var addValue = true;
  5476. var currentKey = '';
  5477. var currentProperty = undefined;
  5478. if (node) {
  5479. if (node.type === 'string') {
  5480. var parent = node.parent;
  5481. if (parent && parent.type === 'property' && parent.keyNode === node) {
  5482. addValue = !parent.valueNode;
  5483. currentProperty = parent;
  5484. currentKey = text.substr(node.offset + 1, node.length - 2);
  5485. if (parent) {
  5486. node = parent.parent;
  5487. }
  5488. }
  5489. }
  5490. }
  5491. // proposals for properties
  5492. if (node && node.type === 'object') {
  5493. // don't suggest keys when the cursor is just before the opening curly brace
  5494. if (node.offset === offset) {
  5495. return result;
  5496. }
  5497. // don't suggest properties that are already present
  5498. var properties = node.properties;
  5499. properties.forEach(function (p) {
  5500. if (!currentProperty || currentProperty !== p) {
  5501. proposed[p.keyNode.value] = jsonLanguageTypes_1.CompletionItem.create('__');
  5502. }
  5503. });
  5504. var separatorAfter_1 = '';
  5505. if (addValue) {
  5506. separatorAfter_1 = _this.evaluateSeparatorAfter(document, document.offsetAt(overwriteRange.end));
  5507. }
  5508. if (schema) {
  5509. // property proposals with schema
  5510. _this.getPropertyCompletions(schema, doc, node, addValue, separatorAfter_1, collector);
  5511. }
  5512. else {
  5513. // property proposals without schema
  5514. _this.getSchemaLessPropertyCompletions(doc, node, currentKey, collector);
  5515. }
  5516. var location_1 = Parser.getNodePath(node);
  5517. _this.contributions.forEach(function (contribution) {
  5518. var collectPromise = contribution.collectPropertyCompletions(document.uri, location_1, currentWord, addValue, separatorAfter_1 === '', collector);
  5519. if (collectPromise) {
  5520. collectionPromises.push(collectPromise);
  5521. }
  5522. });
  5523. if ((!schema && currentWord.length > 0 && text.charAt(offset - currentWord.length - 1) !== '"')) {
  5524. collector.add({
  5525. kind: jsonLanguageTypes_1.CompletionItemKind.Property,
  5526. label: _this.getLabelForValue(currentWord),
  5527. insertText: _this.getInsertTextForProperty(currentWord, undefined, false, separatorAfter_1),
  5528. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet, documentation: '',
  5529. });
  5530. collector.setAsIncomplete();
  5531. }
  5532. }
  5533. // proposals for values
  5534. var types = {};
  5535. if (schema) {
  5536. // value proposals with schema
  5537. _this.getValueCompletions(schema, doc, node, offset, document, collector, types);
  5538. }
  5539. else {
  5540. // value proposals without schema
  5541. _this.getSchemaLessValueCompletions(doc, node, offset, document, collector);
  5542. }
  5543. if (_this.contributions.length > 0) {
  5544. _this.getContributedValueCompletions(doc, node, offset, document, collector, collectionPromises);
  5545. }
  5546. return _this.promiseConstructor.all(collectionPromises).then(function () {
  5547. if (collector.getNumberOfProposals() === 0) {
  5548. var offsetForSeparator = offset;
  5549. if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
  5550. offsetForSeparator = node.offset + node.length;
  5551. }
  5552. var separatorAfter = _this.evaluateSeparatorAfter(document, offsetForSeparator);
  5553. _this.addFillerValueCompletions(types, separatorAfter, collector);
  5554. }
  5555. return result;
  5556. });
  5557. });
  5558. };
  5559. JSONCompletion.prototype.getPropertyCompletions = function (schema, doc, node, addValue, separatorAfter, collector) {
  5560. var _this = this;
  5561. var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset);
  5562. matchingSchemas.forEach(function (s) {
  5563. if (s.node === node && !s.inverted) {
  5564. var schemaProperties_1 = s.schema.properties;
  5565. if (schemaProperties_1) {
  5566. Object.keys(schemaProperties_1).forEach(function (key) {
  5567. var propertySchema = schemaProperties_1[key];
  5568. if (typeof propertySchema === 'object' && !propertySchema.deprecationMessage && !propertySchema.doNotSuggest) {
  5569. var proposal = {
  5570. kind: jsonLanguageTypes_1.CompletionItemKind.Property,
  5571. label: key,
  5572. insertText: _this.getInsertTextForProperty(key, propertySchema, addValue, separatorAfter),
  5573. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5574. filterText: _this.getFilterTextForValue(key),
  5575. documentation: _this.fromMarkup(propertySchema.markdownDescription) || propertySchema.description || '',
  5576. };
  5577. if (propertySchema.suggestSortText !== undefined) {
  5578. proposal.sortText = propertySchema.suggestSortText;
  5579. }
  5580. if (proposal.insertText && strings_1.endsWith(proposal.insertText, "$1" + separatorAfter)) {
  5581. proposal.command = {
  5582. title: 'Suggest',
  5583. command: 'editor.action.triggerSuggest'
  5584. };
  5585. }
  5586. collector.add(proposal);
  5587. }
  5588. });
  5589. }
  5590. var schemaPropertyNames_1 = s.schema.propertyNames;
  5591. if (typeof schemaPropertyNames_1 === 'object' && !schemaPropertyNames_1.deprecationMessage && !schemaPropertyNames_1.doNotSuggest) {
  5592. var propertyNameCompletionItem = function (name, enumDescription) {
  5593. if (enumDescription === void 0) { enumDescription = undefined; }
  5594. var proposal = {
  5595. kind: jsonLanguageTypes_1.CompletionItemKind.Property,
  5596. label: name,
  5597. insertText: _this.getInsertTextForProperty(name, undefined, addValue, separatorAfter),
  5598. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5599. filterText: _this.getFilterTextForValue(name),
  5600. documentation: enumDescription || _this.fromMarkup(schemaPropertyNames_1.markdownDescription) || schemaPropertyNames_1.description || '',
  5601. };
  5602. if (schemaPropertyNames_1.suggestSortText !== undefined) {
  5603. proposal.sortText = schemaPropertyNames_1.suggestSortText;
  5604. }
  5605. if (proposal.insertText && strings_1.endsWith(proposal.insertText, "$1" + separatorAfter)) {
  5606. proposal.command = {
  5607. title: 'Suggest',
  5608. command: 'editor.action.triggerSuggest'
  5609. };
  5610. }
  5611. collector.add(proposal);
  5612. };
  5613. if (schemaPropertyNames_1.enum) {
  5614. for (var i = 0; i < schemaPropertyNames_1.enum.length; i++) {
  5615. var enumDescription = undefined;
  5616. if (schemaPropertyNames_1.markdownEnumDescriptions && i < schemaPropertyNames_1.markdownEnumDescriptions.length) {
  5617. enumDescription = _this.fromMarkup(schemaPropertyNames_1.markdownEnumDescriptions[i]);
  5618. }
  5619. else if (schemaPropertyNames_1.enumDescriptions && i < schemaPropertyNames_1.enumDescriptions.length) {
  5620. enumDescription = schemaPropertyNames_1.enumDescriptions[i];
  5621. }
  5622. propertyNameCompletionItem(schemaPropertyNames_1.enum[i], enumDescription);
  5623. }
  5624. }
  5625. if (schemaPropertyNames_1.const) {
  5626. propertyNameCompletionItem(schemaPropertyNames_1.const);
  5627. }
  5628. }
  5629. }
  5630. });
  5631. };
  5632. JSONCompletion.prototype.getSchemaLessPropertyCompletions = function (doc, node, currentKey, collector) {
  5633. var _this = this;
  5634. var collectCompletionsForSimilarObject = function (obj) {
  5635. obj.properties.forEach(function (p) {
  5636. var key = p.keyNode.value;
  5637. collector.add({
  5638. kind: jsonLanguageTypes_1.CompletionItemKind.Property,
  5639. label: key,
  5640. insertText: _this.getInsertTextForValue(key, ''),
  5641. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5642. filterText: _this.getFilterTextForValue(key),
  5643. documentation: ''
  5644. });
  5645. });
  5646. };
  5647. if (node.parent) {
  5648. if (node.parent.type === 'property') {
  5649. // if the object is a property value, check the tree for other objects that hang under a property of the same name
  5650. var parentKey_1 = node.parent.keyNode.value;
  5651. doc.visit(function (n) {
  5652. if (n.type === 'property' && n !== node.parent && n.keyNode.value === parentKey_1 && n.valueNode && n.valueNode.type === 'object') {
  5653. collectCompletionsForSimilarObject(n.valueNode);
  5654. }
  5655. return true;
  5656. });
  5657. }
  5658. else if (node.parent.type === 'array') {
  5659. // if the object is in an array, use all other array elements as similar objects
  5660. node.parent.items.forEach(function (n) {
  5661. if (n.type === 'object' && n !== node) {
  5662. collectCompletionsForSimilarObject(n);
  5663. }
  5664. });
  5665. }
  5666. }
  5667. else if (node.type === 'object') {
  5668. collector.add({
  5669. kind: jsonLanguageTypes_1.CompletionItemKind.Property,
  5670. label: '$schema',
  5671. insertText: this.getInsertTextForProperty('$schema', undefined, true, ''),
  5672. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet, documentation: '',
  5673. filterText: this.getFilterTextForValue("$schema")
  5674. });
  5675. }
  5676. };
  5677. JSONCompletion.prototype.getSchemaLessValueCompletions = function (doc, node, offset, document, collector) {
  5678. var _this = this;
  5679. var offsetForSeparator = offset;
  5680. if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
  5681. offsetForSeparator = node.offset + node.length;
  5682. node = node.parent;
  5683. }
  5684. if (!node) {
  5685. collector.add({
  5686. kind: this.getSuggestionKind('object'),
  5687. label: 'Empty object',
  5688. insertText: this.getInsertTextForValue({}, ''),
  5689. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5690. documentation: ''
  5691. });
  5692. collector.add({
  5693. kind: this.getSuggestionKind('array'),
  5694. label: 'Empty array',
  5695. insertText: this.getInsertTextForValue([], ''),
  5696. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5697. documentation: ''
  5698. });
  5699. return;
  5700. }
  5701. var separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator);
  5702. var collectSuggestionsForValues = function (value) {
  5703. if (value.parent && !Parser.contains(value.parent, offset, true)) {
  5704. collector.add({
  5705. kind: _this.getSuggestionKind(value.type),
  5706. label: _this.getLabelTextForMatchingNode(value, document),
  5707. insertText: _this.getInsertTextForMatchingNode(value, document, separatorAfter),
  5708. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet, documentation: ''
  5709. });
  5710. }
  5711. if (value.type === 'boolean') {
  5712. _this.addBooleanValueCompletion(!value.value, separatorAfter, collector);
  5713. }
  5714. };
  5715. if (node.type === 'property') {
  5716. if (offset > (node.colonOffset || 0)) {
  5717. var valueNode = node.valueNode;
  5718. if (valueNode && (offset > (valueNode.offset + valueNode.length) || valueNode.type === 'object' || valueNode.type === 'array')) {
  5719. return;
  5720. }
  5721. // suggest values at the same key
  5722. var parentKey_2 = node.keyNode.value;
  5723. doc.visit(function (n) {
  5724. if (n.type === 'property' && n.keyNode.value === parentKey_2 && n.valueNode) {
  5725. collectSuggestionsForValues(n.valueNode);
  5726. }
  5727. return true;
  5728. });
  5729. if (parentKey_2 === '$schema' && node.parent && !node.parent.parent) {
  5730. this.addDollarSchemaCompletions(separatorAfter, collector);
  5731. }
  5732. }
  5733. }
  5734. if (node.type === 'array') {
  5735. if (node.parent && node.parent.type === 'property') {
  5736. // suggest items of an array at the same key
  5737. var parentKey_3 = node.parent.keyNode.value;
  5738. doc.visit(function (n) {
  5739. if (n.type === 'property' && n.keyNode.value === parentKey_3 && n.valueNode && n.valueNode.type === 'array') {
  5740. n.valueNode.items.forEach(collectSuggestionsForValues);
  5741. }
  5742. return true;
  5743. });
  5744. }
  5745. else {
  5746. // suggest items in the same array
  5747. node.items.forEach(collectSuggestionsForValues);
  5748. }
  5749. }
  5750. };
  5751. JSONCompletion.prototype.getValueCompletions = function (schema, doc, node, offset, document, collector, types) {
  5752. var offsetForSeparator = offset;
  5753. var parentKey = undefined;
  5754. var valueNode = undefined;
  5755. if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
  5756. offsetForSeparator = node.offset + node.length;
  5757. valueNode = node;
  5758. node = node.parent;
  5759. }
  5760. if (!node) {
  5761. this.addSchemaValueCompletions(schema.schema, '', collector, types);
  5762. return;
  5763. }
  5764. if ((node.type === 'property') && offset > (node.colonOffset || 0)) {
  5765. var valueNode_1 = node.valueNode;
  5766. if (valueNode_1 && offset > (valueNode_1.offset + valueNode_1.length)) {
  5767. return; // we are past the value node
  5768. }
  5769. parentKey = node.keyNode.value;
  5770. node = node.parent;
  5771. }
  5772. if (node && (parentKey !== undefined || node.type === 'array')) {
  5773. var separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator);
  5774. var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset, valueNode);
  5775. for (var _i = 0, matchingSchemas_1 = matchingSchemas; _i < matchingSchemas_1.length; _i++) {
  5776. var s = matchingSchemas_1[_i];
  5777. if (s.node === node && !s.inverted && s.schema) {
  5778. if (node.type === 'array' && s.schema.items) {
  5779. if (Array.isArray(s.schema.items)) {
  5780. var index = this.findItemAtOffset(node, document, offset);
  5781. if (index < s.schema.items.length) {
  5782. this.addSchemaValueCompletions(s.schema.items[index], separatorAfter, collector, types);
  5783. }
  5784. }
  5785. else {
  5786. this.addSchemaValueCompletions(s.schema.items, separatorAfter, collector, types);
  5787. }
  5788. }
  5789. if (parentKey !== undefined) {
  5790. var propertyMatched = false;
  5791. if (s.schema.properties) {
  5792. var propertySchema = s.schema.properties[parentKey];
  5793. if (propertySchema) {
  5794. propertyMatched = true;
  5795. this.addSchemaValueCompletions(propertySchema, separatorAfter, collector, types);
  5796. }
  5797. }
  5798. if (s.schema.patternProperties && !propertyMatched) {
  5799. for (var _a = 0, _b = Object.keys(s.schema.patternProperties); _a < _b.length; _a++) {
  5800. var pattern = _b[_a];
  5801. var regex = strings_1.extendedRegExp(pattern);
  5802. if (regex.test(parentKey)) {
  5803. propertyMatched = true;
  5804. var propertySchema = s.schema.patternProperties[pattern];
  5805. this.addSchemaValueCompletions(propertySchema, separatorAfter, collector, types);
  5806. }
  5807. }
  5808. }
  5809. if (s.schema.additionalProperties && !propertyMatched) {
  5810. var propertySchema = s.schema.additionalProperties;
  5811. this.addSchemaValueCompletions(propertySchema, separatorAfter, collector, types);
  5812. }
  5813. }
  5814. }
  5815. }
  5816. if (parentKey === '$schema' && !node.parent) {
  5817. this.addDollarSchemaCompletions(separatorAfter, collector);
  5818. }
  5819. if (types['boolean']) {
  5820. this.addBooleanValueCompletion(true, separatorAfter, collector);
  5821. this.addBooleanValueCompletion(false, separatorAfter, collector);
  5822. }
  5823. if (types['null']) {
  5824. this.addNullValueCompletion(separatorAfter, collector);
  5825. }
  5826. }
  5827. };
  5828. JSONCompletion.prototype.getContributedValueCompletions = function (doc, node, offset, document, collector, collectionPromises) {
  5829. if (!node) {
  5830. this.contributions.forEach(function (contribution) {
  5831. var collectPromise = contribution.collectDefaultCompletions(document.uri, collector);
  5832. if (collectPromise) {
  5833. collectionPromises.push(collectPromise);
  5834. }
  5835. });
  5836. }
  5837. else {
  5838. if (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null') {
  5839. node = node.parent;
  5840. }
  5841. if (node && (node.type === 'property') && offset > (node.colonOffset || 0)) {
  5842. var parentKey_4 = node.keyNode.value;
  5843. var valueNode = node.valueNode;
  5844. if ((!valueNode || offset <= (valueNode.offset + valueNode.length)) && node.parent) {
  5845. var location_2 = Parser.getNodePath(node.parent);
  5846. this.contributions.forEach(function (contribution) {
  5847. var collectPromise = contribution.collectValueCompletions(document.uri, location_2, parentKey_4, collector);
  5848. if (collectPromise) {
  5849. collectionPromises.push(collectPromise);
  5850. }
  5851. });
  5852. }
  5853. }
  5854. }
  5855. };
  5856. JSONCompletion.prototype.addSchemaValueCompletions = function (schema, separatorAfter, collector, types) {
  5857. var _this = this;
  5858. if (typeof schema === 'object') {
  5859. this.addEnumValueCompletions(schema, separatorAfter, collector);
  5860. this.addDefaultValueCompletions(schema, separatorAfter, collector);
  5861. this.collectTypes(schema, types);
  5862. if (Array.isArray(schema.allOf)) {
  5863. schema.allOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
  5864. }
  5865. if (Array.isArray(schema.anyOf)) {
  5866. schema.anyOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
  5867. }
  5868. if (Array.isArray(schema.oneOf)) {
  5869. schema.oneOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
  5870. }
  5871. }
  5872. };
  5873. JSONCompletion.prototype.addDefaultValueCompletions = function (schema, separatorAfter, collector, arrayDepth) {
  5874. var _this = this;
  5875. if (arrayDepth === void 0) { arrayDepth = 0; }
  5876. var hasProposals = false;
  5877. if (objects_1.isDefined(schema.default)) {
  5878. var type = schema.type;
  5879. var value = schema.default;
  5880. for (var i = arrayDepth; i > 0; i--) {
  5881. value = [value];
  5882. type = 'array';
  5883. }
  5884. collector.add({
  5885. kind: this.getSuggestionKind(type),
  5886. label: this.getLabelForValue(value),
  5887. insertText: this.getInsertTextForValue(value, separatorAfter),
  5888. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5889. detail: localize('json.suggest.default', 'Default value')
  5890. });
  5891. hasProposals = true;
  5892. }
  5893. if (Array.isArray(schema.examples)) {
  5894. schema.examples.forEach(function (example) {
  5895. var type = schema.type;
  5896. var value = example;
  5897. for (var i = arrayDepth; i > 0; i--) {
  5898. value = [value];
  5899. type = 'array';
  5900. }
  5901. collector.add({
  5902. kind: _this.getSuggestionKind(type),
  5903. label: _this.getLabelForValue(value),
  5904. insertText: _this.getInsertTextForValue(value, separatorAfter),
  5905. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet
  5906. });
  5907. hasProposals = true;
  5908. });
  5909. }
  5910. if (Array.isArray(schema.defaultSnippets)) {
  5911. schema.defaultSnippets.forEach(function (s) {
  5912. var type = schema.type;
  5913. var value = s.body;
  5914. var label = s.label;
  5915. var insertText;
  5916. var filterText;
  5917. if (objects_1.isDefined(value)) {
  5918. var type_1 = schema.type;
  5919. for (var i = arrayDepth; i > 0; i--) {
  5920. value = [value];
  5921. type_1 = 'array';
  5922. }
  5923. insertText = _this.getInsertTextForSnippetValue(value, separatorAfter);
  5924. filterText = _this.getFilterTextForSnippetValue(value);
  5925. label = label || _this.getLabelForSnippetValue(value);
  5926. }
  5927. else if (typeof s.bodyText === 'string') {
  5928. var prefix = '', suffix = '', indent = '';
  5929. for (var i = arrayDepth; i > 0; i--) {
  5930. prefix = prefix + indent + '[\n';
  5931. suffix = suffix + '\n' + indent + ']';
  5932. indent += '\t';
  5933. type = 'array';
  5934. }
  5935. insertText = prefix + indent + s.bodyText.split('\n').join('\n' + indent) + suffix + separatorAfter;
  5936. label = label || insertText,
  5937. filterText = insertText.replace(/[\n]/g, ''); // remove new lines
  5938. }
  5939. else {
  5940. return;
  5941. }
  5942. collector.add({
  5943. kind: _this.getSuggestionKind(type),
  5944. label: label,
  5945. documentation: _this.fromMarkup(s.markdownDescription) || s.description,
  5946. insertText: insertText,
  5947. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5948. filterText: filterText
  5949. });
  5950. hasProposals = true;
  5951. });
  5952. }
  5953. if (!hasProposals && typeof schema.items === 'object' && !Array.isArray(schema.items) && arrayDepth < 5 /* beware of recursion */) {
  5954. this.addDefaultValueCompletions(schema.items, separatorAfter, collector, arrayDepth + 1);
  5955. }
  5956. };
  5957. JSONCompletion.prototype.addEnumValueCompletions = function (schema, separatorAfter, collector) {
  5958. if (objects_1.isDefined(schema.const)) {
  5959. collector.add({
  5960. kind: this.getSuggestionKind(schema.type),
  5961. label: this.getLabelForValue(schema.const),
  5962. insertText: this.getInsertTextForValue(schema.const, separatorAfter),
  5963. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5964. documentation: this.fromMarkup(schema.markdownDescription) || schema.description
  5965. });
  5966. }
  5967. if (Array.isArray(schema.enum)) {
  5968. for (var i = 0, length = schema.enum.length; i < length; i++) {
  5969. var enm = schema.enum[i];
  5970. var documentation = this.fromMarkup(schema.markdownDescription) || schema.description;
  5971. if (schema.markdownEnumDescriptions && i < schema.markdownEnumDescriptions.length && this.doesSupportMarkdown()) {
  5972. documentation = this.fromMarkup(schema.markdownEnumDescriptions[i]);
  5973. }
  5974. else if (schema.enumDescriptions && i < schema.enumDescriptions.length) {
  5975. documentation = schema.enumDescriptions[i];
  5976. }
  5977. collector.add({
  5978. kind: this.getSuggestionKind(schema.type),
  5979. label: this.getLabelForValue(enm),
  5980. insertText: this.getInsertTextForValue(enm, separatorAfter),
  5981. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5982. documentation: documentation
  5983. });
  5984. }
  5985. }
  5986. };
  5987. JSONCompletion.prototype.collectTypes = function (schema, types) {
  5988. if (Array.isArray(schema.enum) || objects_1.isDefined(schema.const)) {
  5989. return;
  5990. }
  5991. var type = schema.type;
  5992. if (Array.isArray(type)) {
  5993. type.forEach(function (t) { return types[t] = true; });
  5994. }
  5995. else if (type) {
  5996. types[type] = true;
  5997. }
  5998. };
  5999. JSONCompletion.prototype.addFillerValueCompletions = function (types, separatorAfter, collector) {
  6000. if (types['object']) {
  6001. collector.add({
  6002. kind: this.getSuggestionKind('object'),
  6003. label: '{}',
  6004. insertText: this.getInsertTextForGuessedValue({}, separatorAfter),
  6005. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  6006. detail: localize('defaults.object', 'New object'),
  6007. documentation: ''
  6008. });
  6009. }
  6010. if (types['array']) {
  6011. collector.add({
  6012. kind: this.getSuggestionKind('array'),
  6013. label: '[]',
  6014. insertText: this.getInsertTextForGuessedValue([], separatorAfter),
  6015. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  6016. detail: localize('defaults.array', 'New array'),
  6017. documentation: ''
  6018. });
  6019. }
  6020. };
  6021. JSONCompletion.prototype.addBooleanValueCompletion = function (value, separatorAfter, collector) {
  6022. collector.add({
  6023. kind: this.getSuggestionKind('boolean'),
  6024. label: value ? 'true' : 'false',
  6025. insertText: this.getInsertTextForValue(value, separatorAfter),
  6026. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  6027. documentation: ''
  6028. });
  6029. };
  6030. JSONCompletion.prototype.addNullValueCompletion = function (separatorAfter, collector) {
  6031. collector.add({
  6032. kind: this.getSuggestionKind('null'),
  6033. label: 'null',
  6034. insertText: 'null' + separatorAfter,
  6035. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  6036. documentation: ''
  6037. });
  6038. };
  6039. JSONCompletion.prototype.addDollarSchemaCompletions = function (separatorAfter, collector) {
  6040. var _this = this;
  6041. var schemaIds = this.schemaService.getRegisteredSchemaIds(function (schema) { return schema === 'http' || schema === 'https'; });
  6042. schemaIds.forEach(function (schemaId) { return collector.add({
  6043. kind: jsonLanguageTypes_1.CompletionItemKind.Module,
  6044. label: _this.getLabelForValue(schemaId),
  6045. filterText: _this.getFilterTextForValue(schemaId),
  6046. insertText: _this.getInsertTextForValue(schemaId, separatorAfter),
  6047. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet, documentation: ''
  6048. }); });
  6049. };
  6050. JSONCompletion.prototype.getLabelForValue = function (value) {
  6051. return JSON.stringify(value);
  6052. };
  6053. JSONCompletion.prototype.getFilterTextForValue = function (value) {
  6054. return JSON.stringify(value);
  6055. };
  6056. JSONCompletion.prototype.getFilterTextForSnippetValue = function (value) {
  6057. return JSON.stringify(value).replace(/\$\{\d+:([^}]+)\}|\$\d+/g, '$1');
  6058. };
  6059. JSONCompletion.prototype.getLabelForSnippetValue = function (value) {
  6060. var label = JSON.stringify(value);
  6061. return label.replace(/\$\{\d+:([^}]+)\}|\$\d+/g, '$1');
  6062. };
  6063. JSONCompletion.prototype.getInsertTextForPlainText = function (text) {
  6064. return text.replace(/[\\\$\}]/g, '\\$&'); // escape $, \ and }
  6065. };
  6066. JSONCompletion.prototype.getInsertTextForValue = function (value, separatorAfter) {
  6067. var text = JSON.stringify(value, null, '\t');
  6068. if (text === '{}') {
  6069. return '{$1}' + separatorAfter;
  6070. }
  6071. else if (text === '[]') {
  6072. return '[$1]' + separatorAfter;
  6073. }
  6074. return this.getInsertTextForPlainText(text + separatorAfter);
  6075. };
  6076. JSONCompletion.prototype.getInsertTextForSnippetValue = function (value, separatorAfter) {
  6077. var replacer = function (value) {
  6078. if (typeof value === 'string') {
  6079. if (value[0] === '^') {
  6080. return value.substr(1);
  6081. }
  6082. }
  6083. return JSON.stringify(value);
  6084. };
  6085. return json_1.stringifyObject(value, '', replacer) + separatorAfter;
  6086. };
  6087. JSONCompletion.prototype.getInsertTextForGuessedValue = function (value, separatorAfter) {
  6088. switch (typeof value) {
  6089. case 'object':
  6090. if (value === null) {
  6091. return '${1:null}' + separatorAfter;
  6092. }
  6093. return this.getInsertTextForValue(value, separatorAfter);
  6094. case 'string':
  6095. var snippetValue = JSON.stringify(value);
  6096. snippetValue = snippetValue.substr(1, snippetValue.length - 2); // remove quotes
  6097. snippetValue = this.getInsertTextForPlainText(snippetValue); // escape \ and }
  6098. return '"${1:' + snippetValue + '}"' + separatorAfter;
  6099. case 'number':
  6100. case 'boolean':
  6101. return '${1:' + JSON.stringify(value) + '}' + separatorAfter;
  6102. }
  6103. return this.getInsertTextForValue(value, separatorAfter);
  6104. };
  6105. JSONCompletion.prototype.getSuggestionKind = function (type) {
  6106. if (Array.isArray(type)) {
  6107. var array = type;
  6108. type = array.length > 0 ? array[0] : undefined;
  6109. }
  6110. if (!type) {
  6111. return jsonLanguageTypes_1.CompletionItemKind.Value;
  6112. }
  6113. switch (type) {
  6114. case 'string': return jsonLanguageTypes_1.CompletionItemKind.Value;
  6115. case 'object': return jsonLanguageTypes_1.CompletionItemKind.Module;
  6116. case 'property': return jsonLanguageTypes_1.CompletionItemKind.Property;
  6117. default: return jsonLanguageTypes_1.CompletionItemKind.Value;
  6118. }
  6119. };
  6120. JSONCompletion.prototype.getLabelTextForMatchingNode = function (node, document) {
  6121. switch (node.type) {
  6122. case 'array':
  6123. return '[]';
  6124. case 'object':
  6125. return '{}';
  6126. default:
  6127. var content = document.getText().substr(node.offset, node.length);
  6128. return content;
  6129. }
  6130. };
  6131. JSONCompletion.prototype.getInsertTextForMatchingNode = function (node, document, separatorAfter) {
  6132. switch (node.type) {
  6133. case 'array':
  6134. return this.getInsertTextForValue([], separatorAfter);
  6135. case 'object':
  6136. return this.getInsertTextForValue({}, separatorAfter);
  6137. default:
  6138. var content = document.getText().substr(node.offset, node.length) + separatorAfter;
  6139. return this.getInsertTextForPlainText(content);
  6140. }
  6141. };
  6142. JSONCompletion.prototype.getInsertTextForProperty = function (key, propertySchema, addValue, separatorAfter) {
  6143. var propertyText = this.getInsertTextForValue(key, '');
  6144. if (!addValue) {
  6145. return propertyText;
  6146. }
  6147. var resultText = propertyText + ': ';
  6148. var value;
  6149. var nValueProposals = 0;
  6150. if (propertySchema) {
  6151. if (Array.isArray(propertySchema.defaultSnippets)) {
  6152. if (propertySchema.defaultSnippets.length === 1) {
  6153. var body = propertySchema.defaultSnippets[0].body;
  6154. if (objects_1.isDefined(body)) {
  6155. value = this.getInsertTextForSnippetValue(body, '');
  6156. }
  6157. }
  6158. nValueProposals += propertySchema.defaultSnippets.length;
  6159. }
  6160. if (propertySchema.enum) {
  6161. if (!value && propertySchema.enum.length === 1) {
  6162. value = this.getInsertTextForGuessedValue(propertySchema.enum[0], '');
  6163. }
  6164. nValueProposals += propertySchema.enum.length;
  6165. }
  6166. if (objects_1.isDefined(propertySchema.default)) {
  6167. if (!value) {
  6168. value = this.getInsertTextForGuessedValue(propertySchema.default, '');
  6169. }
  6170. nValueProposals++;
  6171. }
  6172. if (Array.isArray(propertySchema.examples) && propertySchema.examples.length) {
  6173. if (!value) {
  6174. value = this.getInsertTextForGuessedValue(propertySchema.examples[0], '');
  6175. }
  6176. nValueProposals += propertySchema.examples.length;
  6177. }
  6178. if (nValueProposals === 0) {
  6179. var type = Array.isArray(propertySchema.type) ? propertySchema.type[0] : propertySchema.type;
  6180. if (!type) {
  6181. if (propertySchema.properties) {
  6182. type = 'object';
  6183. }
  6184. else if (propertySchema.items) {
  6185. type = 'array';
  6186. }
  6187. }
  6188. switch (type) {
  6189. case 'boolean':
  6190. value = '$1';
  6191. break;
  6192. case 'string':
  6193. value = '"$1"';
  6194. break;
  6195. case 'object':
  6196. value = '{$1}';
  6197. break;
  6198. case 'array':
  6199. value = '[$1]';
  6200. break;
  6201. case 'number':
  6202. case 'integer':
  6203. value = '${1:0}';
  6204. break;
  6205. case 'null':
  6206. value = '${1:null}';
  6207. break;
  6208. default:
  6209. return propertyText;
  6210. }
  6211. }
  6212. }
  6213. if (!value || nValueProposals > 1) {
  6214. value = '$1';
  6215. }
  6216. return resultText + value + separatorAfter;
  6217. };
  6218. JSONCompletion.prototype.getCurrentWord = function (document, offset) {
  6219. var i = offset - 1;
  6220. var text = document.getText();
  6221. while (i >= 0 && ' \t\n\r\v":{[,]}'.indexOf(text.charAt(i)) === -1) {
  6222. i--;
  6223. }
  6224. return text.substring(i + 1, offset);
  6225. };
  6226. JSONCompletion.prototype.evaluateSeparatorAfter = function (document, offset) {
  6227. var scanner = Json.createScanner(document.getText(), true);
  6228. scanner.setPosition(offset);
  6229. var token = scanner.scan();
  6230. switch (token) {
  6231. case 5 /* CommaToken */:
  6232. case 2 /* CloseBraceToken */:
  6233. case 4 /* CloseBracketToken */:
  6234. case 17 /* EOF */:
  6235. return '';
  6236. default:
  6237. return ',';
  6238. }
  6239. };
  6240. JSONCompletion.prototype.findItemAtOffset = function (node, document, offset) {
  6241. var scanner = Json.createScanner(document.getText(), true);
  6242. var children = node.items;
  6243. for (var i = children.length - 1; i >= 0; i--) {
  6244. var child = children[i];
  6245. if (offset > child.offset + child.length) {
  6246. scanner.setPosition(child.offset + child.length);
  6247. var token = scanner.scan();
  6248. if (token === 5 /* CommaToken */ && offset >= scanner.getTokenOffset() + scanner.getTokenLength()) {
  6249. return i + 1;
  6250. }
  6251. return i;
  6252. }
  6253. else if (offset >= child.offset) {
  6254. return i;
  6255. }
  6256. }
  6257. return 0;
  6258. };
  6259. JSONCompletion.prototype.isInComment = function (document, start, offset) {
  6260. var scanner = Json.createScanner(document.getText(), false);
  6261. scanner.setPosition(start);
  6262. var token = scanner.scan();
  6263. while (token !== 17 /* EOF */ && (scanner.getTokenOffset() + scanner.getTokenLength() < offset)) {
  6264. token = scanner.scan();
  6265. }
  6266. return (token === 12 /* LineCommentTrivia */ || token === 13 /* BlockCommentTrivia */) && scanner.getTokenOffset() <= offset;
  6267. };
  6268. JSONCompletion.prototype.fromMarkup = function (markupString) {
  6269. if (markupString && this.doesSupportMarkdown()) {
  6270. return {
  6271. kind: jsonLanguageTypes_1.MarkupKind.Markdown,
  6272. value: markupString
  6273. };
  6274. }
  6275. return undefined;
  6276. };
  6277. JSONCompletion.prototype.doesSupportMarkdown = function () {
  6278. if (!objects_1.isDefined(this.supportsMarkdown)) {
  6279. var completion = this.clientCapabilities.textDocument && this.clientCapabilities.textDocument.completion;
  6280. this.supportsMarkdown = completion && completion.completionItem && Array.isArray(completion.completionItem.documentationFormat) && completion.completionItem.documentationFormat.indexOf(jsonLanguageTypes_1.MarkupKind.Markdown) !== -1;
  6281. }
  6282. return this.supportsMarkdown;
  6283. };
  6284. JSONCompletion.prototype.doesSupportsCommitCharacters = function () {
  6285. if (!objects_1.isDefined(this.supportsCommitCharacters)) {
  6286. var completion = this.clientCapabilities.textDocument && this.clientCapabilities.textDocument.completion;
  6287. this.supportsCommitCharacters = completion && completion.completionItem && !!completion.completionItem.commitCharactersSupport;
  6288. }
  6289. return this.supportsCommitCharacters;
  6290. };
  6291. return JSONCompletion;
  6292. }());
  6293. exports.JSONCompletion = JSONCompletion;
  6294. });
  6295. /*---------------------------------------------------------------------------------------------
  6296. * Copyright (c) Microsoft Corporation. All rights reserved.
  6297. * Licensed under the MIT License. See License.txt in the project root for license information.
  6298. *--------------------------------------------------------------------------------------------*/
  6299. (function (factory) {
  6300. if (typeof module === "object" && typeof module.exports === "object") {
  6301. var v = factory(require, exports);
  6302. if (v !== undefined) module.exports = v;
  6303. }
  6304. else if (typeof define === "function" && define.amd) {
  6305. define('vscode-json-languageservice/services/jsonHover',["require", "exports", "../parser/jsonParser", "../jsonLanguageTypes"], factory);
  6306. }
  6307. })(function (require, exports) {
  6308. "use strict";
  6309. Object.defineProperty(exports, "__esModule", { value: true });
  6310. exports.JSONHover = void 0;
  6311. var Parser = require("../parser/jsonParser");
  6312. var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
  6313. var JSONHover = /** @class */ (function () {
  6314. function JSONHover(schemaService, contributions, promiseConstructor) {
  6315. if (contributions === void 0) { contributions = []; }
  6316. this.schemaService = schemaService;
  6317. this.contributions = contributions;
  6318. this.promise = promiseConstructor || Promise;
  6319. }
  6320. JSONHover.prototype.doHover = function (document, position, doc) {
  6321. var offset = document.offsetAt(position);
  6322. var node = doc.getNodeFromOffset(offset);
  6323. if (!node || (node.type === 'object' || node.type === 'array') && offset > node.offset + 1 && offset < node.offset + node.length - 1) {
  6324. return this.promise.resolve(null);
  6325. }
  6326. var hoverRangeNode = node;
  6327. // use the property description when hovering over an object key
  6328. if (node.type === 'string') {
  6329. var parent = node.parent;
  6330. if (parent && parent.type === 'property' && parent.keyNode === node) {
  6331. node = parent.valueNode;
  6332. if (!node) {
  6333. return this.promise.resolve(null);
  6334. }
  6335. }
  6336. }
  6337. var hoverRange = jsonLanguageTypes_1.Range.create(document.positionAt(hoverRangeNode.offset), document.positionAt(hoverRangeNode.offset + hoverRangeNode.length));
  6338. var createHover = function (contents) {
  6339. var result = {
  6340. contents: contents,
  6341. range: hoverRange
  6342. };
  6343. return result;
  6344. };
  6345. var location = Parser.getNodePath(node);
  6346. for (var i = this.contributions.length - 1; i >= 0; i--) {
  6347. var contribution = this.contributions[i];
  6348. var promise = contribution.getInfoContribution(document.uri, location);
  6349. if (promise) {
  6350. return promise.then(function (htmlContent) { return createHover(htmlContent); });
  6351. }
  6352. }
  6353. return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
  6354. if (schema && node) {
  6355. var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset);
  6356. var title_1 = undefined;
  6357. var markdownDescription_1 = undefined;
  6358. var markdownEnumValueDescription_1 = undefined, enumValue_1 = undefined;
  6359. matchingSchemas.every(function (s) {
  6360. if (s.node === node && !s.inverted && s.schema) {
  6361. title_1 = title_1 || s.schema.title;
  6362. markdownDescription_1 = markdownDescription_1 || s.schema.markdownDescription || toMarkdown(s.schema.description);
  6363. if (s.schema.enum) {
  6364. var idx = s.schema.enum.indexOf(Parser.getNodeValue(node));
  6365. if (s.schema.markdownEnumDescriptions) {
  6366. markdownEnumValueDescription_1 = s.schema.markdownEnumDescriptions[idx];
  6367. }
  6368. else if (s.schema.enumDescriptions) {
  6369. markdownEnumValueDescription_1 = toMarkdown(s.schema.enumDescriptions[idx]);
  6370. }
  6371. if (markdownEnumValueDescription_1) {
  6372. enumValue_1 = s.schema.enum[idx];
  6373. if (typeof enumValue_1 !== 'string') {
  6374. enumValue_1 = JSON.stringify(enumValue_1);
  6375. }
  6376. }
  6377. }
  6378. }
  6379. return true;
  6380. });
  6381. var result = '';
  6382. if (title_1) {
  6383. result = toMarkdown(title_1);
  6384. }
  6385. if (markdownDescription_1) {
  6386. if (result.length > 0) {
  6387. result += "\n\n";
  6388. }
  6389. result += markdownDescription_1;
  6390. }
  6391. if (markdownEnumValueDescription_1) {
  6392. if (result.length > 0) {
  6393. result += "\n\n";
  6394. }
  6395. result += "`" + toMarkdownCodeBlock(enumValue_1) + "`: " + markdownEnumValueDescription_1;
  6396. }
  6397. return createHover([result]);
  6398. }
  6399. return null;
  6400. });
  6401. };
  6402. return JSONHover;
  6403. }());
  6404. exports.JSONHover = JSONHover;
  6405. function toMarkdown(plain) {
  6406. if (plain) {
  6407. var res = plain.replace(/([^\n\r])(\r?\n)([^\n\r])/gm, '$1\n\n$3'); // single new lines to \n\n (Markdown paragraph)
  6408. return res.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&"); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
  6409. }
  6410. return undefined;
  6411. }
  6412. function toMarkdownCodeBlock(content) {
  6413. // see https://daringfireball.net/projects/markdown/syntax#precode
  6414. if (content.indexOf('`') !== -1) {
  6415. return '`` ' + content + ' ``';
  6416. }
  6417. return content;
  6418. }
  6419. });
  6420. !function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define('vscode-uri/index',[],e);else{var r=e();for(var n in r)("object"==typeof exports?exports:t)[n]=r[n]}}(this,(function(){return(()=>{"use strict";var t={470:t=>{function e(t){if("string"!=typeof t)throw new TypeError("Path must be a string. Received "+JSON.stringify(t))}function r(t,e){for(var r,n="",i=0,o=-1,a=0,h=0;h<=t.length;++h){if(h<t.length)r=t.charCodeAt(h);else{if(47===r)break;r=47}if(47===r){if(o===h-1||1===a);else if(o!==h-1&&2===a){if(n.length<2||2!==i||46!==n.charCodeAt(n.length-1)||46!==n.charCodeAt(n.length-2))if(n.length>2){var s=n.lastIndexOf("/");if(s!==n.length-1){-1===s?(n="",i=0):i=(n=n.slice(0,s)).length-1-n.lastIndexOf("/"),o=h,a=0;continue}}else if(2===n.length||1===n.length){n="",i=0,o=h,a=0;continue}e&&(n.length>0?n+="/..":n="..",i=2)}else n.length>0?n+="/"+t.slice(o+1,h):n=t.slice(o+1,h),i=h-o-1;o=h,a=0}else 46===r&&-1!==a?++a:a=-1}return n}var n={resolve:function(){for(var t,n="",i=!1,o=arguments.length-1;o>=-1&&!i;o--){var a;o>=0?a=arguments[o]:(void 0===t&&(t=process.cwd()),a=t),e(a),0!==a.length&&(n=a+"/"+n,i=47===a.charCodeAt(0))}return n=r(n,!i),i?n.length>0?"/"+n:"/":n.length>0?n:"."},normalize:function(t){if(e(t),0===t.length)return".";var n=47===t.charCodeAt(0),i=47===t.charCodeAt(t.length-1);return 0!==(t=r(t,!n)).length||n||(t="."),t.length>0&&i&&(t+="/"),n?"/"+t:t},isAbsolute:function(t){return e(t),t.length>0&&47===t.charCodeAt(0)},join:function(){if(0===arguments.length)return".";for(var t,r=0;r<arguments.length;++r){var i=arguments[r];e(i),i.length>0&&(void 0===t?t=i:t+="/"+i)}return void 0===t?".":n.normalize(t)},relative:function(t,r){if(e(t),e(r),t===r)return"";if((t=n.resolve(t))===(r=n.resolve(r)))return"";for(var i=1;i<t.length&&47===t.charCodeAt(i);++i);for(var o=t.length,a=o-i,h=1;h<r.length&&47===r.charCodeAt(h);++h);for(var s=r.length-h,f=a<s?a:s,u=-1,c=0;c<=f;++c){if(c===f){if(s>f){if(47===r.charCodeAt(h+c))return r.slice(h+c+1);if(0===c)return r.slice(h+c)}else a>f&&(47===t.charCodeAt(i+c)?u=c:0===c&&(u=0));break}var l=t.charCodeAt(i+c);if(l!==r.charCodeAt(h+c))break;47===l&&(u=c)}var p="";for(c=i+u+1;c<=o;++c)c!==o&&47!==t.charCodeAt(c)||(0===p.length?p+="..":p+="/..");return p.length>0?p+r.slice(h+u):(h+=u,47===r.charCodeAt(h)&&++h,r.slice(h))},_makeLong:function(t){return t},dirname:function(t){if(e(t),0===t.length)return".";for(var r=t.charCodeAt(0),n=47===r,i=-1,o=!0,a=t.length-1;a>=1;--a)if(47===(r=t.charCodeAt(a))){if(!o){i=a;break}}else o=!1;return-1===i?n?"/":".":n&&1===i?"//":t.slice(0,i)},basename:function(t,r){if(void 0!==r&&"string"!=typeof r)throw new TypeError('"ext" argument must be a string');e(t);var n,i=0,o=-1,a=!0;if(void 0!==r&&r.length>0&&r.length<=t.length){if(r.length===t.length&&r===t)return"";var h=r.length-1,s=-1;for(n=t.length-1;n>=0;--n){var f=t.charCodeAt(n);if(47===f){if(!a){i=n+1;break}}else-1===s&&(a=!1,s=n+1),h>=0&&(f===r.charCodeAt(h)?-1==--h&&(o=n):(h=-1,o=s))}return i===o?o=s:-1===o&&(o=t.length),t.slice(i,o)}for(n=t.length-1;n>=0;--n)if(47===t.charCodeAt(n)){if(!a){i=n+1;break}}else-1===o&&(a=!1,o=n+1);return-1===o?"":t.slice(i,o)},extname:function(t){e(t);for(var r=-1,n=0,i=-1,o=!0,a=0,h=t.length-1;h>=0;--h){var s=t.charCodeAt(h);if(47!==s)-1===i&&(o=!1,i=h+1),46===s?-1===r?r=h:1!==a&&(a=1):-1!==r&&(a=-1);else if(!o){n=h+1;break}}return-1===r||-1===i||0===a||1===a&&r===i-1&&r===n+1?"":t.slice(r,i)},format:function(t){if(null===t||"object"!=typeof t)throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof t);return function(t,e){var r=e.dir||e.root,n=e.base||(e.name||"")+(e.ext||"");return r?r===e.root?r+n:r+"/"+n:n}(0,t)},parse:function(t){e(t);var r={root:"",dir:"",base:"",ext:"",name:""};if(0===t.length)return r;var n,i=t.charCodeAt(0),o=47===i;o?(r.root="/",n=1):n=0;for(var a=-1,h=0,s=-1,f=!0,u=t.length-1,c=0;u>=n;--u)if(47!==(i=t.charCodeAt(u)))-1===s&&(f=!1,s=u+1),46===i?-1===a?a=u:1!==c&&(c=1):-1!==a&&(c=-1);else if(!f){h=u+1;break}return-1===a||-1===s||0===c||1===c&&a===s-1&&a===h+1?-1!==s&&(r.base=r.name=0===h&&o?t.slice(1,s):t.slice(h,s)):(0===h&&o?(r.name=t.slice(1,a),r.base=t.slice(1,s)):(r.name=t.slice(h,a),r.base=t.slice(h,s)),r.ext=t.slice(a,s)),h>0?r.dir=t.slice(0,h-1):o&&(r.dir="/"),r},sep:"/",delimiter:":",win32:null,posix:null};n.posix=n,t.exports=n},465:(t,e,r)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Utils=e.URI=void 0;var n=r(796);Object.defineProperty(e,"URI",{enumerable:!0,get:function(){return n.URI}});var i=r(679);Object.defineProperty(e,"Utils",{enumerable:!0,get:function(){return i.Utils}})},674:(t,e)=>{if(Object.defineProperty(e,"__esModule",{value:!0}),e.isWindows=void 0,"object"==typeof process)e.isWindows="win32"===process.platform;else if("object"==typeof navigator){var r=navigator.userAgent;e.isWindows=r.indexOf("Windows")>=0}},796:function(t,e,r){var n,i,o=this&&this.__extends||(n=function(t,e){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])})(t,e)},function(t,e){function r(){this.constructor=t}n(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)});Object.defineProperty(e,"__esModule",{value:!0}),e.uriToFsPath=e.URI=void 0;var a=r(674),h=/^\w[\w\d+.-]*$/,s=/^\//,f=/^\/\//,u="",c="/",l=/^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,p=function(){function t(t,e,r,n,i,o){void 0===o&&(o=!1),"object"==typeof t?(this.scheme=t.scheme||u,this.authority=t.authority||u,this.path=t.path||u,this.query=t.query||u,this.fragment=t.fragment||u):(this.scheme=function(t,e){return t||e?t:"file"}(t,o),this.authority=e||u,this.path=function(t,e){switch(t){case"https":case"http":case"file":e?e[0]!==c&&(e=c+e):e=c}return e}(this.scheme,r||u),this.query=n||u,this.fragment=i||u,function(t,e){if(!t.scheme&&e)throw new Error('[UriError]: Scheme is missing: {scheme: "", authority: "'+t.authority+'", path: "'+t.path+'", query: "'+t.query+'", fragment: "'+t.fragment+'"}');if(t.scheme&&!h.test(t.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(t.path)if(t.authority){if(!s.test(t.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(f.test(t.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,o))}return t.isUri=function(e){return e instanceof t||!!e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString},Object.defineProperty(t.prototype,"fsPath",{get:function(){return b(this,!1)},enumerable:!1,configurable:!0}),t.prototype.with=function(t){if(!t)return this;var e=t.scheme,r=t.authority,n=t.path,i=t.query,o=t.fragment;return void 0===e?e=this.scheme:null===e&&(e=u),void 0===r?r=this.authority:null===r&&(r=u),void 0===n?n=this.path:null===n&&(n=u),void 0===i?i=this.query:null===i&&(i=u),void 0===o?o=this.fragment:null===o&&(o=u),e===this.scheme&&r===this.authority&&n===this.path&&i===this.query&&o===this.fragment?this:new g(e,r,n,i,o)},t.parse=function(t,e){void 0===e&&(e=!1);var r=l.exec(t);return r?new g(r[2]||u,_(r[4]||u),_(r[5]||u),_(r[7]||u),_(r[9]||u),e):new g(u,u,u,u,u)},t.file=function(t){var e=u;if(a.isWindows&&(t=t.replace(/\\/g,c)),t[0]===c&&t[1]===c){var r=t.indexOf(c,2);-1===r?(e=t.substring(2),t=c):(e=t.substring(2,r),t=t.substring(r)||c)}return new g("file",e,t,u,u)},t.from=function(t){return new g(t.scheme,t.authority,t.path,t.query,t.fragment)},t.prototype.toString=function(t){return void 0===t&&(t=!1),C(this,t)},t.prototype.toJSON=function(){return this},t.revive=function(e){if(e){if(e instanceof t)return e;var r=new g(e);return r._formatted=e.external,r._fsPath=e._sep===d?e.fsPath:null,r}return e},t}();e.URI=p;var d=a.isWindows?1:void 0,g=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._formatted=null,e._fsPath=null,e}return o(e,t),Object.defineProperty(e.prototype,"fsPath",{get:function(){return this._fsPath||(this._fsPath=b(this,!1)),this._fsPath},enumerable:!1,configurable:!0}),e.prototype.toString=function(t){return void 0===t&&(t=!1),t?C(this,!0):(this._formatted||(this._formatted=C(this,!1)),this._formatted)},e.prototype.toJSON=function(){var t={$mid:1};return this._fsPath&&(t.fsPath=this._fsPath,t._sep=d),this._formatted&&(t.external=this._formatted),this.path&&(t.path=this.path),this.scheme&&(t.scheme=this.scheme),this.authority&&(t.authority=this.authority),this.query&&(t.query=this.query),this.fragment&&(t.fragment=this.fragment),t},e}(p),v=((i={})[58]="%3A",i[47]="%2F",i[63]="%3F",i[35]="%23",i[91]="%5B",i[93]="%5D",i[64]="%40",i[33]="%21",i[36]="%24",i[38]="%26",i[39]="%27",i[40]="%28",i[41]="%29",i[42]="%2A",i[43]="%2B",i[44]="%2C",i[59]="%3B",i[61]="%3D",i[32]="%20",i);function m(t,e){for(var r=void 0,n=-1,i=0;i<t.length;i++){var o=t.charCodeAt(i);if(o>=97&&o<=122||o>=65&&o<=90||o>=48&&o<=57||45===o||46===o||95===o||126===o||e&&47===o)-1!==n&&(r+=encodeURIComponent(t.substring(n,i)),n=-1),void 0!==r&&(r+=t.charAt(i));else{void 0===r&&(r=t.substr(0,i));var a=v[o];void 0!==a?(-1!==n&&(r+=encodeURIComponent(t.substring(n,i)),n=-1),r+=a):-1===n&&(n=i)}}return-1!==n&&(r+=encodeURIComponent(t.substring(n))),void 0!==r?r:t}function y(t){for(var e=void 0,r=0;r<t.length;r++){var n=t.charCodeAt(r);35===n||63===n?(void 0===e&&(e=t.substr(0,r)),e+=v[n]):void 0!==e&&(e+=t[r])}return void 0!==e?e:t}function b(t,e){var r;return r=t.authority&&t.path.length>1&&"file"===t.scheme?"//"+t.authority+t.path:47===t.path.charCodeAt(0)&&(t.path.charCodeAt(1)>=65&&t.path.charCodeAt(1)<=90||t.path.charCodeAt(1)>=97&&t.path.charCodeAt(1)<=122)&&58===t.path.charCodeAt(2)?e?t.path.substr(1):t.path[1].toLowerCase()+t.path.substr(2):t.path,a.isWindows&&(r=r.replace(/\//g,"\\")),r}function C(t,e){var r=e?y:m,n="",i=t.scheme,o=t.authority,a=t.path,h=t.query,s=t.fragment;if(i&&(n+=i,n+=":"),(o||"file"===i)&&(n+=c,n+=c),o){var f=o.indexOf("@");if(-1!==f){var u=o.substr(0,f);o=o.substr(f+1),-1===(f=u.indexOf(":"))?n+=r(u,!1):(n+=r(u.substr(0,f),!1),n+=":",n+=r(u.substr(f+1),!1)),n+="@"}-1===(f=(o=o.toLowerCase()).indexOf(":"))?n+=r(o,!1):(n+=r(o.substr(0,f),!1),n+=o.substr(f))}if(a){if(a.length>=3&&47===a.charCodeAt(0)&&58===a.charCodeAt(2))(l=a.charCodeAt(1))>=65&&l<=90&&(a="/"+String.fromCharCode(l+32)+":"+a.substr(3));else if(a.length>=2&&58===a.charCodeAt(1)){var l;(l=a.charCodeAt(0))>=65&&l<=90&&(a=String.fromCharCode(l+32)+":"+a.substr(2))}n+=r(a,!0)}return h&&(n+="?",n+=r(h,!1)),s&&(n+="#",n+=e?s:m(s,!1)),n}function A(t){try{return decodeURIComponent(t)}catch(e){return t.length>3?t.substr(0,3)+A(t.substr(3)):t}}e.uriToFsPath=b;var w=/(%[0-9A-Za-z][0-9A-Za-z])+/g;function _(t){return t.match(w)?t.replace(w,(function(t){return A(t)})):t}},679:function(t,e,r){var n=this&&this.__spreadArrays||function(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;var n=Array(t),i=0;for(e=0;e<r;e++)for(var o=arguments[e],a=0,h=o.length;a<h;a++,i++)n[i]=o[a];return n};Object.defineProperty(e,"__esModule",{value:!0}),e.Utils=void 0;var i,o=r(470),a=o.posix||o;(i=e.Utils||(e.Utils={})).joinPath=function(t){for(var e=[],r=1;r<arguments.length;r++)e[r-1]=arguments[r];return t.with({path:a.join.apply(a,n([t.path],e))})},i.resolvePath=function(t){for(var e=[],r=1;r<arguments.length;r++)e[r-1]=arguments[r];var i=t.path||"/";return t.with({path:a.resolve.apply(a,n([i],e))})},i.dirname=function(t){var e=a.dirname(t.path);return 1===e.length&&46===e.charCodeAt(0)?t:t.with({path:e})},i.basename=function(t){return a.basename(t.path)},i.extname=function(t){return a.extname(t.path)}}},e={};return function r(n){if(e[n])return e[n].exports;var i=e[n]={exports:{}};return t[n].call(i.exports,i,i.exports,r),i.exports}(465)})()}));
  6421. //# sourceMappingURL=index.js.map;
  6422. define('vscode-uri', ['vscode-uri/index'], function (main) { return main; });
  6423. (function (factory) {
  6424. if (typeof module === "object" && typeof module.exports === "object") {
  6425. var v = factory(require, exports);
  6426. if (v !== undefined) module.exports = v;
  6427. }
  6428. else if (typeof define === "function" && define.amd) {
  6429. define('vscode-json-languageservice/utils/glob',["require", "exports"], factory);
  6430. }
  6431. })(function (require, exports) {
  6432. "use strict";
  6433. Object.defineProperty(exports, "__esModule", { value: true });
  6434. exports.createRegex = void 0;
  6435. /*---------------------------------------------------------------------------------------------
  6436. * Copyright (c) Microsoft Corporation. All rights reserved.
  6437. * Copyright (c) 2013, Nick Fitzgerald
  6438. * Licensed under the MIT License. See LICENCE.md in the project root for license information.
  6439. *--------------------------------------------------------------------------------------------*/
  6440. function createRegex(glob, opts) {
  6441. if (typeof glob !== 'string') {
  6442. throw new TypeError('Expected a string');
  6443. }
  6444. var str = String(glob);
  6445. // The regexp we are building, as a string.
  6446. var reStr = "";
  6447. // Whether we are matching so called "extended" globs (like bash) and should
  6448. // support single character matching, matching ranges of characters, group
  6449. // matching, etc.
  6450. var extended = opts ? !!opts.extended : false;
  6451. // When globstar is _false_ (default), '/foo/*' is translated a regexp like
  6452. // '^\/foo\/.*$' which will match any string beginning with '/foo/'
  6453. // When globstar is _true_, '/foo/*' is translated to regexp like
  6454. // '^\/foo\/[^/]*$' which will match any string beginning with '/foo/' BUT
  6455. // which does not have a '/' to the right of it.
  6456. // E.g. with '/foo/*' these will match: '/foo/bar', '/foo/bar.txt' but
  6457. // these will not '/foo/bar/baz', '/foo/bar/baz.txt'
  6458. // Lastely, when globstar is _true_, '/foo/**' is equivelant to '/foo/*' when
  6459. // globstar is _false_
  6460. var globstar = opts ? !!opts.globstar : false;
  6461. // If we are doing extended matching, this boolean is true when we are inside
  6462. // a group (eg {*.html,*.js}), and false otherwise.
  6463. var inGroup = false;
  6464. // RegExp flags (eg "i" ) to pass in to RegExp constructor.
  6465. var flags = opts && typeof (opts.flags) === "string" ? opts.flags : "";
  6466. var c;
  6467. for (var i = 0, len = str.length; i < len; i++) {
  6468. c = str[i];
  6469. switch (c) {
  6470. case "/":
  6471. case "$":
  6472. case "^":
  6473. case "+":
  6474. case ".":
  6475. case "(":
  6476. case ")":
  6477. case "=":
  6478. case "!":
  6479. case "|":
  6480. reStr += "\\" + c;
  6481. break;
  6482. case "?":
  6483. if (extended) {
  6484. reStr += ".";
  6485. break;
  6486. }
  6487. case "[":
  6488. case "]":
  6489. if (extended) {
  6490. reStr += c;
  6491. break;
  6492. }
  6493. case "{":
  6494. if (extended) {
  6495. inGroup = true;
  6496. reStr += "(";
  6497. break;
  6498. }
  6499. case "}":
  6500. if (extended) {
  6501. inGroup = false;
  6502. reStr += ")";
  6503. break;
  6504. }
  6505. case ",":
  6506. if (inGroup) {
  6507. reStr += "|";
  6508. break;
  6509. }
  6510. reStr += "\\" + c;
  6511. break;
  6512. case "*":
  6513. // Move over all consecutive "*"'s.
  6514. // Also store the previous and next characters
  6515. var prevChar = str[i - 1];
  6516. var starCount = 1;
  6517. while (str[i + 1] === "*") {
  6518. starCount++;
  6519. i++;
  6520. }
  6521. var nextChar = str[i + 1];
  6522. if (!globstar) {
  6523. // globstar is disabled, so treat any number of "*" as one
  6524. reStr += ".*";
  6525. }
  6526. else {
  6527. // globstar is enabled, so determine if this is a globstar segment
  6528. var isGlobstar = starCount > 1 // multiple "*"'s
  6529. && (prevChar === "/" || prevChar === undefined || prevChar === '{' || prevChar === ',') // from the start of the segment
  6530. && (nextChar === "/" || nextChar === undefined || nextChar === ',' || nextChar === '}'); // to the end of the segment
  6531. if (isGlobstar) {
  6532. if (nextChar === "/") {
  6533. i++; // move over the "/"
  6534. }
  6535. else if (prevChar === '/' && reStr.endsWith('\\/')) {
  6536. reStr = reStr.substr(0, reStr.length - 2);
  6537. }
  6538. // it's a globstar, so match zero or more path segments
  6539. reStr += "((?:[^/]*(?:\/|$))*)";
  6540. }
  6541. else {
  6542. // it's not a globstar, so only match one path segment
  6543. reStr += "([^/]*)";
  6544. }
  6545. }
  6546. break;
  6547. default:
  6548. reStr += c;
  6549. }
  6550. }
  6551. // When regexp 'g' flag is specified don't
  6552. // constrain the regular expression with ^ & $
  6553. if (!flags || !~flags.indexOf('g')) {
  6554. reStr = "^" + reStr + "$";
  6555. }
  6556. return new RegExp(reStr, flags);
  6557. }
  6558. exports.createRegex = createRegex;
  6559. ;
  6560. });
  6561. /*---------------------------------------------------------------------------------------------
  6562. * Copyright (c) Microsoft Corporation. All rights reserved.
  6563. * Licensed under the MIT License. See License.txt in the project root for license information.
  6564. *--------------------------------------------------------------------------------------------*/
  6565. (function (factory) {
  6566. if (typeof module === "object" && typeof module.exports === "object") {
  6567. var v = factory(require, exports);
  6568. if (v !== undefined) module.exports = v;
  6569. }
  6570. else if (typeof define === "function" && define.amd) {
  6571. define('vscode-json-languageservice/services/jsonSchemaService',["require", "exports", "jsonc-parser", "vscode-uri", "../utils/strings", "../parser/jsonParser", "vscode-nls", "../utils/glob"], factory);
  6572. }
  6573. })(function (require, exports) {
  6574. "use strict";
  6575. Object.defineProperty(exports, "__esModule", { value: true });
  6576. exports.JSONSchemaService = exports.ResolvedSchema = exports.UnresolvedSchema = void 0;
  6577. var Json = require("jsonc-parser");
  6578. var vscode_uri_1 = require("vscode-uri");
  6579. var Strings = require("../utils/strings");
  6580. var Parser = require("../parser/jsonParser");
  6581. var nls = require("vscode-nls");
  6582. var glob_1 = require("../utils/glob");
  6583. var localize = nls.loadMessageBundle();
  6584. var BANG = '!';
  6585. var PATH_SEP = '/';
  6586. var FilePatternAssociation = /** @class */ (function () {
  6587. function FilePatternAssociation(pattern, uris) {
  6588. this.globWrappers = [];
  6589. try {
  6590. for (var _i = 0, pattern_1 = pattern; _i < pattern_1.length; _i++) {
  6591. var patternString = pattern_1[_i];
  6592. var include = patternString[0] !== BANG;
  6593. if (!include) {
  6594. patternString = patternString.substring(1);
  6595. }
  6596. if (patternString.length > 0) {
  6597. if (patternString[0] === PATH_SEP) {
  6598. patternString = patternString.substring(1);
  6599. }
  6600. this.globWrappers.push({
  6601. regexp: glob_1.createRegex('**/' + patternString, { extended: true, globstar: true }),
  6602. include: include,
  6603. });
  6604. }
  6605. }
  6606. ;
  6607. this.uris = uris;
  6608. }
  6609. catch (e) {
  6610. this.globWrappers.length = 0;
  6611. this.uris = [];
  6612. }
  6613. }
  6614. FilePatternAssociation.prototype.matchesPattern = function (fileName) {
  6615. var match = false;
  6616. for (var _i = 0, _a = this.globWrappers; _i < _a.length; _i++) {
  6617. var _b = _a[_i], regexp = _b.regexp, include = _b.include;
  6618. if (regexp.test(fileName)) {
  6619. match = include;
  6620. }
  6621. }
  6622. return match;
  6623. };
  6624. FilePatternAssociation.prototype.getURIs = function () {
  6625. return this.uris;
  6626. };
  6627. return FilePatternAssociation;
  6628. }());
  6629. var SchemaHandle = /** @class */ (function () {
  6630. function SchemaHandle(service, url, unresolvedSchemaContent) {
  6631. this.service = service;
  6632. this.url = url;
  6633. this.dependencies = {};
  6634. if (unresolvedSchemaContent) {
  6635. this.unresolvedSchema = this.service.promise.resolve(new UnresolvedSchema(unresolvedSchemaContent));
  6636. }
  6637. }
  6638. SchemaHandle.prototype.getUnresolvedSchema = function () {
  6639. if (!this.unresolvedSchema) {
  6640. this.unresolvedSchema = this.service.loadSchema(this.url);
  6641. }
  6642. return this.unresolvedSchema;
  6643. };
  6644. SchemaHandle.prototype.getResolvedSchema = function () {
  6645. var _this = this;
  6646. if (!this.resolvedSchema) {
  6647. this.resolvedSchema = this.getUnresolvedSchema().then(function (unresolved) {
  6648. return _this.service.resolveSchemaContent(unresolved, _this.url, _this.dependencies);
  6649. });
  6650. }
  6651. return this.resolvedSchema;
  6652. };
  6653. SchemaHandle.prototype.clearSchema = function () {
  6654. this.resolvedSchema = undefined;
  6655. this.unresolvedSchema = undefined;
  6656. this.dependencies = {};
  6657. };
  6658. return SchemaHandle;
  6659. }());
  6660. var UnresolvedSchema = /** @class */ (function () {
  6661. function UnresolvedSchema(schema, errors) {
  6662. if (errors === void 0) { errors = []; }
  6663. this.schema = schema;
  6664. this.errors = errors;
  6665. }
  6666. return UnresolvedSchema;
  6667. }());
  6668. exports.UnresolvedSchema = UnresolvedSchema;
  6669. var ResolvedSchema = /** @class */ (function () {
  6670. function ResolvedSchema(schema, errors) {
  6671. if (errors === void 0) { errors = []; }
  6672. this.schema = schema;
  6673. this.errors = errors;
  6674. }
  6675. ResolvedSchema.prototype.getSection = function (path) {
  6676. var schemaRef = this.getSectionRecursive(path, this.schema);
  6677. if (schemaRef) {
  6678. return Parser.asSchema(schemaRef);
  6679. }
  6680. return undefined;
  6681. };
  6682. ResolvedSchema.prototype.getSectionRecursive = function (path, schema) {
  6683. if (!schema || typeof schema === 'boolean' || path.length === 0) {
  6684. return schema;
  6685. }
  6686. var next = path.shift();
  6687. if (schema.properties && typeof schema.properties[next]) {
  6688. return this.getSectionRecursive(path, schema.properties[next]);
  6689. }
  6690. else if (schema.patternProperties) {
  6691. for (var _i = 0, _a = Object.keys(schema.patternProperties); _i < _a.length; _i++) {
  6692. var pattern = _a[_i];
  6693. var regex = Strings.extendedRegExp(pattern);
  6694. if (regex.test(next)) {
  6695. return this.getSectionRecursive(path, schema.patternProperties[pattern]);
  6696. }
  6697. }
  6698. }
  6699. else if (typeof schema.additionalProperties === 'object') {
  6700. return this.getSectionRecursive(path, schema.additionalProperties);
  6701. }
  6702. else if (next.match('[0-9]+')) {
  6703. if (Array.isArray(schema.items)) {
  6704. var index = parseInt(next, 10);
  6705. if (!isNaN(index) && schema.items[index]) {
  6706. return this.getSectionRecursive(path, schema.items[index]);
  6707. }
  6708. }
  6709. else if (schema.items) {
  6710. return this.getSectionRecursive(path, schema.items);
  6711. }
  6712. }
  6713. return undefined;
  6714. };
  6715. return ResolvedSchema;
  6716. }());
  6717. exports.ResolvedSchema = ResolvedSchema;
  6718. var JSONSchemaService = /** @class */ (function () {
  6719. function JSONSchemaService(requestService, contextService, promiseConstructor) {
  6720. this.contextService = contextService;
  6721. this.requestService = requestService;
  6722. this.promiseConstructor = promiseConstructor || Promise;
  6723. this.callOnDispose = [];
  6724. this.contributionSchemas = {};
  6725. this.contributionAssociations = [];
  6726. this.schemasById = {};
  6727. this.filePatternAssociations = [];
  6728. this.registeredSchemasIds = {};
  6729. }
  6730. JSONSchemaService.prototype.getRegisteredSchemaIds = function (filter) {
  6731. return Object.keys(this.registeredSchemasIds).filter(function (id) {
  6732. var scheme = vscode_uri_1.URI.parse(id).scheme;
  6733. return scheme !== 'schemaservice' && (!filter || filter(scheme));
  6734. });
  6735. };
  6736. Object.defineProperty(JSONSchemaService.prototype, "promise", {
  6737. get: function () {
  6738. return this.promiseConstructor;
  6739. },
  6740. enumerable: false,
  6741. configurable: true
  6742. });
  6743. JSONSchemaService.prototype.dispose = function () {
  6744. while (this.callOnDispose.length > 0) {
  6745. this.callOnDispose.pop()();
  6746. }
  6747. };
  6748. JSONSchemaService.prototype.onResourceChange = function (uri) {
  6749. var _this = this;
  6750. var hasChanges = false;
  6751. uri = normalizeId(uri);
  6752. var toWalk = [uri];
  6753. var all = Object.keys(this.schemasById).map(function (key) { return _this.schemasById[key]; });
  6754. while (toWalk.length) {
  6755. var curr = toWalk.pop();
  6756. for (var i = 0; i < all.length; i++) {
  6757. var handle = all[i];
  6758. if (handle && (handle.url === curr || handle.dependencies[curr])) {
  6759. if (handle.url !== curr) {
  6760. toWalk.push(handle.url);
  6761. }
  6762. handle.clearSchema();
  6763. all[i] = undefined;
  6764. hasChanges = true;
  6765. }
  6766. }
  6767. }
  6768. return hasChanges;
  6769. };
  6770. JSONSchemaService.prototype.setSchemaContributions = function (schemaContributions) {
  6771. if (schemaContributions.schemas) {
  6772. var schemas = schemaContributions.schemas;
  6773. for (var id in schemas) {
  6774. var normalizedId = normalizeId(id);
  6775. this.contributionSchemas[normalizedId] = this.addSchemaHandle(normalizedId, schemas[id]);
  6776. }
  6777. }
  6778. if (Array.isArray(schemaContributions.schemaAssociations)) {
  6779. var schemaAssociations = schemaContributions.schemaAssociations;
  6780. for (var _i = 0, schemaAssociations_1 = schemaAssociations; _i < schemaAssociations_1.length; _i++) {
  6781. var schemaAssociation = schemaAssociations_1[_i];
  6782. var uris = schemaAssociation.uris.map(normalizeId);
  6783. var association = this.addFilePatternAssociation(schemaAssociation.pattern, uris);
  6784. this.contributionAssociations.push(association);
  6785. }
  6786. }
  6787. };
  6788. JSONSchemaService.prototype.addSchemaHandle = function (id, unresolvedSchemaContent) {
  6789. var schemaHandle = new SchemaHandle(this, id, unresolvedSchemaContent);
  6790. this.schemasById[id] = schemaHandle;
  6791. return schemaHandle;
  6792. };
  6793. JSONSchemaService.prototype.getOrAddSchemaHandle = function (id, unresolvedSchemaContent) {
  6794. return this.schemasById[id] || this.addSchemaHandle(id, unresolvedSchemaContent);
  6795. };
  6796. JSONSchemaService.prototype.addFilePatternAssociation = function (pattern, uris) {
  6797. var fpa = new FilePatternAssociation(pattern, uris);
  6798. this.filePatternAssociations.push(fpa);
  6799. return fpa;
  6800. };
  6801. JSONSchemaService.prototype.registerExternalSchema = function (uri, filePatterns, unresolvedSchemaContent) {
  6802. var id = normalizeId(uri);
  6803. this.registeredSchemasIds[id] = true;
  6804. this.cachedSchemaForResource = undefined;
  6805. if (filePatterns) {
  6806. this.addFilePatternAssociation(filePatterns, [uri]);
  6807. }
  6808. return unresolvedSchemaContent ? this.addSchemaHandle(id, unresolvedSchemaContent) : this.getOrAddSchemaHandle(id);
  6809. };
  6810. JSONSchemaService.prototype.clearExternalSchemas = function () {
  6811. this.schemasById = {};
  6812. this.filePatternAssociations = [];
  6813. this.registeredSchemasIds = {};
  6814. this.cachedSchemaForResource = undefined;
  6815. for (var id in this.contributionSchemas) {
  6816. this.schemasById[id] = this.contributionSchemas[id];
  6817. this.registeredSchemasIds[id] = true;
  6818. }
  6819. for (var _i = 0, _a = this.contributionAssociations; _i < _a.length; _i++) {
  6820. var contributionAssociation = _a[_i];
  6821. this.filePatternAssociations.push(contributionAssociation);
  6822. }
  6823. };
  6824. JSONSchemaService.prototype.getResolvedSchema = function (schemaId) {
  6825. var id = normalizeId(schemaId);
  6826. var schemaHandle = this.schemasById[id];
  6827. if (schemaHandle) {
  6828. return schemaHandle.getResolvedSchema();
  6829. }
  6830. return this.promise.resolve(undefined);
  6831. };
  6832. JSONSchemaService.prototype.loadSchema = function (url) {
  6833. if (!this.requestService) {
  6834. var errorMessage = localize('json.schema.norequestservice', 'Unable to load schema from \'{0}\'. No schema request service available', toDisplayString(url));
  6835. return this.promise.resolve(new UnresolvedSchema({}, [errorMessage]));
  6836. }
  6837. return this.requestService(url).then(function (content) {
  6838. if (!content) {
  6839. var errorMessage = localize('json.schema.nocontent', 'Unable to load schema from \'{0}\': No content.', toDisplayString(url));
  6840. return new UnresolvedSchema({}, [errorMessage]);
  6841. }
  6842. var schemaContent = {};
  6843. var jsonErrors = [];
  6844. schemaContent = Json.parse(content, jsonErrors);
  6845. var errors = jsonErrors.length ? [localize('json.schema.invalidFormat', 'Unable to parse content from \'{0}\': Parse error at offset {1}.', toDisplayString(url), jsonErrors[0].offset)] : [];
  6846. return new UnresolvedSchema(schemaContent, errors);
  6847. }, function (error) {
  6848. var errorMessage = error.toString();
  6849. var errorSplit = error.toString().split('Error: ');
  6850. if (errorSplit.length > 1) {
  6851. // more concise error message, URL and context are attached by caller anyways
  6852. errorMessage = errorSplit[1];
  6853. }
  6854. if (Strings.endsWith(errorMessage, '.')) {
  6855. errorMessage = errorMessage.substr(0, errorMessage.length - 1);
  6856. }
  6857. return new UnresolvedSchema({}, [localize('json.schema.nocontent', 'Unable to load schema from \'{0}\': {1}.', toDisplayString(url), errorMessage)]);
  6858. });
  6859. };
  6860. JSONSchemaService.prototype.resolveSchemaContent = function (schemaToResolve, schemaURL, dependencies) {
  6861. var _this = this;
  6862. var resolveErrors = schemaToResolve.errors.slice(0);
  6863. var schema = schemaToResolve.schema;
  6864. if (schema.$schema) {
  6865. var id = normalizeId(schema.$schema);
  6866. if (id === 'http://json-schema.org/draft-03/schema') {
  6867. return this.promise.resolve(new ResolvedSchema({}, [localize('json.schema.draft03.notsupported', "Draft-03 schemas are not supported.")]));
  6868. }
  6869. else if (id === 'https://json-schema.org/draft/2019-09/schema') {
  6870. resolveErrors.push(localize('json.schema.draft201909.notsupported', "Draft 2019-09 schemas are not yet fully supported."));
  6871. }
  6872. }
  6873. var contextService = this.contextService;
  6874. var findSection = function (schema, path) {
  6875. if (!path) {
  6876. return schema;
  6877. }
  6878. var current = schema;
  6879. if (path[0] === '/') {
  6880. path = path.substr(1);
  6881. }
  6882. path.split('/').some(function (part) {
  6883. part = part.replace(/~1/g, '/').replace(/~0/g, '~');
  6884. current = current[part];
  6885. return !current;
  6886. });
  6887. return current;
  6888. };
  6889. var merge = function (target, sourceRoot, sourceURI, refSegment) {
  6890. var path = refSegment ? decodeURIComponent(refSegment) : undefined;
  6891. var section = findSection(sourceRoot, path);
  6892. if (section) {
  6893. for (var key in section) {
  6894. if (section.hasOwnProperty(key) && !target.hasOwnProperty(key)) {
  6895. target[key] = section[key];
  6896. }
  6897. }
  6898. }
  6899. else {
  6900. resolveErrors.push(localize('json.schema.invalidref', '$ref \'{0}\' in \'{1}\' can not be resolved.', path, sourceURI));
  6901. }
  6902. };
  6903. var resolveExternalLink = function (node, uri, refSegment, parentSchemaURL, parentSchemaDependencies) {
  6904. if (contextService && !/^[A-Za-z][A-Za-z0-9+\-.+]*:\/\/.*/.test(uri)) {
  6905. uri = contextService.resolveRelativePath(uri, parentSchemaURL);
  6906. }
  6907. uri = normalizeId(uri);
  6908. var referencedHandle = _this.getOrAddSchemaHandle(uri);
  6909. return referencedHandle.getUnresolvedSchema().then(function (unresolvedSchema) {
  6910. parentSchemaDependencies[uri] = true;
  6911. if (unresolvedSchema.errors.length) {
  6912. var loc = refSegment ? uri + '#' + refSegment : uri;
  6913. resolveErrors.push(localize('json.schema.problemloadingref', 'Problems loading reference \'{0}\': {1}', loc, unresolvedSchema.errors[0]));
  6914. }
  6915. merge(node, unresolvedSchema.schema, uri, refSegment);
  6916. return resolveRefs(node, unresolvedSchema.schema, uri, referencedHandle.dependencies);
  6917. });
  6918. };
  6919. var resolveRefs = function (node, parentSchema, parentSchemaURL, parentSchemaDependencies) {
  6920. if (!node || typeof node !== 'object') {
  6921. return Promise.resolve(null);
  6922. }
  6923. var toWalk = [node];
  6924. var seen = [];
  6925. var openPromises = [];
  6926. var collectEntries = function () {
  6927. var entries = [];
  6928. for (var _i = 0; _i < arguments.length; _i++) {
  6929. entries[_i] = arguments[_i];
  6930. }
  6931. for (var _a = 0, entries_1 = entries; _a < entries_1.length; _a++) {
  6932. var entry = entries_1[_a];
  6933. if (typeof entry === 'object') {
  6934. toWalk.push(entry);
  6935. }
  6936. }
  6937. };
  6938. var collectMapEntries = function () {
  6939. var maps = [];
  6940. for (var _i = 0; _i < arguments.length; _i++) {
  6941. maps[_i] = arguments[_i];
  6942. }
  6943. for (var _a = 0, maps_1 = maps; _a < maps_1.length; _a++) {
  6944. var map = maps_1[_a];
  6945. if (typeof map === 'object') {
  6946. for (var k in map) {
  6947. var key = k;
  6948. var entry = map[key];
  6949. if (typeof entry === 'object') {
  6950. toWalk.push(entry);
  6951. }
  6952. }
  6953. }
  6954. }
  6955. };
  6956. var collectArrayEntries = function () {
  6957. var arrays = [];
  6958. for (var _i = 0; _i < arguments.length; _i++) {
  6959. arrays[_i] = arguments[_i];
  6960. }
  6961. for (var _a = 0, arrays_1 = arrays; _a < arrays_1.length; _a++) {
  6962. var array = arrays_1[_a];
  6963. if (Array.isArray(array)) {
  6964. for (var _b = 0, array_1 = array; _b < array_1.length; _b++) {
  6965. var entry = array_1[_b];
  6966. if (typeof entry === 'object') {
  6967. toWalk.push(entry);
  6968. }
  6969. }
  6970. }
  6971. }
  6972. };
  6973. var handleRef = function (next) {
  6974. var seenRefs = [];
  6975. while (next.$ref) {
  6976. var ref = next.$ref;
  6977. var segments = ref.split('#', 2);
  6978. delete next.$ref;
  6979. if (segments[0].length > 0) {
  6980. openPromises.push(resolveExternalLink(next, segments[0], segments[1], parentSchemaURL, parentSchemaDependencies));
  6981. return;
  6982. }
  6983. else {
  6984. if (seenRefs.indexOf(ref) === -1) {
  6985. merge(next, parentSchema, parentSchemaURL, segments[1]); // can set next.$ref again, use seenRefs to avoid circle
  6986. seenRefs.push(ref);
  6987. }
  6988. }
  6989. }
  6990. collectEntries(next.items, next.additionalItems, next.additionalProperties, next.not, next.contains, next.propertyNames, next.if, next.then, next.else);
  6991. collectMapEntries(next.definitions, next.properties, next.patternProperties, next.dependencies);
  6992. collectArrayEntries(next.anyOf, next.allOf, next.oneOf, next.items);
  6993. };
  6994. while (toWalk.length) {
  6995. var next = toWalk.pop();
  6996. if (seen.indexOf(next) >= 0) {
  6997. continue;
  6998. }
  6999. seen.push(next);
  7000. handleRef(next);
  7001. }
  7002. return _this.promise.all(openPromises);
  7003. };
  7004. return resolveRefs(schema, schema, schemaURL, dependencies).then(function (_) { return new ResolvedSchema(schema, resolveErrors); });
  7005. };
  7006. JSONSchemaService.prototype.getSchemaForResource = function (resource, document) {
  7007. // first use $schema if present
  7008. if (document && document.root && document.root.type === 'object') {
  7009. var schemaProperties = document.root.properties.filter(function (p) { return (p.keyNode.value === '$schema') && p.valueNode && p.valueNode.type === 'string'; });
  7010. if (schemaProperties.length > 0) {
  7011. var valueNode = schemaProperties[0].valueNode;
  7012. if (valueNode && valueNode.type === 'string') {
  7013. var schemeId = Parser.getNodeValue(valueNode);
  7014. if (schemeId && Strings.startsWith(schemeId, '.') && this.contextService) {
  7015. schemeId = this.contextService.resolveRelativePath(schemeId, resource);
  7016. }
  7017. if (schemeId) {
  7018. var id = normalizeId(schemeId);
  7019. return this.getOrAddSchemaHandle(id).getResolvedSchema();
  7020. }
  7021. }
  7022. }
  7023. }
  7024. if (this.cachedSchemaForResource && this.cachedSchemaForResource.resource === resource) {
  7025. return this.cachedSchemaForResource.resolvedSchema;
  7026. }
  7027. var seen = Object.create(null);
  7028. var schemas = [];
  7029. var normalizedResource = normalizeResourceForMatching(resource);
  7030. for (var _i = 0, _a = this.filePatternAssociations; _i < _a.length; _i++) {
  7031. var entry = _a[_i];
  7032. if (entry.matchesPattern(normalizedResource)) {
  7033. for (var _b = 0, _c = entry.getURIs(); _b < _c.length; _b++) {
  7034. var schemaId = _c[_b];
  7035. if (!seen[schemaId]) {
  7036. schemas.push(schemaId);
  7037. seen[schemaId] = true;
  7038. }
  7039. }
  7040. }
  7041. }
  7042. var resolvedSchema = schemas.length > 0 ? this.createCombinedSchema(resource, schemas).getResolvedSchema() : this.promise.resolve(undefined);
  7043. this.cachedSchemaForResource = { resource: resource, resolvedSchema: resolvedSchema };
  7044. return resolvedSchema;
  7045. };
  7046. JSONSchemaService.prototype.createCombinedSchema = function (resource, schemaIds) {
  7047. if (schemaIds.length === 1) {
  7048. return this.getOrAddSchemaHandle(schemaIds[0]);
  7049. }
  7050. else {
  7051. var combinedSchemaId = 'schemaservice://combinedSchema/' + encodeURIComponent(resource);
  7052. var combinedSchema = {
  7053. allOf: schemaIds.map(function (schemaId) { return ({ $ref: schemaId }); })
  7054. };
  7055. return this.addSchemaHandle(combinedSchemaId, combinedSchema);
  7056. }
  7057. };
  7058. JSONSchemaService.prototype.getMatchingSchemas = function (document, jsonDocument, schema) {
  7059. if (schema) {
  7060. var id = schema.id || ('schemaservice://untitled/matchingSchemas/' + idCounter++);
  7061. return this.resolveSchemaContent(new UnresolvedSchema(schema), id, {}).then(function (resolvedSchema) {
  7062. return jsonDocument.getMatchingSchemas(resolvedSchema.schema).filter(function (s) { return !s.inverted; });
  7063. });
  7064. }
  7065. return this.getSchemaForResource(document.uri, jsonDocument).then(function (schema) {
  7066. if (schema) {
  7067. return jsonDocument.getMatchingSchemas(schema.schema).filter(function (s) { return !s.inverted; });
  7068. }
  7069. return [];
  7070. });
  7071. };
  7072. return JSONSchemaService;
  7073. }());
  7074. exports.JSONSchemaService = JSONSchemaService;
  7075. var idCounter = 0;
  7076. function normalizeId(id) {
  7077. // remove trailing '#', normalize drive capitalization
  7078. try {
  7079. return vscode_uri_1.URI.parse(id).toString();
  7080. }
  7081. catch (e) {
  7082. return id;
  7083. }
  7084. }
  7085. function normalizeResourceForMatching(resource) {
  7086. // remove queries and fragments, normalize drive capitalization
  7087. try {
  7088. return vscode_uri_1.URI.parse(resource).with({ fragment: null, query: null }).toString();
  7089. }
  7090. catch (e) {
  7091. return resource;
  7092. }
  7093. }
  7094. function toDisplayString(url) {
  7095. try {
  7096. var uri = vscode_uri_1.URI.parse(url);
  7097. if (uri.scheme === 'file') {
  7098. return uri.fsPath;
  7099. }
  7100. }
  7101. catch (e) {
  7102. // ignore
  7103. }
  7104. return url;
  7105. }
  7106. });
  7107. /*---------------------------------------------------------------------------------------------
  7108. * Copyright (c) Microsoft Corporation. All rights reserved.
  7109. * Licensed under the MIT License. See License.txt in the project root for license information.
  7110. *--------------------------------------------------------------------------------------------*/
  7111. (function (factory) {
  7112. if (typeof module === "object" && typeof module.exports === "object") {
  7113. var v = factory(require, exports);
  7114. if (v !== undefined) module.exports = v;
  7115. }
  7116. else if (typeof define === "function" && define.amd) {
  7117. define('vscode-json-languageservice/services/jsonValidation',["require", "exports", "./jsonSchemaService", "../jsonLanguageTypes", "vscode-nls", "../utils/objects"], factory);
  7118. }
  7119. })(function (require, exports) {
  7120. "use strict";
  7121. Object.defineProperty(exports, "__esModule", { value: true });
  7122. exports.JSONValidation = void 0;
  7123. var jsonSchemaService_1 = require("./jsonSchemaService");
  7124. var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
  7125. var nls = require("vscode-nls");
  7126. var objects_1 = require("../utils/objects");
  7127. var localize = nls.loadMessageBundle();
  7128. var JSONValidation = /** @class */ (function () {
  7129. function JSONValidation(jsonSchemaService, promiseConstructor) {
  7130. this.jsonSchemaService = jsonSchemaService;
  7131. this.promise = promiseConstructor;
  7132. this.validationEnabled = true;
  7133. }
  7134. JSONValidation.prototype.configure = function (raw) {
  7135. if (raw) {
  7136. this.validationEnabled = raw.validate !== false;
  7137. this.commentSeverity = raw.allowComments ? undefined : jsonLanguageTypes_1.DiagnosticSeverity.Error;
  7138. }
  7139. };
  7140. JSONValidation.prototype.doValidation = function (textDocument, jsonDocument, documentSettings, schema) {
  7141. var _this = this;
  7142. if (!this.validationEnabled) {
  7143. return this.promise.resolve([]);
  7144. }
  7145. var diagnostics = [];
  7146. var added = {};
  7147. var addProblem = function (problem) {
  7148. // remove duplicated messages
  7149. var signature = problem.range.start.line + ' ' + problem.range.start.character + ' ' + problem.message;
  7150. if (!added[signature]) {
  7151. added[signature] = true;
  7152. diagnostics.push(problem);
  7153. }
  7154. };
  7155. var getDiagnostics = function (schema) {
  7156. var trailingCommaSeverity = (documentSettings === null || documentSettings === void 0 ? void 0 : documentSettings.trailingCommas) ? toDiagnosticSeverity(documentSettings.trailingCommas) : jsonLanguageTypes_1.DiagnosticSeverity.Error;
  7157. var commentSeverity = (documentSettings === null || documentSettings === void 0 ? void 0 : documentSettings.comments) ? toDiagnosticSeverity(documentSettings.comments) : _this.commentSeverity;
  7158. var schemaValidation = (documentSettings === null || documentSettings === void 0 ? void 0 : documentSettings.schemaValidation) ? toDiagnosticSeverity(documentSettings.schemaValidation) : jsonLanguageTypes_1.DiagnosticSeverity.Warning;
  7159. var schemaRequest = (documentSettings === null || documentSettings === void 0 ? void 0 : documentSettings.schemaRequest) ? toDiagnosticSeverity(documentSettings.schemaRequest) : jsonLanguageTypes_1.DiagnosticSeverity.Warning;
  7160. if (schema) {
  7161. if (schema.errors.length && jsonDocument.root && schemaRequest) {
  7162. var astRoot = jsonDocument.root;
  7163. var property = astRoot.type === 'object' ? astRoot.properties[0] : undefined;
  7164. if (property && property.keyNode.value === '$schema') {
  7165. var node = property.valueNode || property;
  7166. var range = jsonLanguageTypes_1.Range.create(textDocument.positionAt(node.offset), textDocument.positionAt(node.offset + node.length));
  7167. addProblem(jsonLanguageTypes_1.Diagnostic.create(range, schema.errors[0], schemaRequest, jsonLanguageTypes_1.ErrorCode.SchemaResolveError));
  7168. }
  7169. else {
  7170. var range = jsonLanguageTypes_1.Range.create(textDocument.positionAt(astRoot.offset), textDocument.positionAt(astRoot.offset + 1));
  7171. addProblem(jsonLanguageTypes_1.Diagnostic.create(range, schema.errors[0], schemaRequest, jsonLanguageTypes_1.ErrorCode.SchemaResolveError));
  7172. }
  7173. }
  7174. else if (schemaValidation) {
  7175. var semanticErrors = jsonDocument.validate(textDocument, schema.schema, schemaValidation);
  7176. if (semanticErrors) {
  7177. semanticErrors.forEach(addProblem);
  7178. }
  7179. }
  7180. if (schemaAllowsComments(schema.schema)) {
  7181. commentSeverity = undefined;
  7182. }
  7183. if (schemaAllowsTrailingCommas(schema.schema)) {
  7184. trailingCommaSeverity = undefined;
  7185. }
  7186. }
  7187. for (var _i = 0, _a = jsonDocument.syntaxErrors; _i < _a.length; _i++) {
  7188. var p = _a[_i];
  7189. if (p.code === jsonLanguageTypes_1.ErrorCode.TrailingComma) {
  7190. if (typeof trailingCommaSeverity !== 'number') {
  7191. continue;
  7192. }
  7193. p.severity = trailingCommaSeverity;
  7194. }
  7195. addProblem(p);
  7196. }
  7197. if (typeof commentSeverity === 'number') {
  7198. var message_1 = localize('InvalidCommentToken', 'Comments are not permitted in JSON.');
  7199. jsonDocument.comments.forEach(function (c) {
  7200. addProblem(jsonLanguageTypes_1.Diagnostic.create(c, message_1, commentSeverity, jsonLanguageTypes_1.ErrorCode.CommentNotPermitted));
  7201. });
  7202. }
  7203. return diagnostics;
  7204. };
  7205. if (schema) {
  7206. var id = schema.id || ('schemaservice://untitled/' + idCounter++);
  7207. return this.jsonSchemaService.resolveSchemaContent(new jsonSchemaService_1.UnresolvedSchema(schema), id, {}).then(function (resolvedSchema) {
  7208. return getDiagnostics(resolvedSchema);
  7209. });
  7210. }
  7211. return this.jsonSchemaService.getSchemaForResource(textDocument.uri, jsonDocument).then(function (schema) {
  7212. return getDiagnostics(schema);
  7213. });
  7214. };
  7215. return JSONValidation;
  7216. }());
  7217. exports.JSONValidation = JSONValidation;
  7218. var idCounter = 0;
  7219. function schemaAllowsComments(schemaRef) {
  7220. if (schemaRef && typeof schemaRef === 'object') {
  7221. if (objects_1.isBoolean(schemaRef.allowComments)) {
  7222. return schemaRef.allowComments;
  7223. }
  7224. if (schemaRef.allOf) {
  7225. for (var _i = 0, _a = schemaRef.allOf; _i < _a.length; _i++) {
  7226. var schema = _a[_i];
  7227. var allow = schemaAllowsComments(schema);
  7228. if (objects_1.isBoolean(allow)) {
  7229. return allow;
  7230. }
  7231. }
  7232. }
  7233. }
  7234. return undefined;
  7235. }
  7236. function schemaAllowsTrailingCommas(schemaRef) {
  7237. if (schemaRef && typeof schemaRef === 'object') {
  7238. if (objects_1.isBoolean(schemaRef.allowTrailingCommas)) {
  7239. return schemaRef.allowTrailingCommas;
  7240. }
  7241. var deprSchemaRef = schemaRef;
  7242. if (objects_1.isBoolean(deprSchemaRef['allowsTrailingCommas'])) { // deprecated
  7243. return deprSchemaRef['allowsTrailingCommas'];
  7244. }
  7245. if (schemaRef.allOf) {
  7246. for (var _i = 0, _a = schemaRef.allOf; _i < _a.length; _i++) {
  7247. var schema = _a[_i];
  7248. var allow = schemaAllowsTrailingCommas(schema);
  7249. if (objects_1.isBoolean(allow)) {
  7250. return allow;
  7251. }
  7252. }
  7253. }
  7254. }
  7255. return undefined;
  7256. }
  7257. function toDiagnosticSeverity(severityLevel) {
  7258. switch (severityLevel) {
  7259. case 'error': return jsonLanguageTypes_1.DiagnosticSeverity.Error;
  7260. case 'warning': return jsonLanguageTypes_1.DiagnosticSeverity.Warning;
  7261. case 'ignore': return undefined;
  7262. }
  7263. return undefined;
  7264. }
  7265. });
  7266. /*---------------------------------------------------------------------------------------------
  7267. * Copyright (c) Microsoft Corporation. All rights reserved.
  7268. * Licensed under the MIT License. See License.txt in the project root for license information.
  7269. *--------------------------------------------------------------------------------------------*/
  7270. (function (factory) {
  7271. if (typeof module === "object" && typeof module.exports === "object") {
  7272. var v = factory(require, exports);
  7273. if (v !== undefined) module.exports = v;
  7274. }
  7275. else if (typeof define === "function" && define.amd) {
  7276. define('vscode-json-languageservice/utils/colors',["require", "exports"], factory);
  7277. }
  7278. })(function (require, exports) {
  7279. "use strict";
  7280. Object.defineProperty(exports, "__esModule", { value: true });
  7281. exports.colorFrom256RGB = exports.colorFromHex = exports.hexDigit = void 0;
  7282. var Digit0 = 48;
  7283. var Digit9 = 57;
  7284. var A = 65;
  7285. var a = 97;
  7286. var f = 102;
  7287. function hexDigit(charCode) {
  7288. if (charCode < Digit0) {
  7289. return 0;
  7290. }
  7291. if (charCode <= Digit9) {
  7292. return charCode - Digit0;
  7293. }
  7294. if (charCode < a) {
  7295. charCode += (a - A);
  7296. }
  7297. if (charCode >= a && charCode <= f) {
  7298. return charCode - a + 10;
  7299. }
  7300. return 0;
  7301. }
  7302. exports.hexDigit = hexDigit;
  7303. function colorFromHex(text) {
  7304. if (text[0] !== '#') {
  7305. return undefined;
  7306. }
  7307. switch (text.length) {
  7308. case 4:
  7309. return {
  7310. red: (hexDigit(text.charCodeAt(1)) * 0x11) / 255.0,
  7311. green: (hexDigit(text.charCodeAt(2)) * 0x11) / 255.0,
  7312. blue: (hexDigit(text.charCodeAt(3)) * 0x11) / 255.0,
  7313. alpha: 1
  7314. };
  7315. case 5:
  7316. return {
  7317. red: (hexDigit(text.charCodeAt(1)) * 0x11) / 255.0,
  7318. green: (hexDigit(text.charCodeAt(2)) * 0x11) / 255.0,
  7319. blue: (hexDigit(text.charCodeAt(3)) * 0x11) / 255.0,
  7320. alpha: (hexDigit(text.charCodeAt(4)) * 0x11) / 255.0,
  7321. };
  7322. case 7:
  7323. return {
  7324. red: (hexDigit(text.charCodeAt(1)) * 0x10 + hexDigit(text.charCodeAt(2))) / 255.0,
  7325. green: (hexDigit(text.charCodeAt(3)) * 0x10 + hexDigit(text.charCodeAt(4))) / 255.0,
  7326. blue: (hexDigit(text.charCodeAt(5)) * 0x10 + hexDigit(text.charCodeAt(6))) / 255.0,
  7327. alpha: 1
  7328. };
  7329. case 9:
  7330. return {
  7331. red: (hexDigit(text.charCodeAt(1)) * 0x10 + hexDigit(text.charCodeAt(2))) / 255.0,
  7332. green: (hexDigit(text.charCodeAt(3)) * 0x10 + hexDigit(text.charCodeAt(4))) / 255.0,
  7333. blue: (hexDigit(text.charCodeAt(5)) * 0x10 + hexDigit(text.charCodeAt(6))) / 255.0,
  7334. alpha: (hexDigit(text.charCodeAt(7)) * 0x10 + hexDigit(text.charCodeAt(8))) / 255.0
  7335. };
  7336. }
  7337. return undefined;
  7338. }
  7339. exports.colorFromHex = colorFromHex;
  7340. function colorFrom256RGB(red, green, blue, alpha) {
  7341. if (alpha === void 0) { alpha = 1.0; }
  7342. return {
  7343. red: red / 255.0,
  7344. green: green / 255.0,
  7345. blue: blue / 255.0,
  7346. alpha: alpha
  7347. };
  7348. }
  7349. exports.colorFrom256RGB = colorFrom256RGB;
  7350. });
  7351. /*---------------------------------------------------------------------------------------------
  7352. * Copyright (c) Microsoft Corporation. All rights reserved.
  7353. * Licensed under the MIT License. See License.txt in the project root for license information.
  7354. *--------------------------------------------------------------------------------------------*/
  7355. (function (factory) {
  7356. if (typeof module === "object" && typeof module.exports === "object") {
  7357. var v = factory(require, exports);
  7358. if (v !== undefined) module.exports = v;
  7359. }
  7360. else if (typeof define === "function" && define.amd) {
  7361. define('vscode-json-languageservice/services/jsonDocumentSymbols',["require", "exports", "../parser/jsonParser", "../utils/strings", "../utils/colors", "../jsonLanguageTypes"], factory);
  7362. }
  7363. })(function (require, exports) {
  7364. "use strict";
  7365. Object.defineProperty(exports, "__esModule", { value: true });
  7366. exports.JSONDocumentSymbols = void 0;
  7367. var Parser = require("../parser/jsonParser");
  7368. var Strings = require("../utils/strings");
  7369. var colors_1 = require("../utils/colors");
  7370. var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
  7371. var JSONDocumentSymbols = /** @class */ (function () {
  7372. function JSONDocumentSymbols(schemaService) {
  7373. this.schemaService = schemaService;
  7374. }
  7375. JSONDocumentSymbols.prototype.findDocumentSymbols = function (document, doc, context) {
  7376. var _this = this;
  7377. if (context === void 0) { context = { resultLimit: Number.MAX_VALUE }; }
  7378. var root = doc.root;
  7379. if (!root) {
  7380. return [];
  7381. }
  7382. var limit = context.resultLimit || Number.MAX_VALUE;
  7383. // special handling for key bindings
  7384. var resourceString = document.uri;
  7385. if ((resourceString === 'vscode://defaultsettings/keybindings.json') || Strings.endsWith(resourceString.toLowerCase(), '/user/keybindings.json')) {
  7386. if (root.type === 'array') {
  7387. var result_1 = [];
  7388. for (var _i = 0, _a = root.items; _i < _a.length; _i++) {
  7389. var item = _a[_i];
  7390. if (item.type === 'object') {
  7391. for (var _b = 0, _c = item.properties; _b < _c.length; _b++) {
  7392. var property = _c[_b];
  7393. if (property.keyNode.value === 'key' && property.valueNode) {
  7394. var location = jsonLanguageTypes_1.Location.create(document.uri, getRange(document, item));
  7395. result_1.push({ name: Parser.getNodeValue(property.valueNode), kind: jsonLanguageTypes_1.SymbolKind.Function, location: location });
  7396. limit--;
  7397. if (limit <= 0) {
  7398. if (context && context.onResultLimitExceeded) {
  7399. context.onResultLimitExceeded(resourceString);
  7400. }
  7401. return result_1;
  7402. }
  7403. }
  7404. }
  7405. }
  7406. }
  7407. return result_1;
  7408. }
  7409. }
  7410. var toVisit = [
  7411. { node: root, containerName: '' }
  7412. ];
  7413. var nextToVisit = 0;
  7414. var limitExceeded = false;
  7415. var result = [];
  7416. var collectOutlineEntries = function (node, containerName) {
  7417. if (node.type === 'array') {
  7418. node.items.forEach(function (node) {
  7419. if (node) {
  7420. toVisit.push({ node: node, containerName: containerName });
  7421. }
  7422. });
  7423. }
  7424. else if (node.type === 'object') {
  7425. node.properties.forEach(function (property) {
  7426. var valueNode = property.valueNode;
  7427. if (valueNode) {
  7428. if (limit > 0) {
  7429. limit--;
  7430. var location = jsonLanguageTypes_1.Location.create(document.uri, getRange(document, property));
  7431. var childContainerName = containerName ? containerName + '.' + property.keyNode.value : property.keyNode.value;
  7432. result.push({ name: _this.getKeyLabel(property), kind: _this.getSymbolKind(valueNode.type), location: location, containerName: containerName });
  7433. toVisit.push({ node: valueNode, containerName: childContainerName });
  7434. }
  7435. else {
  7436. limitExceeded = true;
  7437. }
  7438. }
  7439. });
  7440. }
  7441. };
  7442. // breath first traversal
  7443. while (nextToVisit < toVisit.length) {
  7444. var next = toVisit[nextToVisit++];
  7445. collectOutlineEntries(next.node, next.containerName);
  7446. }
  7447. if (limitExceeded && context && context.onResultLimitExceeded) {
  7448. context.onResultLimitExceeded(resourceString);
  7449. }
  7450. return result;
  7451. };
  7452. JSONDocumentSymbols.prototype.findDocumentSymbols2 = function (document, doc, context) {
  7453. var _this = this;
  7454. if (context === void 0) { context = { resultLimit: Number.MAX_VALUE }; }
  7455. var root = doc.root;
  7456. if (!root) {
  7457. return [];
  7458. }
  7459. var limit = context.resultLimit || Number.MAX_VALUE;
  7460. // special handling for key bindings
  7461. var resourceString = document.uri;
  7462. if ((resourceString === 'vscode://defaultsettings/keybindings.json') || Strings.endsWith(resourceString.toLowerCase(), '/user/keybindings.json')) {
  7463. if (root.type === 'array') {
  7464. var result_2 = [];
  7465. for (var _i = 0, _a = root.items; _i < _a.length; _i++) {
  7466. var item = _a[_i];
  7467. if (item.type === 'object') {
  7468. for (var _b = 0, _c = item.properties; _b < _c.length; _b++) {
  7469. var property = _c[_b];
  7470. if (property.keyNode.value === 'key' && property.valueNode) {
  7471. var range = getRange(document, item);
  7472. var selectionRange = getRange(document, property.keyNode);
  7473. result_2.push({ name: Parser.getNodeValue(property.valueNode), kind: jsonLanguageTypes_1.SymbolKind.Function, range: range, selectionRange: selectionRange });
  7474. limit--;
  7475. if (limit <= 0) {
  7476. if (context && context.onResultLimitExceeded) {
  7477. context.onResultLimitExceeded(resourceString);
  7478. }
  7479. return result_2;
  7480. }
  7481. }
  7482. }
  7483. }
  7484. }
  7485. return result_2;
  7486. }
  7487. }
  7488. var result = [];
  7489. var toVisit = [
  7490. { node: root, result: result }
  7491. ];
  7492. var nextToVisit = 0;
  7493. var limitExceeded = false;
  7494. var collectOutlineEntries = function (node, result) {
  7495. if (node.type === 'array') {
  7496. node.items.forEach(function (node, index) {
  7497. if (node) {
  7498. if (limit > 0) {
  7499. limit--;
  7500. var range = getRange(document, node);
  7501. var selectionRange = range;
  7502. var name = String(index);
  7503. var symbol = { name: name, kind: _this.getSymbolKind(node.type), range: range, selectionRange: selectionRange, children: [] };
  7504. result.push(symbol);
  7505. toVisit.push({ result: symbol.children, node: node });
  7506. }
  7507. else {
  7508. limitExceeded = true;
  7509. }
  7510. }
  7511. });
  7512. }
  7513. else if (node.type === 'object') {
  7514. node.properties.forEach(function (property) {
  7515. var valueNode = property.valueNode;
  7516. if (valueNode) {
  7517. if (limit > 0) {
  7518. limit--;
  7519. var range = getRange(document, property);
  7520. var selectionRange = getRange(document, property.keyNode);
  7521. var children = [];
  7522. var symbol = { name: _this.getKeyLabel(property), kind: _this.getSymbolKind(valueNode.type), range: range, selectionRange: selectionRange, children: children, detail: _this.getDetail(valueNode) };
  7523. result.push(symbol);
  7524. toVisit.push({ result: children, node: valueNode });
  7525. }
  7526. else {
  7527. limitExceeded = true;
  7528. }
  7529. }
  7530. });
  7531. }
  7532. };
  7533. // breath first traversal
  7534. while (nextToVisit < toVisit.length) {
  7535. var next = toVisit[nextToVisit++];
  7536. collectOutlineEntries(next.node, next.result);
  7537. }
  7538. if (limitExceeded && context && context.onResultLimitExceeded) {
  7539. context.onResultLimitExceeded(resourceString);
  7540. }
  7541. return result;
  7542. };
  7543. JSONDocumentSymbols.prototype.getSymbolKind = function (nodeType) {
  7544. switch (nodeType) {
  7545. case 'object':
  7546. return jsonLanguageTypes_1.SymbolKind.Module;
  7547. case 'string':
  7548. return jsonLanguageTypes_1.SymbolKind.String;
  7549. case 'number':
  7550. return jsonLanguageTypes_1.SymbolKind.Number;
  7551. case 'array':
  7552. return jsonLanguageTypes_1.SymbolKind.Array;
  7553. case 'boolean':
  7554. return jsonLanguageTypes_1.SymbolKind.Boolean;
  7555. default: // 'null'
  7556. return jsonLanguageTypes_1.SymbolKind.Variable;
  7557. }
  7558. };
  7559. JSONDocumentSymbols.prototype.getKeyLabel = function (property) {
  7560. var name = property.keyNode.value;
  7561. if (name) {
  7562. name = name.replace(/[\n]/g, '↵');
  7563. }
  7564. if (name && name.trim()) {
  7565. return name;
  7566. }
  7567. return "\"" + name + "\"";
  7568. };
  7569. JSONDocumentSymbols.prototype.getDetail = function (node) {
  7570. if (!node) {
  7571. return undefined;
  7572. }
  7573. if (node.type === 'boolean' || node.type === 'number' || node.type === 'null' || node.type === 'string') {
  7574. return String(node.value);
  7575. }
  7576. else {
  7577. if (node.type === 'array') {
  7578. return node.children.length ? undefined : '[]';
  7579. }
  7580. else if (node.type === 'object') {
  7581. return node.children.length ? undefined : '{}';
  7582. }
  7583. }
  7584. return undefined;
  7585. };
  7586. JSONDocumentSymbols.prototype.findDocumentColors = function (document, doc, context) {
  7587. return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
  7588. var result = [];
  7589. if (schema) {
  7590. var limit = context && typeof context.resultLimit === 'number' ? context.resultLimit : Number.MAX_VALUE;
  7591. var matchingSchemas = doc.getMatchingSchemas(schema.schema);
  7592. var visitedNode = {};
  7593. for (var _i = 0, matchingSchemas_1 = matchingSchemas; _i < matchingSchemas_1.length; _i++) {
  7594. var s = matchingSchemas_1[_i];
  7595. if (!s.inverted && s.schema && (s.schema.format === 'color' || s.schema.format === 'color-hex') && s.node && s.node.type === 'string') {
  7596. var nodeId = String(s.node.offset);
  7597. if (!visitedNode[nodeId]) {
  7598. var color = colors_1.colorFromHex(Parser.getNodeValue(s.node));
  7599. if (color) {
  7600. var range = getRange(document, s.node);
  7601. result.push({ color: color, range: range });
  7602. }
  7603. visitedNode[nodeId] = true;
  7604. limit--;
  7605. if (limit <= 0) {
  7606. if (context && context.onResultLimitExceeded) {
  7607. context.onResultLimitExceeded(document.uri);
  7608. }
  7609. return result;
  7610. }
  7611. }
  7612. }
  7613. }
  7614. }
  7615. return result;
  7616. });
  7617. };
  7618. JSONDocumentSymbols.prototype.getColorPresentations = function (document, doc, color, range) {
  7619. var result = [];
  7620. var red256 = Math.round(color.red * 255), green256 = Math.round(color.green * 255), blue256 = Math.round(color.blue * 255);
  7621. function toTwoDigitHex(n) {
  7622. var r = n.toString(16);
  7623. return r.length !== 2 ? '0' + r : r;
  7624. }
  7625. var label;
  7626. if (color.alpha === 1) {
  7627. label = "#" + toTwoDigitHex(red256) + toTwoDigitHex(green256) + toTwoDigitHex(blue256);
  7628. }
  7629. else {
  7630. label = "#" + toTwoDigitHex(red256) + toTwoDigitHex(green256) + toTwoDigitHex(blue256) + toTwoDigitHex(Math.round(color.alpha * 255));
  7631. }
  7632. result.push({ label: label, textEdit: jsonLanguageTypes_1.TextEdit.replace(range, JSON.stringify(label)) });
  7633. return result;
  7634. };
  7635. return JSONDocumentSymbols;
  7636. }());
  7637. exports.JSONDocumentSymbols = JSONDocumentSymbols;
  7638. function getRange(document, node) {
  7639. return jsonLanguageTypes_1.Range.create(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
  7640. }
  7641. });
  7642. /*---------------------------------------------------------------------------------------------
  7643. * Copyright (c) Microsoft Corporation. All rights reserved.
  7644. * Licensed under the MIT License. See License.txt in the project root for license information.
  7645. *--------------------------------------------------------------------------------------------*/
  7646. (function (factory) {
  7647. if (typeof module === "object" && typeof module.exports === "object") {
  7648. var v = factory(require, exports);
  7649. if (v !== undefined) module.exports = v;
  7650. }
  7651. else if (typeof define === "function" && define.amd) {
  7652. define('vscode-json-languageservice/services/configuration',["require", "exports", "vscode-nls"], factory);
  7653. }
  7654. })(function (require, exports) {
  7655. "use strict";
  7656. Object.defineProperty(exports, "__esModule", { value: true });
  7657. exports.schemaContributions = void 0;
  7658. var nls = require("vscode-nls");
  7659. var localize = nls.loadMessageBundle();
  7660. exports.schemaContributions = {
  7661. schemaAssociations: [],
  7662. schemas: {
  7663. // refer to the latest schema
  7664. 'http://json-schema.org/schema#': {
  7665. $ref: 'http://json-schema.org/draft-07/schema#'
  7666. },
  7667. // bundle the schema-schema to include (localized) descriptions
  7668. 'http://json-schema.org/draft-04/schema#': {
  7669. 'title': localize('schema.json', 'Describes a JSON file using a schema. See json-schema.org for more info.'),
  7670. '$schema': 'http://json-schema.org/draft-04/schema#',
  7671. 'definitions': {
  7672. 'schemaArray': {
  7673. 'type': 'array',
  7674. 'minItems': 1,
  7675. 'items': {
  7676. '$ref': '#'
  7677. }
  7678. },
  7679. 'positiveInteger': {
  7680. 'type': 'integer',
  7681. 'minimum': 0
  7682. },
  7683. 'positiveIntegerDefault0': {
  7684. 'allOf': [
  7685. {
  7686. '$ref': '#/definitions/positiveInteger'
  7687. },
  7688. {
  7689. 'default': 0
  7690. }
  7691. ]
  7692. },
  7693. 'simpleTypes': {
  7694. 'type': 'string',
  7695. 'enum': [
  7696. 'array',
  7697. 'boolean',
  7698. 'integer',
  7699. 'null',
  7700. 'number',
  7701. 'object',
  7702. 'string'
  7703. ]
  7704. },
  7705. 'stringArray': {
  7706. 'type': 'array',
  7707. 'items': {
  7708. 'type': 'string'
  7709. },
  7710. 'minItems': 1,
  7711. 'uniqueItems': true
  7712. }
  7713. },
  7714. 'type': 'object',
  7715. 'properties': {
  7716. 'id': {
  7717. 'type': 'string',
  7718. 'format': 'uri'
  7719. },
  7720. '$schema': {
  7721. 'type': 'string',
  7722. 'format': 'uri'
  7723. },
  7724. 'title': {
  7725. 'type': 'string'
  7726. },
  7727. 'description': {
  7728. 'type': 'string'
  7729. },
  7730. 'default': {},
  7731. 'multipleOf': {
  7732. 'type': 'number',
  7733. 'minimum': 0,
  7734. 'exclusiveMinimum': true
  7735. },
  7736. 'maximum': {
  7737. 'type': 'number'
  7738. },
  7739. 'exclusiveMaximum': {
  7740. 'type': 'boolean',
  7741. 'default': false
  7742. },
  7743. 'minimum': {
  7744. 'type': 'number'
  7745. },
  7746. 'exclusiveMinimum': {
  7747. 'type': 'boolean',
  7748. 'default': false
  7749. },
  7750. 'maxLength': {
  7751. 'allOf': [
  7752. {
  7753. '$ref': '#/definitions/positiveInteger'
  7754. }
  7755. ]
  7756. },
  7757. 'minLength': {
  7758. 'allOf': [
  7759. {
  7760. '$ref': '#/definitions/positiveIntegerDefault0'
  7761. }
  7762. ]
  7763. },
  7764. 'pattern': {
  7765. 'type': 'string',
  7766. 'format': 'regex'
  7767. },
  7768. 'additionalItems': {
  7769. 'anyOf': [
  7770. {
  7771. 'type': 'boolean'
  7772. },
  7773. {
  7774. '$ref': '#'
  7775. }
  7776. ],
  7777. 'default': {}
  7778. },
  7779. 'items': {
  7780. 'anyOf': [
  7781. {
  7782. '$ref': '#'
  7783. },
  7784. {
  7785. '$ref': '#/definitions/schemaArray'
  7786. }
  7787. ],
  7788. 'default': {}
  7789. },
  7790. 'maxItems': {
  7791. 'allOf': [
  7792. {
  7793. '$ref': '#/definitions/positiveInteger'
  7794. }
  7795. ]
  7796. },
  7797. 'minItems': {
  7798. 'allOf': [
  7799. {
  7800. '$ref': '#/definitions/positiveIntegerDefault0'
  7801. }
  7802. ]
  7803. },
  7804. 'uniqueItems': {
  7805. 'type': 'boolean',
  7806. 'default': false
  7807. },
  7808. 'maxProperties': {
  7809. 'allOf': [
  7810. {
  7811. '$ref': '#/definitions/positiveInteger'
  7812. }
  7813. ]
  7814. },
  7815. 'minProperties': {
  7816. 'allOf': [
  7817. {
  7818. '$ref': '#/definitions/positiveIntegerDefault0'
  7819. }
  7820. ]
  7821. },
  7822. 'required': {
  7823. 'allOf': [
  7824. {
  7825. '$ref': '#/definitions/stringArray'
  7826. }
  7827. ]
  7828. },
  7829. 'additionalProperties': {
  7830. 'anyOf': [
  7831. {
  7832. 'type': 'boolean'
  7833. },
  7834. {
  7835. '$ref': '#'
  7836. }
  7837. ],
  7838. 'default': {}
  7839. },
  7840. 'definitions': {
  7841. 'type': 'object',
  7842. 'additionalProperties': {
  7843. '$ref': '#'
  7844. },
  7845. 'default': {}
  7846. },
  7847. 'properties': {
  7848. 'type': 'object',
  7849. 'additionalProperties': {
  7850. '$ref': '#'
  7851. },
  7852. 'default': {}
  7853. },
  7854. 'patternProperties': {
  7855. 'type': 'object',
  7856. 'additionalProperties': {
  7857. '$ref': '#'
  7858. },
  7859. 'default': {}
  7860. },
  7861. 'dependencies': {
  7862. 'type': 'object',
  7863. 'additionalProperties': {
  7864. 'anyOf': [
  7865. {
  7866. '$ref': '#'
  7867. },
  7868. {
  7869. '$ref': '#/definitions/stringArray'
  7870. }
  7871. ]
  7872. }
  7873. },
  7874. 'enum': {
  7875. 'type': 'array',
  7876. 'minItems': 1,
  7877. 'uniqueItems': true
  7878. },
  7879. 'type': {
  7880. 'anyOf': [
  7881. {
  7882. '$ref': '#/definitions/simpleTypes'
  7883. },
  7884. {
  7885. 'type': 'array',
  7886. 'items': {
  7887. '$ref': '#/definitions/simpleTypes'
  7888. },
  7889. 'minItems': 1,
  7890. 'uniqueItems': true
  7891. }
  7892. ]
  7893. },
  7894. 'format': {
  7895. 'anyOf': [
  7896. {
  7897. 'type': 'string',
  7898. 'enum': [
  7899. 'date-time',
  7900. 'uri',
  7901. 'email',
  7902. 'hostname',
  7903. 'ipv4',
  7904. 'ipv6',
  7905. 'regex'
  7906. ]
  7907. },
  7908. {
  7909. 'type': 'string'
  7910. }
  7911. ]
  7912. },
  7913. 'allOf': {
  7914. 'allOf': [
  7915. {
  7916. '$ref': '#/definitions/schemaArray'
  7917. }
  7918. ]
  7919. },
  7920. 'anyOf': {
  7921. 'allOf': [
  7922. {
  7923. '$ref': '#/definitions/schemaArray'
  7924. }
  7925. ]
  7926. },
  7927. 'oneOf': {
  7928. 'allOf': [
  7929. {
  7930. '$ref': '#/definitions/schemaArray'
  7931. }
  7932. ]
  7933. },
  7934. 'not': {
  7935. 'allOf': [
  7936. {
  7937. '$ref': '#'
  7938. }
  7939. ]
  7940. }
  7941. },
  7942. 'dependencies': {
  7943. 'exclusiveMaximum': [
  7944. 'maximum'
  7945. ],
  7946. 'exclusiveMinimum': [
  7947. 'minimum'
  7948. ]
  7949. },
  7950. 'default': {}
  7951. },
  7952. 'http://json-schema.org/draft-07/schema#': {
  7953. 'title': localize('schema.json', 'Describes a JSON file using a schema. See json-schema.org for more info.'),
  7954. 'definitions': {
  7955. 'schemaArray': {
  7956. 'type': 'array',
  7957. 'minItems': 1,
  7958. 'items': { '$ref': '#' }
  7959. },
  7960. 'nonNegativeInteger': {
  7961. 'type': 'integer',
  7962. 'minimum': 0
  7963. },
  7964. 'nonNegativeIntegerDefault0': {
  7965. 'allOf': [
  7966. { '$ref': '#/definitions/nonNegativeInteger' },
  7967. { 'default': 0 }
  7968. ]
  7969. },
  7970. 'simpleTypes': {
  7971. 'enum': [
  7972. 'array',
  7973. 'boolean',
  7974. 'integer',
  7975. 'null',
  7976. 'number',
  7977. 'object',
  7978. 'string'
  7979. ]
  7980. },
  7981. 'stringArray': {
  7982. 'type': 'array',
  7983. 'items': { 'type': 'string' },
  7984. 'uniqueItems': true,
  7985. 'default': []
  7986. }
  7987. },
  7988. 'type': ['object', 'boolean'],
  7989. 'properties': {
  7990. '$id': {
  7991. 'type': 'string',
  7992. 'format': 'uri-reference'
  7993. },
  7994. '$schema': {
  7995. 'type': 'string',
  7996. 'format': 'uri'
  7997. },
  7998. '$ref': {
  7999. 'type': 'string',
  8000. 'format': 'uri-reference'
  8001. },
  8002. '$comment': {
  8003. 'type': 'string'
  8004. },
  8005. 'title': {
  8006. 'type': 'string'
  8007. },
  8008. 'description': {
  8009. 'type': 'string'
  8010. },
  8011. 'default': true,
  8012. 'readOnly': {
  8013. 'type': 'boolean',
  8014. 'default': false
  8015. },
  8016. 'examples': {
  8017. 'type': 'array',
  8018. 'items': true
  8019. },
  8020. 'multipleOf': {
  8021. 'type': 'number',
  8022. 'exclusiveMinimum': 0
  8023. },
  8024. 'maximum': {
  8025. 'type': 'number'
  8026. },
  8027. 'exclusiveMaximum': {
  8028. 'type': 'number'
  8029. },
  8030. 'minimum': {
  8031. 'type': 'number'
  8032. },
  8033. 'exclusiveMinimum': {
  8034. 'type': 'number'
  8035. },
  8036. 'maxLength': { '$ref': '#/definitions/nonNegativeInteger' },
  8037. 'minLength': { '$ref': '#/definitions/nonNegativeIntegerDefault0' },
  8038. 'pattern': {
  8039. 'type': 'string',
  8040. 'format': 'regex'
  8041. },
  8042. 'additionalItems': { '$ref': '#' },
  8043. 'items': {
  8044. 'anyOf': [
  8045. { '$ref': '#' },
  8046. { '$ref': '#/definitions/schemaArray' }
  8047. ],
  8048. 'default': true
  8049. },
  8050. 'maxItems': { '$ref': '#/definitions/nonNegativeInteger' },
  8051. 'minItems': { '$ref': '#/definitions/nonNegativeIntegerDefault0' },
  8052. 'uniqueItems': {
  8053. 'type': 'boolean',
  8054. 'default': false
  8055. },
  8056. 'contains': { '$ref': '#' },
  8057. 'maxProperties': { '$ref': '#/definitions/nonNegativeInteger' },
  8058. 'minProperties': { '$ref': '#/definitions/nonNegativeIntegerDefault0' },
  8059. 'required': { '$ref': '#/definitions/stringArray' },
  8060. 'additionalProperties': { '$ref': '#' },
  8061. 'definitions': {
  8062. 'type': 'object',
  8063. 'additionalProperties': { '$ref': '#' },
  8064. 'default': {}
  8065. },
  8066. 'properties': {
  8067. 'type': 'object',
  8068. 'additionalProperties': { '$ref': '#' },
  8069. 'default': {}
  8070. },
  8071. 'patternProperties': {
  8072. 'type': 'object',
  8073. 'additionalProperties': { '$ref': '#' },
  8074. 'propertyNames': { 'format': 'regex' },
  8075. 'default': {}
  8076. },
  8077. 'dependencies': {
  8078. 'type': 'object',
  8079. 'additionalProperties': {
  8080. 'anyOf': [
  8081. { '$ref': '#' },
  8082. { '$ref': '#/definitions/stringArray' }
  8083. ]
  8084. }
  8085. },
  8086. 'propertyNames': { '$ref': '#' },
  8087. 'const': true,
  8088. 'enum': {
  8089. 'type': 'array',
  8090. 'items': true,
  8091. 'minItems': 1,
  8092. 'uniqueItems': true
  8093. },
  8094. 'type': {
  8095. 'anyOf': [
  8096. { '$ref': '#/definitions/simpleTypes' },
  8097. {
  8098. 'type': 'array',
  8099. 'items': { '$ref': '#/definitions/simpleTypes' },
  8100. 'minItems': 1,
  8101. 'uniqueItems': true
  8102. }
  8103. ]
  8104. },
  8105. 'format': { 'type': 'string' },
  8106. 'contentMediaType': { 'type': 'string' },
  8107. 'contentEncoding': { 'type': 'string' },
  8108. 'if': { '$ref': '#' },
  8109. 'then': { '$ref': '#' },
  8110. 'else': { '$ref': '#' },
  8111. 'allOf': { '$ref': '#/definitions/schemaArray' },
  8112. 'anyOf': { '$ref': '#/definitions/schemaArray' },
  8113. 'oneOf': { '$ref': '#/definitions/schemaArray' },
  8114. 'not': { '$ref': '#' }
  8115. },
  8116. 'default': true
  8117. }
  8118. }
  8119. };
  8120. var descriptions = {
  8121. id: localize('schema.json.id', "A unique identifier for the schema."),
  8122. $schema: localize('schema.json.$schema', "The schema to verify this document against."),
  8123. title: localize('schema.json.title', "A descriptive title of the element."),
  8124. description: localize('schema.json.description', "A long description of the element. Used in hover menus and suggestions."),
  8125. default: localize('schema.json.default', "A default value. Used by suggestions."),
  8126. multipleOf: localize('schema.json.multipleOf', "A number that should cleanly divide the current value (i.e. have no remainder)."),
  8127. maximum: localize('schema.json.maximum', "The maximum numerical value, inclusive by default."),
  8128. exclusiveMaximum: localize('schema.json.exclusiveMaximum', "Makes the maximum property exclusive."),
  8129. minimum: localize('schema.json.minimum', "The minimum numerical value, inclusive by default."),
  8130. exclusiveMinimum: localize('schema.json.exclusiveMininum', "Makes the minimum property exclusive."),
  8131. maxLength: localize('schema.json.maxLength', "The maximum length of a string."),
  8132. minLength: localize('schema.json.minLength', "The minimum length of a string."),
  8133. pattern: localize('schema.json.pattern', "A regular expression to match the string against. It is not implicitly anchored."),
  8134. additionalItems: localize('schema.json.additionalItems', "For arrays, only when items is set as an array. If it is a schema, then this schema validates items after the ones specified by the items array. If it is false, then additional items will cause validation to fail."),
  8135. items: localize('schema.json.items', "For arrays. Can either be a schema to validate every element against or an array of schemas to validate each item against in order (the first schema will validate the first element, the second schema will validate the second element, and so on."),
  8136. maxItems: localize('schema.json.maxItems', "The maximum number of items that can be inside an array. Inclusive."),
  8137. minItems: localize('schema.json.minItems', "The minimum number of items that can be inside an array. Inclusive."),
  8138. uniqueItems: localize('schema.json.uniqueItems', "If all of the items in the array must be unique. Defaults to false."),
  8139. maxProperties: localize('schema.json.maxProperties', "The maximum number of properties an object can have. Inclusive."),
  8140. minProperties: localize('schema.json.minProperties', "The minimum number of properties an object can have. Inclusive."),
  8141. required: localize('schema.json.required', "An array of strings that lists the names of all properties required on this object."),
  8142. additionalProperties: localize('schema.json.additionalProperties', "Either a schema or a boolean. If a schema, then used to validate all properties not matched by 'properties' or 'patternProperties'. If false, then any properties not matched by either will cause this schema to fail."),
  8143. definitions: localize('schema.json.definitions', "Not used for validation. Place subschemas here that you wish to reference inline with $ref."),
  8144. properties: localize('schema.json.properties', "A map of property names to schemas for each property."),
  8145. patternProperties: localize('schema.json.patternProperties', "A map of regular expressions on property names to schemas for matching properties."),
  8146. dependencies: localize('schema.json.dependencies', "A map of property names to either an array of property names or a schema. An array of property names means the property named in the key depends on the properties in the array being present in the object in order to be valid. If the value is a schema, then the schema is only applied to the object if the property in the key exists on the object."),
  8147. enum: localize('schema.json.enum', "The set of literal values that are valid."),
  8148. type: localize('schema.json.type', "Either a string of one of the basic schema types (number, integer, null, array, object, boolean, string) or an array of strings specifying a subset of those types."),
  8149. format: localize('schema.json.format', "Describes the format expected for the value."),
  8150. allOf: localize('schema.json.allOf', "An array of schemas, all of which must match."),
  8151. anyOf: localize('schema.json.anyOf', "An array of schemas, where at least one must match."),
  8152. oneOf: localize('schema.json.oneOf', "An array of schemas, exactly one of which must match."),
  8153. not: localize('schema.json.not', "A schema which must not match."),
  8154. $id: localize('schema.json.$id', "A unique identifier for the schema."),
  8155. $ref: localize('schema.json.$ref', "Reference a definition hosted on any location."),
  8156. $comment: localize('schema.json.$comment', "Comments from schema authors to readers or maintainers of the schema."),
  8157. readOnly: localize('schema.json.readOnly', "Indicates that the value of the instance is managed exclusively by the owning authority."),
  8158. examples: localize('schema.json.examples', "Sample JSON values associated with a particular schema, for the purpose of illustrating usage."),
  8159. contains: localize('schema.json.contains', "An array instance is valid against \"contains\" if at least one of its elements is valid against the given schema."),
  8160. propertyNames: localize('schema.json.propertyNames', "If the instance is an object, this keyword validates if every property name in the instance validates against the provided schema."),
  8161. const: localize('schema.json.const', "An instance validates successfully against this keyword if its value is equal to the value of the keyword."),
  8162. contentMediaType: localize('schema.json.contentMediaType', "Describes the media type of a string property."),
  8163. contentEncoding: localize('schema.json.contentEncoding', "Describes the content encoding of a string property."),
  8164. if: localize('schema.json.if', "The validation outcome of the \"if\" subschema controls which of the \"then\" or \"else\" keywords are evaluated."),
  8165. then: localize('schema.json.then', "The \"if\" subschema is used for validation when the \"if\" subschema succeeds."),
  8166. else: localize('schema.json.else', "The \"else\" subschema is used for validation when the \"if\" subschema fails.")
  8167. };
  8168. for (var schemaName in exports.schemaContributions.schemas) {
  8169. var schema = exports.schemaContributions.schemas[schemaName];
  8170. for (var property in schema.properties) {
  8171. var propertyObject = schema.properties[property];
  8172. if (typeof propertyObject === 'boolean') {
  8173. propertyObject = schema.properties[property] = {};
  8174. }
  8175. var description = descriptions[property];
  8176. if (description) {
  8177. propertyObject['description'] = description;
  8178. }
  8179. else {
  8180. console.log(property + ": localize('schema.json." + property + "', \"\")");
  8181. }
  8182. }
  8183. }
  8184. });
  8185. /*---------------------------------------------------------------------------------------------
  8186. * Copyright (c) Microsoft Corporation. All rights reserved.
  8187. * Licensed under the MIT License. See License.txt in the project root for license information.
  8188. *--------------------------------------------------------------------------------------------*/
  8189. (function (factory) {
  8190. if (typeof module === "object" && typeof module.exports === "object") {
  8191. var v = factory(require, exports);
  8192. if (v !== undefined) module.exports = v;
  8193. }
  8194. else if (typeof define === "function" && define.amd) {
  8195. define('vscode-json-languageservice/services/jsonFolding',["require", "exports", "jsonc-parser", "../jsonLanguageTypes"], factory);
  8196. }
  8197. })(function (require, exports) {
  8198. "use strict";
  8199. Object.defineProperty(exports, "__esModule", { value: true });
  8200. exports.getFoldingRanges = void 0;
  8201. var jsonc_parser_1 = require("jsonc-parser");
  8202. var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
  8203. function getFoldingRanges(document, context) {
  8204. var ranges = [];
  8205. var nestingLevels = [];
  8206. var stack = [];
  8207. var prevStart = -1;
  8208. var scanner = jsonc_parser_1.createScanner(document.getText(), false);
  8209. var token = scanner.scan();
  8210. function addRange(range) {
  8211. ranges.push(range);
  8212. nestingLevels.push(stack.length);
  8213. }
  8214. while (token !== 17 /* EOF */) {
  8215. switch (token) {
  8216. case 1 /* OpenBraceToken */:
  8217. case 3 /* OpenBracketToken */: {
  8218. var startLine = document.positionAt(scanner.getTokenOffset()).line;
  8219. var range = { startLine: startLine, endLine: startLine, kind: token === 1 /* OpenBraceToken */ ? 'object' : 'array' };
  8220. stack.push(range);
  8221. break;
  8222. }
  8223. case 2 /* CloseBraceToken */:
  8224. case 4 /* CloseBracketToken */: {
  8225. var kind = token === 2 /* CloseBraceToken */ ? 'object' : 'array';
  8226. if (stack.length > 0 && stack[stack.length - 1].kind === kind) {
  8227. var range = stack.pop();
  8228. var line = document.positionAt(scanner.getTokenOffset()).line;
  8229. if (range && line > range.startLine + 1 && prevStart !== range.startLine) {
  8230. range.endLine = line - 1;
  8231. addRange(range);
  8232. prevStart = range.startLine;
  8233. }
  8234. }
  8235. break;
  8236. }
  8237. case 13 /* BlockCommentTrivia */: {
  8238. var startLine = document.positionAt(scanner.getTokenOffset()).line;
  8239. var endLine = document.positionAt(scanner.getTokenOffset() + scanner.getTokenLength()).line;
  8240. if (scanner.getTokenError() === 1 /* UnexpectedEndOfComment */ && startLine + 1 < document.lineCount) {
  8241. scanner.setPosition(document.offsetAt(jsonLanguageTypes_1.Position.create(startLine + 1, 0)));
  8242. }
  8243. else {
  8244. if (startLine < endLine) {
  8245. addRange({ startLine: startLine, endLine: endLine, kind: jsonLanguageTypes_1.FoldingRangeKind.Comment });
  8246. prevStart = startLine;
  8247. }
  8248. }
  8249. break;
  8250. }
  8251. case 12 /* LineCommentTrivia */: {
  8252. var text = document.getText().substr(scanner.getTokenOffset(), scanner.getTokenLength());
  8253. var m = text.match(/^\/\/\s*#(region\b)|(endregion\b)/);
  8254. if (m) {
  8255. var line = document.positionAt(scanner.getTokenOffset()).line;
  8256. if (m[1]) { // start pattern match
  8257. var range = { startLine: line, endLine: line, kind: jsonLanguageTypes_1.FoldingRangeKind.Region };
  8258. stack.push(range);
  8259. }
  8260. else {
  8261. var i = stack.length - 1;
  8262. while (i >= 0 && stack[i].kind !== jsonLanguageTypes_1.FoldingRangeKind.Region) {
  8263. i--;
  8264. }
  8265. if (i >= 0) {
  8266. var range = stack[i];
  8267. stack.length = i;
  8268. if (line > range.startLine && prevStart !== range.startLine) {
  8269. range.endLine = line;
  8270. addRange(range);
  8271. prevStart = range.startLine;
  8272. }
  8273. }
  8274. }
  8275. }
  8276. break;
  8277. }
  8278. }
  8279. token = scanner.scan();
  8280. }
  8281. var rangeLimit = context && context.rangeLimit;
  8282. if (typeof rangeLimit !== 'number' || ranges.length <= rangeLimit) {
  8283. return ranges;
  8284. }
  8285. if (context && context.onRangeLimitExceeded) {
  8286. context.onRangeLimitExceeded(document.uri);
  8287. }
  8288. var counts = [];
  8289. for (var _i = 0, nestingLevels_1 = nestingLevels; _i < nestingLevels_1.length; _i++) {
  8290. var level = nestingLevels_1[_i];
  8291. if (level < 30) {
  8292. counts[level] = (counts[level] || 0) + 1;
  8293. }
  8294. }
  8295. var entries = 0;
  8296. var maxLevel = 0;
  8297. for (var i = 0; i < counts.length; i++) {
  8298. var n = counts[i];
  8299. if (n) {
  8300. if (n + entries > rangeLimit) {
  8301. maxLevel = i;
  8302. break;
  8303. }
  8304. entries += n;
  8305. }
  8306. }
  8307. var result = [];
  8308. for (var i = 0; i < ranges.length; i++) {
  8309. var level = nestingLevels[i];
  8310. if (typeof level === 'number') {
  8311. if (level < maxLevel || (level === maxLevel && entries++ < rangeLimit)) {
  8312. result.push(ranges[i]);
  8313. }
  8314. }
  8315. }
  8316. return result;
  8317. }
  8318. exports.getFoldingRanges = getFoldingRanges;
  8319. });
  8320. /*---------------------------------------------------------------------------------------------
  8321. * Copyright (c) Microsoft Corporation. All rights reserved.
  8322. * Licensed under the MIT License. See License.txt in the project root for license information.
  8323. *--------------------------------------------------------------------------------------------*/
  8324. (function (factory) {
  8325. if (typeof module === "object" && typeof module.exports === "object") {
  8326. var v = factory(require, exports);
  8327. if (v !== undefined) module.exports = v;
  8328. }
  8329. else if (typeof define === "function" && define.amd) {
  8330. define('vscode-json-languageservice/services/jsonSelectionRanges',["require", "exports", "../jsonLanguageTypes", "jsonc-parser"], factory);
  8331. }
  8332. })(function (require, exports) {
  8333. "use strict";
  8334. Object.defineProperty(exports, "__esModule", { value: true });
  8335. exports.getSelectionRanges = void 0;
  8336. var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
  8337. var jsonc_parser_1 = require("jsonc-parser");
  8338. function getSelectionRanges(document, positions, doc) {
  8339. function getSelectionRange(position) {
  8340. var offset = document.offsetAt(position);
  8341. var node = doc.getNodeFromOffset(offset, true);
  8342. var result = [];
  8343. while (node) {
  8344. switch (node.type) {
  8345. case 'string':
  8346. case 'object':
  8347. case 'array':
  8348. // range without ", [ or {
  8349. var cStart = node.offset + 1, cEnd = node.offset + node.length - 1;
  8350. if (cStart < cEnd && offset >= cStart && offset <= cEnd) {
  8351. result.push(newRange(cStart, cEnd));
  8352. }
  8353. result.push(newRange(node.offset, node.offset + node.length));
  8354. break;
  8355. case 'number':
  8356. case 'boolean':
  8357. case 'null':
  8358. case 'property':
  8359. result.push(newRange(node.offset, node.offset + node.length));
  8360. break;
  8361. }
  8362. if (node.type === 'property' || node.parent && node.parent.type === 'array') {
  8363. var afterCommaOffset = getOffsetAfterNextToken(node.offset + node.length, 5 /* CommaToken */);
  8364. if (afterCommaOffset !== -1) {
  8365. result.push(newRange(node.offset, afterCommaOffset));
  8366. }
  8367. }
  8368. node = node.parent;
  8369. }
  8370. var current = undefined;
  8371. for (var index = result.length - 1; index >= 0; index--) {
  8372. current = jsonLanguageTypes_1.SelectionRange.create(result[index], current);
  8373. }
  8374. if (!current) {
  8375. current = jsonLanguageTypes_1.SelectionRange.create(jsonLanguageTypes_1.Range.create(position, position));
  8376. }
  8377. return current;
  8378. }
  8379. function newRange(start, end) {
  8380. return jsonLanguageTypes_1.Range.create(document.positionAt(start), document.positionAt(end));
  8381. }
  8382. var scanner = jsonc_parser_1.createScanner(document.getText(), true);
  8383. function getOffsetAfterNextToken(offset, expectedToken) {
  8384. scanner.setPosition(offset);
  8385. var token = scanner.scan();
  8386. if (token === expectedToken) {
  8387. return scanner.getTokenOffset() + scanner.getTokenLength();
  8388. }
  8389. return -1;
  8390. }
  8391. return positions.map(getSelectionRange);
  8392. }
  8393. exports.getSelectionRanges = getSelectionRanges;
  8394. });
  8395. /*---------------------------------------------------------------------------------------------
  8396. * Copyright (c) Microsoft Corporation. All rights reserved.
  8397. * Licensed under the MIT License. See License.txt in the project root for license information.
  8398. *--------------------------------------------------------------------------------------------*/
  8399. (function (factory) {
  8400. if (typeof module === "object" && typeof module.exports === "object") {
  8401. var v = factory(require, exports);
  8402. if (v !== undefined) module.exports = v;
  8403. }
  8404. else if (typeof define === "function" && define.amd) {
  8405. define('vscode-json-languageservice/services/jsonLinks',["require", "exports", "../jsonLanguageTypes"], factory);
  8406. }
  8407. })(function (require, exports) {
  8408. "use strict";
  8409. Object.defineProperty(exports, "__esModule", { value: true });
  8410. exports.findLinks = void 0;
  8411. var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
  8412. function findLinks(document, doc) {
  8413. var links = [];
  8414. doc.visit(function (node) {
  8415. var _a;
  8416. if (node.type === "property" && node.keyNode.value === "$ref" && ((_a = node.valueNode) === null || _a === void 0 ? void 0 : _a.type) === 'string') {
  8417. var path = node.valueNode.value;
  8418. var targetNode = findTargetNode(doc, path);
  8419. if (targetNode) {
  8420. var targetPos = document.positionAt(targetNode.offset);
  8421. links.push({
  8422. target: document.uri + "#" + (targetPos.line + 1) + "," + (targetPos.character + 1),
  8423. range: createRange(document, node.valueNode)
  8424. });
  8425. }
  8426. }
  8427. return true;
  8428. });
  8429. return Promise.resolve(links);
  8430. }
  8431. exports.findLinks = findLinks;
  8432. function createRange(document, node) {
  8433. return jsonLanguageTypes_1.Range.create(document.positionAt(node.offset + 1), document.positionAt(node.offset + node.length - 1));
  8434. }
  8435. function findTargetNode(doc, path) {
  8436. var tokens = parseJSONPointer(path);
  8437. if (!tokens) {
  8438. return null;
  8439. }
  8440. return findNode(tokens, doc.root);
  8441. }
  8442. function findNode(pointer, node) {
  8443. if (!node) {
  8444. return null;
  8445. }
  8446. if (pointer.length === 0) {
  8447. return node;
  8448. }
  8449. var token = pointer.shift();
  8450. if (node && node.type === 'object') {
  8451. var propertyNode = node.properties.find(function (propertyNode) { return propertyNode.keyNode.value === token; });
  8452. if (!propertyNode) {
  8453. return null;
  8454. }
  8455. return findNode(pointer, propertyNode.valueNode);
  8456. }
  8457. else if (node && node.type === 'array') {
  8458. if (token.match(/^(0|[1-9][0-9]*)$/)) {
  8459. var index = Number.parseInt(token);
  8460. var arrayItem = node.items[index];
  8461. if (!arrayItem) {
  8462. return null;
  8463. }
  8464. return findNode(pointer, arrayItem);
  8465. }
  8466. }
  8467. return null;
  8468. }
  8469. function parseJSONPointer(path) {
  8470. if (path === "#") {
  8471. return [];
  8472. }
  8473. if (path[0] !== '#' || path[1] !== '/') {
  8474. return null;
  8475. }
  8476. return path.substring(2).split(/\//).map(unescape);
  8477. }
  8478. function unescape(str) {
  8479. return str.replace(/~1/g, '/').replace(/~0/g, '~');
  8480. }
  8481. });
  8482. /*---------------------------------------------------------------------------------------------
  8483. * Copyright (c) Microsoft Corporation. All rights reserved.
  8484. * Licensed under the MIT License. See License.txt in the project root for license information.
  8485. *--------------------------------------------------------------------------------------------*/
  8486. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  8487. if (k2 === undefined) k2 = k;
  8488. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  8489. }) : (function(o, m, k, k2) {
  8490. if (k2 === undefined) k2 = k;
  8491. o[k2] = m[k];
  8492. }));
  8493. var __exportStar = (this && this.__exportStar) || function(m, exports) {
  8494. for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
  8495. };
  8496. (function (factory) {
  8497. if (typeof module === "object" && typeof module.exports === "object") {
  8498. var v = factory(require, exports);
  8499. if (v !== undefined) module.exports = v;
  8500. }
  8501. else if (typeof define === "function" && define.amd) {
  8502. define('vscode-json-languageservice/jsonLanguageService',["require", "exports", "./services/jsonCompletion", "./services/jsonHover", "./services/jsonValidation", "./services/jsonDocumentSymbols", "./parser/jsonParser", "./services/configuration", "./services/jsonSchemaService", "./services/jsonFolding", "./services/jsonSelectionRanges", "jsonc-parser", "./jsonLanguageTypes", "./services/jsonLinks", "./jsonLanguageTypes"], factory);
  8503. }
  8504. })(function (require, exports) {
  8505. "use strict";
  8506. Object.defineProperty(exports, "__esModule", { value: true });
  8507. exports.getLanguageService = void 0;
  8508. var jsonCompletion_1 = require("./services/jsonCompletion");
  8509. var jsonHover_1 = require("./services/jsonHover");
  8510. var jsonValidation_1 = require("./services/jsonValidation");
  8511. var jsonDocumentSymbols_1 = require("./services/jsonDocumentSymbols");
  8512. var jsonParser_1 = require("./parser/jsonParser");
  8513. var configuration_1 = require("./services/configuration");
  8514. var jsonSchemaService_1 = require("./services/jsonSchemaService");
  8515. var jsonFolding_1 = require("./services/jsonFolding");
  8516. var jsonSelectionRanges_1 = require("./services/jsonSelectionRanges");
  8517. var jsonc_parser_1 = require("jsonc-parser");
  8518. var jsonLanguageTypes_1 = require("./jsonLanguageTypes");
  8519. var jsonLinks_1 = require("./services/jsonLinks");
  8520. __exportStar(require("./jsonLanguageTypes"), exports);
  8521. function getLanguageService(params) {
  8522. var promise = params.promiseConstructor || Promise;
  8523. var jsonSchemaService = new jsonSchemaService_1.JSONSchemaService(params.schemaRequestService, params.workspaceContext, promise);
  8524. jsonSchemaService.setSchemaContributions(configuration_1.schemaContributions);
  8525. var jsonCompletion = new jsonCompletion_1.JSONCompletion(jsonSchemaService, params.contributions, promise, params.clientCapabilities);
  8526. var jsonHover = new jsonHover_1.JSONHover(jsonSchemaService, params.contributions, promise);
  8527. var jsonDocumentSymbols = new jsonDocumentSymbols_1.JSONDocumentSymbols(jsonSchemaService);
  8528. var jsonValidation = new jsonValidation_1.JSONValidation(jsonSchemaService, promise);
  8529. return {
  8530. configure: function (settings) {
  8531. jsonSchemaService.clearExternalSchemas();
  8532. if (settings.schemas) {
  8533. settings.schemas.forEach(function (settings) {
  8534. jsonSchemaService.registerExternalSchema(settings.uri, settings.fileMatch, settings.schema);
  8535. });
  8536. }
  8537. jsonValidation.configure(settings);
  8538. },
  8539. resetSchema: function (uri) { return jsonSchemaService.onResourceChange(uri); },
  8540. doValidation: jsonValidation.doValidation.bind(jsonValidation),
  8541. parseJSONDocument: function (document) { return jsonParser_1.parse(document, { collectComments: true }); },
  8542. newJSONDocument: function (root, diagnostics) { return jsonParser_1.newJSONDocument(root, diagnostics); },
  8543. getMatchingSchemas: jsonSchemaService.getMatchingSchemas.bind(jsonSchemaService),
  8544. doResolve: jsonCompletion.doResolve.bind(jsonCompletion),
  8545. doComplete: jsonCompletion.doComplete.bind(jsonCompletion),
  8546. findDocumentSymbols: jsonDocumentSymbols.findDocumentSymbols.bind(jsonDocumentSymbols),
  8547. findDocumentSymbols2: jsonDocumentSymbols.findDocumentSymbols2.bind(jsonDocumentSymbols),
  8548. findDocumentColors: jsonDocumentSymbols.findDocumentColors.bind(jsonDocumentSymbols),
  8549. getColorPresentations: jsonDocumentSymbols.getColorPresentations.bind(jsonDocumentSymbols),
  8550. doHover: jsonHover.doHover.bind(jsonHover),
  8551. getFoldingRanges: jsonFolding_1.getFoldingRanges,
  8552. getSelectionRanges: jsonSelectionRanges_1.getSelectionRanges,
  8553. findDefinition: function () { return Promise.resolve([]); },
  8554. findLinks: jsonLinks_1.findLinks,
  8555. format: function (d, r, o) {
  8556. var range = undefined;
  8557. if (r) {
  8558. var offset = d.offsetAt(r.start);
  8559. var length = d.offsetAt(r.end) - offset;
  8560. range = { offset: offset, length: length };
  8561. }
  8562. var options = { tabSize: o ? o.tabSize : 4, insertSpaces: (o === null || o === void 0 ? void 0 : o.insertSpaces) === true, insertFinalNewline: (o === null || o === void 0 ? void 0 : o.insertFinalNewline) === true, eol: '\n' };
  8563. return jsonc_parser_1.format(d.getText(), range, options).map(function (e) {
  8564. return jsonLanguageTypes_1.TextEdit.replace(jsonLanguageTypes_1.Range.create(d.positionAt(e.offset), d.positionAt(e.offset + e.length)), e.content);
  8565. });
  8566. }
  8567. };
  8568. }
  8569. exports.getLanguageService = getLanguageService;
  8570. });
  8571. define('vscode-json-languageservice', ['vscode-json-languageservice/jsonLanguageService'], function (main) { return main; });
  8572. /*---------------------------------------------------------------------------------------------
  8573. * Copyright (c) Microsoft Corporation. All rights reserved.
  8574. * Licensed under the MIT License. See License.txt in the project root for license information.
  8575. *--------------------------------------------------------------------------------------------*/
  8576. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  8577. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  8578. return new (P || (P = Promise))(function (resolve, reject) {
  8579. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  8580. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  8581. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  8582. step((generator = generator.apply(thisArg, _arguments || [])).next());
  8583. });
  8584. };
  8585. var __generator = (this && this.__generator) || function (thisArg, body) {
  8586. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  8587. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  8588. function verb(n) { return function (v) { return step([n, v]); }; }
  8589. function step(op) {
  8590. if (f) throw new TypeError("Generator is already executing.");
  8591. while (_) try {
  8592. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  8593. if (y = 0, t) op = [op[0] & 2, t.value];
  8594. switch (op[0]) {
  8595. case 0: case 1: t = op; break;
  8596. case 4: _.label++; return { value: op[1], done: false };
  8597. case 5: _.label++; y = op[1]; op = [0]; continue;
  8598. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  8599. default:
  8600. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  8601. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  8602. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  8603. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  8604. if (t[2]) _.ops.pop();
  8605. _.trys.pop(); continue;
  8606. }
  8607. op = body.call(thisArg, _);
  8608. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  8609. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  8610. }
  8611. };
  8612. define('vs/language/json/jsonWorker',["require", "exports", "vscode-json-languageservice", "vscode-uri"], function (require, exports, jsonService, vscode_uri_1) {
  8613. "use strict";
  8614. Object.defineProperty(exports, "__esModule", { value: true });
  8615. exports.create = exports.JSONWorker = void 0;
  8616. var defaultSchemaRequestService;
  8617. if (typeof fetch !== 'undefined') {
  8618. defaultSchemaRequestService = function (url) {
  8619. return fetch(url).then(function (response) { return response.text(); });
  8620. };
  8621. }
  8622. var JSONWorker = /** @class */ (function () {
  8623. function JSONWorker(ctx, createData) {
  8624. this._ctx = ctx;
  8625. this._languageSettings = createData.languageSettings;
  8626. this._languageId = createData.languageId;
  8627. this._languageService = jsonService.getLanguageService({
  8628. workspaceContext: {
  8629. resolveRelativePath: function (relativePath, resource) {
  8630. var base = resource.substr(0, resource.lastIndexOf('/') + 1);
  8631. return resolvePath(base, relativePath);
  8632. }
  8633. },
  8634. schemaRequestService: createData.enableSchemaRequest && defaultSchemaRequestService
  8635. });
  8636. this._languageService.configure(this._languageSettings);
  8637. }
  8638. JSONWorker.prototype.doValidation = function (uri) {
  8639. return __awaiter(this, void 0, void 0, function () {
  8640. var document, jsonDocument;
  8641. return __generator(this, function (_a) {
  8642. document = this._getTextDocument(uri);
  8643. if (document) {
  8644. jsonDocument = this._languageService.parseJSONDocument(document);
  8645. return [2 /*return*/, this._languageService.doValidation(document, jsonDocument, this._languageSettings)];
  8646. }
  8647. return [2 /*return*/, Promise.resolve([])];
  8648. });
  8649. });
  8650. };
  8651. JSONWorker.prototype.doComplete = function (uri, position) {
  8652. return __awaiter(this, void 0, void 0, function () {
  8653. var document, jsonDocument;
  8654. return __generator(this, function (_a) {
  8655. document = this._getTextDocument(uri);
  8656. jsonDocument = this._languageService.parseJSONDocument(document);
  8657. return [2 /*return*/, this._languageService.doComplete(document, position, jsonDocument)];
  8658. });
  8659. });
  8660. };
  8661. JSONWorker.prototype.doResolve = function (item) {
  8662. return __awaiter(this, void 0, void 0, function () {
  8663. return __generator(this, function (_a) {
  8664. return [2 /*return*/, this._languageService.doResolve(item)];
  8665. });
  8666. });
  8667. };
  8668. JSONWorker.prototype.doHover = function (uri, position) {
  8669. return __awaiter(this, void 0, void 0, function () {
  8670. var document, jsonDocument;
  8671. return __generator(this, function (_a) {
  8672. document = this._getTextDocument(uri);
  8673. jsonDocument = this._languageService.parseJSONDocument(document);
  8674. return [2 /*return*/, this._languageService.doHover(document, position, jsonDocument)];
  8675. });
  8676. });
  8677. };
  8678. JSONWorker.prototype.format = function (uri, range, options) {
  8679. return __awaiter(this, void 0, void 0, function () {
  8680. var document, textEdits;
  8681. return __generator(this, function (_a) {
  8682. document = this._getTextDocument(uri);
  8683. textEdits = this._languageService.format(document, range, options);
  8684. return [2 /*return*/, Promise.resolve(textEdits)];
  8685. });
  8686. });
  8687. };
  8688. JSONWorker.prototype.resetSchema = function (uri) {
  8689. return __awaiter(this, void 0, void 0, function () {
  8690. return __generator(this, function (_a) {
  8691. return [2 /*return*/, Promise.resolve(this._languageService.resetSchema(uri))];
  8692. });
  8693. });
  8694. };
  8695. JSONWorker.prototype.findDocumentSymbols = function (uri) {
  8696. return __awaiter(this, void 0, void 0, function () {
  8697. var document, jsonDocument, symbols;
  8698. return __generator(this, function (_a) {
  8699. document = this._getTextDocument(uri);
  8700. jsonDocument = this._languageService.parseJSONDocument(document);
  8701. symbols = this._languageService.findDocumentSymbols(document, jsonDocument);
  8702. return [2 /*return*/, Promise.resolve(symbols)];
  8703. });
  8704. });
  8705. };
  8706. JSONWorker.prototype.findDocumentColors = function (uri) {
  8707. return __awaiter(this, void 0, void 0, function () {
  8708. var document, jsonDocument, colorSymbols;
  8709. return __generator(this, function (_a) {
  8710. document = this._getTextDocument(uri);
  8711. jsonDocument = this._languageService.parseJSONDocument(document);
  8712. colorSymbols = this._languageService.findDocumentColors(document, jsonDocument);
  8713. return [2 /*return*/, Promise.resolve(colorSymbols)];
  8714. });
  8715. });
  8716. };
  8717. JSONWorker.prototype.getColorPresentations = function (uri, color, range) {
  8718. return __awaiter(this, void 0, void 0, function () {
  8719. var document, jsonDocument, colorPresentations;
  8720. return __generator(this, function (_a) {
  8721. document = this._getTextDocument(uri);
  8722. jsonDocument = this._languageService.parseJSONDocument(document);
  8723. colorPresentations = this._languageService.getColorPresentations(document, jsonDocument, color, range);
  8724. return [2 /*return*/, Promise.resolve(colorPresentations)];
  8725. });
  8726. });
  8727. };
  8728. JSONWorker.prototype.getFoldingRanges = function (uri, context) {
  8729. return __awaiter(this, void 0, void 0, function () {
  8730. var document, ranges;
  8731. return __generator(this, function (_a) {
  8732. document = this._getTextDocument(uri);
  8733. ranges = this._languageService.getFoldingRanges(document, context);
  8734. return [2 /*return*/, Promise.resolve(ranges)];
  8735. });
  8736. });
  8737. };
  8738. JSONWorker.prototype.getSelectionRanges = function (uri, positions) {
  8739. return __awaiter(this, void 0, void 0, function () {
  8740. var document, jsonDocument, ranges;
  8741. return __generator(this, function (_a) {
  8742. document = this._getTextDocument(uri);
  8743. jsonDocument = this._languageService.parseJSONDocument(document);
  8744. ranges = this._languageService.getSelectionRanges(document, positions, jsonDocument);
  8745. return [2 /*return*/, Promise.resolve(ranges)];
  8746. });
  8747. });
  8748. };
  8749. JSONWorker.prototype._getTextDocument = function (uri) {
  8750. var models = this._ctx.getMirrorModels();
  8751. for (var _i = 0, models_1 = models; _i < models_1.length; _i++) {
  8752. var model = models_1[_i];
  8753. if (model.uri.toString() === uri) {
  8754. return jsonService.TextDocument.create(uri, this._languageId, model.version, model.getValue());
  8755. }
  8756. }
  8757. return null;
  8758. };
  8759. return JSONWorker;
  8760. }());
  8761. exports.JSONWorker = JSONWorker;
  8762. // URI path utilities, will (hopefully) move to vscode-uri
  8763. var Slash = '/'.charCodeAt(0);
  8764. var Dot = '.'.charCodeAt(0);
  8765. function isAbsolutePath(path) {
  8766. return path.charCodeAt(0) === Slash;
  8767. }
  8768. function resolvePath(uriString, path) {
  8769. if (isAbsolutePath(path)) {
  8770. var uri = vscode_uri_1.URI.parse(uriString);
  8771. var parts = path.split('/');
  8772. return uri.with({ path: normalizePath(parts) }).toString();
  8773. }
  8774. return joinPath(uriString, path);
  8775. }
  8776. function normalizePath(parts) {
  8777. var newParts = [];
  8778. for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
  8779. var part = parts_1[_i];
  8780. if (part.length === 0 || (part.length === 1 && part.charCodeAt(0) === Dot)) {
  8781. // ignore
  8782. }
  8783. else if (part.length === 2 && part.charCodeAt(0) === Dot && part.charCodeAt(1) === Dot) {
  8784. newParts.pop();
  8785. }
  8786. else {
  8787. newParts.push(part);
  8788. }
  8789. }
  8790. if (parts.length > 1 && parts[parts.length - 1].length === 0) {
  8791. newParts.push('');
  8792. }
  8793. var res = newParts.join('/');
  8794. if (parts[0].length === 0) {
  8795. res = '/' + res;
  8796. }
  8797. return res;
  8798. }
  8799. function joinPath(uriString) {
  8800. var paths = [];
  8801. for (var _i = 1; _i < arguments.length; _i++) {
  8802. paths[_i - 1] = arguments[_i];
  8803. }
  8804. var uri = vscode_uri_1.URI.parse(uriString);
  8805. var parts = uri.path.split('/');
  8806. for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) {
  8807. var path = paths_1[_a];
  8808. parts.push.apply(parts, path.split('/'));
  8809. }
  8810. return uri.with({ path: normalizePath(parts) }).toString();
  8811. }
  8812. function create(ctx, createData) {
  8813. return new JSONWorker(ctx, createData);
  8814. }
  8815. exports.create = create;
  8816. });