jsonMode.js 451 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Licensed under the MIT License. See License.txt in the project root for license information.
  4. *--------------------------------------------------------------------------------------------*/
  5. define('vs/language/json/workerManager',["require", "exports", "./fillers/monaco-editor-core"], function (require, exports, monaco_editor_core_1) {
  6. "use strict";
  7. Object.defineProperty(exports, "__esModule", { value: true });
  8. exports.WorkerManager = void 0;
  9. var STOP_WHEN_IDLE_FOR = 2 * 60 * 1000; // 2min
  10. var WorkerManager = /** @class */ (function () {
  11. function WorkerManager(defaults) {
  12. var _this = this;
  13. this._defaults = defaults;
  14. this._worker = null;
  15. this._idleCheckInterval = setInterval(function () { return _this._checkIfIdle(); }, 30 * 1000);
  16. this._lastUsedTime = 0;
  17. this._configChangeListener = this._defaults.onDidChange(function () { return _this._stopWorker(); });
  18. }
  19. WorkerManager.prototype._stopWorker = function () {
  20. if (this._worker) {
  21. this._worker.dispose();
  22. this._worker = null;
  23. }
  24. this._client = null;
  25. };
  26. WorkerManager.prototype.dispose = function () {
  27. clearInterval(this._idleCheckInterval);
  28. this._configChangeListener.dispose();
  29. this._stopWorker();
  30. };
  31. WorkerManager.prototype._checkIfIdle = function () {
  32. if (!this._worker) {
  33. return;
  34. }
  35. var timePassedSinceLastUsed = Date.now() - this._lastUsedTime;
  36. if (timePassedSinceLastUsed > STOP_WHEN_IDLE_FOR) {
  37. this._stopWorker();
  38. }
  39. };
  40. WorkerManager.prototype._getClient = function () {
  41. this._lastUsedTime = Date.now();
  42. if (!this._client) {
  43. this._worker = monaco_editor_core_1.editor.createWebWorker({
  44. // module that exports the create() method and returns a `JSONWorker` instance
  45. moduleId: 'vs/language/json/jsonWorker',
  46. label: this._defaults.languageId,
  47. // passed in to the create() method
  48. createData: {
  49. languageSettings: this._defaults.diagnosticsOptions,
  50. languageId: this._defaults.languageId,
  51. enableSchemaRequest: this._defaults.diagnosticsOptions.enableSchemaRequest
  52. }
  53. });
  54. this._client = this._worker.getProxy();
  55. }
  56. return this._client;
  57. };
  58. WorkerManager.prototype.getLanguageServiceWorker = function () {
  59. var _this = this;
  60. var resources = [];
  61. for (var _i = 0; _i < arguments.length; _i++) {
  62. resources[_i] = arguments[_i];
  63. }
  64. var _client;
  65. return this._getClient()
  66. .then(function (client) {
  67. _client = client;
  68. })
  69. .then(function (_) {
  70. return _this._worker.withSyncedResources(resources);
  71. })
  72. .then(function (_) { return _client; });
  73. };
  74. return WorkerManager;
  75. }());
  76. exports.WorkerManager = WorkerManager;
  77. });
  78. (function (factory) {
  79. if (typeof module === "object" && typeof module.exports === "object") {
  80. var v = factory(require, exports);
  81. if (v !== undefined) module.exports = v;
  82. }
  83. else if (typeof define === "function" && define.amd) {
  84. define('jsonc-parser/impl/scanner',["require", "exports"], factory);
  85. }
  86. })(function (require, exports) {
  87. /*---------------------------------------------------------------------------------------------
  88. * Copyright (c) Microsoft Corporation. All rights reserved.
  89. * Licensed under the MIT License. See License.txt in the project root for license information.
  90. *--------------------------------------------------------------------------------------------*/
  91. 'use strict';
  92. Object.defineProperty(exports, "__esModule", { value: true });
  93. exports.createScanner = void 0;
  94. /**
  95. * Creates a JSON scanner on the given text.
  96. * If ignoreTrivia is set, whitespaces or comments are ignored.
  97. */
  98. function createScanner(text, ignoreTrivia) {
  99. if (ignoreTrivia === void 0) { ignoreTrivia = false; }
  100. var len = text.length;
  101. var pos = 0, value = '', tokenOffset = 0, token = 16 /* Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* None */;
  102. function scanHexDigits(count, exact) {
  103. var digits = 0;
  104. var value = 0;
  105. while (digits < count || !exact) {
  106. var ch = text.charCodeAt(pos);
  107. if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) {
  108. value = value * 16 + ch - 48 /* _0 */;
  109. }
  110. else if (ch >= 65 /* A */ && ch <= 70 /* F */) {
  111. value = value * 16 + ch - 65 /* A */ + 10;
  112. }
  113. else if (ch >= 97 /* a */ && ch <= 102 /* f */) {
  114. value = value * 16 + ch - 97 /* a */ + 10;
  115. }
  116. else {
  117. break;
  118. }
  119. pos++;
  120. digits++;
  121. }
  122. if (digits < count) {
  123. value = -1;
  124. }
  125. return value;
  126. }
  127. function setPosition(newPosition) {
  128. pos = newPosition;
  129. value = '';
  130. tokenOffset = 0;
  131. token = 16 /* Unknown */;
  132. scanError = 0 /* None */;
  133. }
  134. function scanNumber() {
  135. var start = pos;
  136. if (text.charCodeAt(pos) === 48 /* _0 */) {
  137. pos++;
  138. }
  139. else {
  140. pos++;
  141. while (pos < text.length && isDigit(text.charCodeAt(pos))) {
  142. pos++;
  143. }
  144. }
  145. if (pos < text.length && text.charCodeAt(pos) === 46 /* dot */) {
  146. pos++;
  147. if (pos < text.length && isDigit(text.charCodeAt(pos))) {
  148. pos++;
  149. while (pos < text.length && isDigit(text.charCodeAt(pos))) {
  150. pos++;
  151. }
  152. }
  153. else {
  154. scanError = 3 /* UnexpectedEndOfNumber */;
  155. return text.substring(start, pos);
  156. }
  157. }
  158. var end = pos;
  159. if (pos < text.length && (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */)) {
  160. pos++;
  161. if (pos < text.length && text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) {
  162. pos++;
  163. }
  164. if (pos < text.length && isDigit(text.charCodeAt(pos))) {
  165. pos++;
  166. while (pos < text.length && isDigit(text.charCodeAt(pos))) {
  167. pos++;
  168. }
  169. end = pos;
  170. }
  171. else {
  172. scanError = 3 /* UnexpectedEndOfNumber */;
  173. }
  174. }
  175. return text.substring(start, end);
  176. }
  177. function scanString() {
  178. var result = '', start = pos;
  179. while (true) {
  180. if (pos >= len) {
  181. result += text.substring(start, pos);
  182. scanError = 2 /* UnexpectedEndOfString */;
  183. break;
  184. }
  185. var ch = text.charCodeAt(pos);
  186. if (ch === 34 /* doubleQuote */) {
  187. result += text.substring(start, pos);
  188. pos++;
  189. break;
  190. }
  191. if (ch === 92 /* backslash */) {
  192. result += text.substring(start, pos);
  193. pos++;
  194. if (pos >= len) {
  195. scanError = 2 /* UnexpectedEndOfString */;
  196. break;
  197. }
  198. var ch2 = text.charCodeAt(pos++);
  199. switch (ch2) {
  200. case 34 /* doubleQuote */:
  201. result += '\"';
  202. break;
  203. case 92 /* backslash */:
  204. result += '\\';
  205. break;
  206. case 47 /* slash */:
  207. result += '/';
  208. break;
  209. case 98 /* b */:
  210. result += '\b';
  211. break;
  212. case 102 /* f */:
  213. result += '\f';
  214. break;
  215. case 110 /* n */:
  216. result += '\n';
  217. break;
  218. case 114 /* r */:
  219. result += '\r';
  220. break;
  221. case 116 /* t */:
  222. result += '\t';
  223. break;
  224. case 117 /* u */:
  225. var ch3 = scanHexDigits(4, true);
  226. if (ch3 >= 0) {
  227. result += String.fromCharCode(ch3);
  228. }
  229. else {
  230. scanError = 4 /* InvalidUnicode */;
  231. }
  232. break;
  233. default:
  234. scanError = 5 /* InvalidEscapeCharacter */;
  235. }
  236. start = pos;
  237. continue;
  238. }
  239. if (ch >= 0 && ch <= 0x1f) {
  240. if (isLineBreak(ch)) {
  241. result += text.substring(start, pos);
  242. scanError = 2 /* UnexpectedEndOfString */;
  243. break;
  244. }
  245. else {
  246. scanError = 6 /* InvalidCharacter */;
  247. // mark as error but continue with string
  248. }
  249. }
  250. pos++;
  251. }
  252. return result;
  253. }
  254. function scanNext() {
  255. value = '';
  256. scanError = 0 /* None */;
  257. tokenOffset = pos;
  258. lineStartOffset = lineNumber;
  259. prevTokenLineStartOffset = tokenLineStartOffset;
  260. if (pos >= len) {
  261. // at the end
  262. tokenOffset = len;
  263. return token = 17 /* EOF */;
  264. }
  265. var code = text.charCodeAt(pos);
  266. // trivia: whitespace
  267. if (isWhiteSpace(code)) {
  268. do {
  269. pos++;
  270. value += String.fromCharCode(code);
  271. code = text.charCodeAt(pos);
  272. } while (isWhiteSpace(code));
  273. return token = 15 /* Trivia */;
  274. }
  275. // trivia: newlines
  276. if (isLineBreak(code)) {
  277. pos++;
  278. value += String.fromCharCode(code);
  279. if (code === 13 /* carriageReturn */ && text.charCodeAt(pos) === 10 /* lineFeed */) {
  280. pos++;
  281. value += '\n';
  282. }
  283. lineNumber++;
  284. tokenLineStartOffset = pos;
  285. return token = 14 /* LineBreakTrivia */;
  286. }
  287. switch (code) {
  288. // tokens: []{}:,
  289. case 123 /* openBrace */:
  290. pos++;
  291. return token = 1 /* OpenBraceToken */;
  292. case 125 /* closeBrace */:
  293. pos++;
  294. return token = 2 /* CloseBraceToken */;
  295. case 91 /* openBracket */:
  296. pos++;
  297. return token = 3 /* OpenBracketToken */;
  298. case 93 /* closeBracket */:
  299. pos++;
  300. return token = 4 /* CloseBracketToken */;
  301. case 58 /* colon */:
  302. pos++;
  303. return token = 6 /* ColonToken */;
  304. case 44 /* comma */:
  305. pos++;
  306. return token = 5 /* CommaToken */;
  307. // strings
  308. case 34 /* doubleQuote */:
  309. pos++;
  310. value = scanString();
  311. return token = 10 /* StringLiteral */;
  312. // comments
  313. case 47 /* slash */:
  314. var start = pos - 1;
  315. // Single-line comment
  316. if (text.charCodeAt(pos + 1) === 47 /* slash */) {
  317. pos += 2;
  318. while (pos < len) {
  319. if (isLineBreak(text.charCodeAt(pos))) {
  320. break;
  321. }
  322. pos++;
  323. }
  324. value = text.substring(start, pos);
  325. return token = 12 /* LineCommentTrivia */;
  326. }
  327. // Multi-line comment
  328. if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
  329. pos += 2;
  330. var safeLength = len - 1; // For lookahead.
  331. var commentClosed = false;
  332. while (pos < safeLength) {
  333. var ch = text.charCodeAt(pos);
  334. if (ch === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
  335. pos += 2;
  336. commentClosed = true;
  337. break;
  338. }
  339. pos++;
  340. if (isLineBreak(ch)) {
  341. if (ch === 13 /* carriageReturn */ && text.charCodeAt(pos) === 10 /* lineFeed */) {
  342. pos++;
  343. }
  344. lineNumber++;
  345. tokenLineStartOffset = pos;
  346. }
  347. }
  348. if (!commentClosed) {
  349. pos++;
  350. scanError = 1 /* UnexpectedEndOfComment */;
  351. }
  352. value = text.substring(start, pos);
  353. return token = 13 /* BlockCommentTrivia */;
  354. }
  355. // just a single slash
  356. value += String.fromCharCode(code);
  357. pos++;
  358. return token = 16 /* Unknown */;
  359. // numbers
  360. case 45 /* minus */:
  361. value += String.fromCharCode(code);
  362. pos++;
  363. if (pos === len || !isDigit(text.charCodeAt(pos))) {
  364. return token = 16 /* Unknown */;
  365. }
  366. // found a minus, followed by a number so
  367. // we fall through to proceed with scanning
  368. // numbers
  369. case 48 /* _0 */:
  370. case 49 /* _1 */:
  371. case 50 /* _2 */:
  372. case 51 /* _3 */:
  373. case 52 /* _4 */:
  374. case 53 /* _5 */:
  375. case 54 /* _6 */:
  376. case 55 /* _7 */:
  377. case 56 /* _8 */:
  378. case 57 /* _9 */:
  379. value += scanNumber();
  380. return token = 11 /* NumericLiteral */;
  381. // literals and unknown symbols
  382. default:
  383. // is a literal? Read the full word.
  384. while (pos < len && isUnknownContentCharacter(code)) {
  385. pos++;
  386. code = text.charCodeAt(pos);
  387. }
  388. if (tokenOffset !== pos) {
  389. value = text.substring(tokenOffset, pos);
  390. // keywords: true, false, null
  391. switch (value) {
  392. case 'true': return token = 8 /* TrueKeyword */;
  393. case 'false': return token = 9 /* FalseKeyword */;
  394. case 'null': return token = 7 /* NullKeyword */;
  395. }
  396. return token = 16 /* Unknown */;
  397. }
  398. // some
  399. value += String.fromCharCode(code);
  400. pos++;
  401. return token = 16 /* Unknown */;
  402. }
  403. }
  404. function isUnknownContentCharacter(code) {
  405. if (isWhiteSpace(code) || isLineBreak(code)) {
  406. return false;
  407. }
  408. switch (code) {
  409. case 125 /* closeBrace */:
  410. case 93 /* closeBracket */:
  411. case 123 /* openBrace */:
  412. case 91 /* openBracket */:
  413. case 34 /* doubleQuote */:
  414. case 58 /* colon */:
  415. case 44 /* comma */:
  416. case 47 /* slash */:
  417. return false;
  418. }
  419. return true;
  420. }
  421. function scanNextNonTrivia() {
  422. var result;
  423. do {
  424. result = scanNext();
  425. } while (result >= 12 /* LineCommentTrivia */ && result <= 15 /* Trivia */);
  426. return result;
  427. }
  428. return {
  429. setPosition: setPosition,
  430. getPosition: function () { return pos; },
  431. scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
  432. getToken: function () { return token; },
  433. getTokenValue: function () { return value; },
  434. getTokenOffset: function () { return tokenOffset; },
  435. getTokenLength: function () { return pos - tokenOffset; },
  436. getTokenStartLine: function () { return lineStartOffset; },
  437. getTokenStartCharacter: function () { return tokenOffset - prevTokenLineStartOffset; },
  438. getTokenError: function () { return scanError; },
  439. };
  440. }
  441. exports.createScanner = createScanner;
  442. function isWhiteSpace(ch) {
  443. return ch === 32 /* space */ || ch === 9 /* tab */ || ch === 11 /* verticalTab */ || ch === 12 /* formFeed */ ||
  444. ch === 160 /* nonBreakingSpace */ || ch === 5760 /* ogham */ || ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
  445. ch === 8239 /* narrowNoBreakSpace */ || ch === 8287 /* mathematicalSpace */ || ch === 12288 /* ideographicSpace */ || ch === 65279 /* byteOrderMark */;
  446. }
  447. function isLineBreak(ch) {
  448. return ch === 10 /* lineFeed */ || ch === 13 /* carriageReturn */ || ch === 8232 /* lineSeparator */ || ch === 8233 /* paragraphSeparator */;
  449. }
  450. function isDigit(ch) {
  451. return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
  452. }
  453. });
  454. (function (factory) {
  455. if (typeof module === "object" && typeof module.exports === "object") {
  456. var v = factory(require, exports);
  457. if (v !== undefined) module.exports = v;
  458. }
  459. else if (typeof define === "function" && define.amd) {
  460. define('jsonc-parser/impl/format',["require", "exports", "./scanner"], factory);
  461. }
  462. })(function (require, exports) {
  463. /*---------------------------------------------------------------------------------------------
  464. * Copyright (c) Microsoft Corporation. All rights reserved.
  465. * Licensed under the MIT License. See License.txt in the project root for license information.
  466. *--------------------------------------------------------------------------------------------*/
  467. 'use strict';
  468. Object.defineProperty(exports, "__esModule", { value: true });
  469. exports.isEOL = exports.format = void 0;
  470. var scanner_1 = require("./scanner");
  471. function format(documentText, range, options) {
  472. var initialIndentLevel;
  473. var formatText;
  474. var formatTextStart;
  475. var rangeStart;
  476. var rangeEnd;
  477. if (range) {
  478. rangeStart = range.offset;
  479. rangeEnd = rangeStart + range.length;
  480. formatTextStart = rangeStart;
  481. while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {
  482. formatTextStart--;
  483. }
  484. var endOffset = rangeEnd;
  485. while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {
  486. endOffset++;
  487. }
  488. formatText = documentText.substring(formatTextStart, endOffset);
  489. initialIndentLevel = computeIndentLevel(formatText, options);
  490. }
  491. else {
  492. formatText = documentText;
  493. initialIndentLevel = 0;
  494. formatTextStart = 0;
  495. rangeStart = 0;
  496. rangeEnd = documentText.length;
  497. }
  498. var eol = getEOL(options, documentText);
  499. var lineBreak = false;
  500. var indentLevel = 0;
  501. var indentValue;
  502. if (options.insertSpaces) {
  503. indentValue = repeat(' ', options.tabSize || 4);
  504. }
  505. else {
  506. indentValue = '\t';
  507. }
  508. var scanner = scanner_1.createScanner(formatText, false);
  509. var hasError = false;
  510. function newLineAndIndent() {
  511. return eol + repeat(indentValue, initialIndentLevel + indentLevel);
  512. }
  513. function scanNext() {
  514. var token = scanner.scan();
  515. lineBreak = false;
  516. while (token === 15 /* Trivia */ || token === 14 /* LineBreakTrivia */) {
  517. lineBreak = lineBreak || (token === 14 /* LineBreakTrivia */);
  518. token = scanner.scan();
  519. }
  520. hasError = token === 16 /* Unknown */ || scanner.getTokenError() !== 0 /* None */;
  521. return token;
  522. }
  523. var editOperations = [];
  524. function addEdit(text, startOffset, endOffset) {
  525. if (!hasError && (!range || (startOffset < rangeEnd && endOffset > rangeStart)) && documentText.substring(startOffset, endOffset) !== text) {
  526. editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });
  527. }
  528. }
  529. var firstToken = scanNext();
  530. if (firstToken !== 17 /* EOF */) {
  531. var firstTokenStart = scanner.getTokenOffset() + formatTextStart;
  532. var initialIndent = repeat(indentValue, initialIndentLevel);
  533. addEdit(initialIndent, formatTextStart, firstTokenStart);
  534. }
  535. while (firstToken !== 17 /* EOF */) {
  536. var firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
  537. var secondToken = scanNext();
  538. var replaceContent = '';
  539. var needsLineBreak = false;
  540. while (!lineBreak && (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */)) {
  541. // comments on the same line: keep them on the same line, but ignore them otherwise
  542. var commentTokenStart = scanner.getTokenOffset() + formatTextStart;
  543. addEdit(' ', firstTokenEnd, commentTokenStart);
  544. firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
  545. needsLineBreak = secondToken === 12 /* LineCommentTrivia */;
  546. replaceContent = needsLineBreak ? newLineAndIndent() : '';
  547. secondToken = scanNext();
  548. }
  549. if (secondToken === 2 /* CloseBraceToken */) {
  550. if (firstToken !== 1 /* OpenBraceToken */) {
  551. indentLevel--;
  552. replaceContent = newLineAndIndent();
  553. }
  554. }
  555. else if (secondToken === 4 /* CloseBracketToken */) {
  556. if (firstToken !== 3 /* OpenBracketToken */) {
  557. indentLevel--;
  558. replaceContent = newLineAndIndent();
  559. }
  560. }
  561. else {
  562. switch (firstToken) {
  563. case 3 /* OpenBracketToken */:
  564. case 1 /* OpenBraceToken */:
  565. indentLevel++;
  566. replaceContent = newLineAndIndent();
  567. break;
  568. case 5 /* CommaToken */:
  569. case 12 /* LineCommentTrivia */:
  570. replaceContent = newLineAndIndent();
  571. break;
  572. case 13 /* BlockCommentTrivia */:
  573. if (lineBreak) {
  574. replaceContent = newLineAndIndent();
  575. }
  576. else if (!needsLineBreak) {
  577. // symbol following comment on the same line: keep on same line, separate with ' '
  578. replaceContent = ' ';
  579. }
  580. break;
  581. case 6 /* ColonToken */:
  582. if (!needsLineBreak) {
  583. replaceContent = ' ';
  584. }
  585. break;
  586. case 10 /* StringLiteral */:
  587. if (secondToken === 6 /* ColonToken */) {
  588. if (!needsLineBreak) {
  589. replaceContent = '';
  590. }
  591. break;
  592. }
  593. // fall through
  594. case 7 /* NullKeyword */:
  595. case 8 /* TrueKeyword */:
  596. case 9 /* FalseKeyword */:
  597. case 11 /* NumericLiteral */:
  598. case 2 /* CloseBraceToken */:
  599. case 4 /* CloseBracketToken */:
  600. if (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */) {
  601. if (!needsLineBreak) {
  602. replaceContent = ' ';
  603. }
  604. }
  605. else if (secondToken !== 5 /* CommaToken */ && secondToken !== 17 /* EOF */) {
  606. hasError = true;
  607. }
  608. break;
  609. case 16 /* Unknown */:
  610. hasError = true;
  611. break;
  612. }
  613. if (lineBreak && (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */)) {
  614. replaceContent = newLineAndIndent();
  615. }
  616. }
  617. if (secondToken === 17 /* EOF */) {
  618. replaceContent = options.insertFinalNewline ? eol : '';
  619. }
  620. var secondTokenStart = scanner.getTokenOffset() + formatTextStart;
  621. addEdit(replaceContent, firstTokenEnd, secondTokenStart);
  622. firstToken = secondToken;
  623. }
  624. return editOperations;
  625. }
  626. exports.format = format;
  627. function repeat(s, count) {
  628. var result = '';
  629. for (var i = 0; i < count; i++) {
  630. result += s;
  631. }
  632. return result;
  633. }
  634. function computeIndentLevel(content, options) {
  635. var i = 0;
  636. var nChars = 0;
  637. var tabSize = options.tabSize || 4;
  638. while (i < content.length) {
  639. var ch = content.charAt(i);
  640. if (ch === ' ') {
  641. nChars++;
  642. }
  643. else if (ch === '\t') {
  644. nChars += tabSize;
  645. }
  646. else {
  647. break;
  648. }
  649. i++;
  650. }
  651. return Math.floor(nChars / tabSize);
  652. }
  653. function getEOL(options, text) {
  654. for (var i = 0; i < text.length; i++) {
  655. var ch = text.charAt(i);
  656. if (ch === '\r') {
  657. if (i + 1 < text.length && text.charAt(i + 1) === '\n') {
  658. return '\r\n';
  659. }
  660. return '\r';
  661. }
  662. else if (ch === '\n') {
  663. return '\n';
  664. }
  665. }
  666. return (options && options.eol) || '\n';
  667. }
  668. function isEOL(text, offset) {
  669. return '\r\n'.indexOf(text.charAt(offset)) !== -1;
  670. }
  671. exports.isEOL = isEOL;
  672. });
  673. (function (factory) {
  674. if (typeof module === "object" && typeof module.exports === "object") {
  675. var v = factory(require, exports);
  676. if (v !== undefined) module.exports = v;
  677. }
  678. else if (typeof define === "function" && define.amd) {
  679. define('jsonc-parser/impl/parser',["require", "exports", "./scanner"], factory);
  680. }
  681. })(function (require, exports) {
  682. /*---------------------------------------------------------------------------------------------
  683. * Copyright (c) Microsoft Corporation. All rights reserved.
  684. * Licensed under the MIT License. See License.txt in the project root for license information.
  685. *--------------------------------------------------------------------------------------------*/
  686. 'use strict';
  687. Object.defineProperty(exports, "__esModule", { value: true });
  688. exports.getNodeType = exports.stripComments = exports.visit = exports.findNodeAtOffset = exports.contains = exports.getNodeValue = exports.getNodePath = exports.findNodeAtLocation = exports.parseTree = exports.parse = exports.getLocation = void 0;
  689. var scanner_1 = require("./scanner");
  690. var ParseOptions;
  691. (function (ParseOptions) {
  692. ParseOptions.DEFAULT = {
  693. allowTrailingComma: false
  694. };
  695. })(ParseOptions || (ParseOptions = {}));
  696. /**
  697. * 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.
  698. */
  699. function getLocation(text, position) {
  700. var segments = []; // strings or numbers
  701. var earlyReturnException = new Object();
  702. var previousNode = undefined;
  703. var previousNodeInst = {
  704. value: {},
  705. offset: 0,
  706. length: 0,
  707. type: 'object',
  708. parent: undefined
  709. };
  710. var isAtPropertyKey = false;
  711. function setPreviousNode(value, offset, length, type) {
  712. previousNodeInst.value = value;
  713. previousNodeInst.offset = offset;
  714. previousNodeInst.length = length;
  715. previousNodeInst.type = type;
  716. previousNodeInst.colonOffset = undefined;
  717. previousNode = previousNodeInst;
  718. }
  719. try {
  720. visit(text, {
  721. onObjectBegin: function (offset, length) {
  722. if (position <= offset) {
  723. throw earlyReturnException;
  724. }
  725. previousNode = undefined;
  726. isAtPropertyKey = position > offset;
  727. segments.push(''); // push a placeholder (will be replaced)
  728. },
  729. onObjectProperty: function (name, offset, length) {
  730. if (position < offset) {
  731. throw earlyReturnException;
  732. }
  733. setPreviousNode(name, offset, length, 'property');
  734. segments[segments.length - 1] = name;
  735. if (position <= offset + length) {
  736. throw earlyReturnException;
  737. }
  738. },
  739. onObjectEnd: function (offset, length) {
  740. if (position <= offset) {
  741. throw earlyReturnException;
  742. }
  743. previousNode = undefined;
  744. segments.pop();
  745. },
  746. onArrayBegin: function (offset, length) {
  747. if (position <= offset) {
  748. throw earlyReturnException;
  749. }
  750. previousNode = undefined;
  751. segments.push(0);
  752. },
  753. onArrayEnd: function (offset, length) {
  754. if (position <= offset) {
  755. throw earlyReturnException;
  756. }
  757. previousNode = undefined;
  758. segments.pop();
  759. },
  760. onLiteralValue: function (value, offset, length) {
  761. if (position < offset) {
  762. throw earlyReturnException;
  763. }
  764. setPreviousNode(value, offset, length, getNodeType(value));
  765. if (position <= offset + length) {
  766. throw earlyReturnException;
  767. }
  768. },
  769. onSeparator: function (sep, offset, length) {
  770. if (position <= offset) {
  771. throw earlyReturnException;
  772. }
  773. if (sep === ':' && previousNode && previousNode.type === 'property') {
  774. previousNode.colonOffset = offset;
  775. isAtPropertyKey = false;
  776. previousNode = undefined;
  777. }
  778. else if (sep === ',') {
  779. var last = segments[segments.length - 1];
  780. if (typeof last === 'number') {
  781. segments[segments.length - 1] = last + 1;
  782. }
  783. else {
  784. isAtPropertyKey = true;
  785. segments[segments.length - 1] = '';
  786. }
  787. previousNode = undefined;
  788. }
  789. }
  790. });
  791. }
  792. catch (e) {
  793. if (e !== earlyReturnException) {
  794. throw e;
  795. }
  796. }
  797. return {
  798. path: segments,
  799. previousNode: previousNode,
  800. isAtPropertyKey: isAtPropertyKey,
  801. matches: function (pattern) {
  802. var k = 0;
  803. for (var i = 0; k < pattern.length && i < segments.length; i++) {
  804. if (pattern[k] === segments[i] || pattern[k] === '*') {
  805. k++;
  806. }
  807. else if (pattern[k] !== '**') {
  808. return false;
  809. }
  810. }
  811. return k === pattern.length;
  812. }
  813. };
  814. }
  815. exports.getLocation = getLocation;
  816. /**
  817. * 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.
  818. * Therefore always check the errors list to find out if the input was valid.
  819. */
  820. function parse(text, errors, options) {
  821. if (errors === void 0) { errors = []; }
  822. if (options === void 0) { options = ParseOptions.DEFAULT; }
  823. var currentProperty = null;
  824. var currentParent = [];
  825. var previousParents = [];
  826. function onValue(value) {
  827. if (Array.isArray(currentParent)) {
  828. currentParent.push(value);
  829. }
  830. else if (currentProperty !== null) {
  831. currentParent[currentProperty] = value;
  832. }
  833. }
  834. var visitor = {
  835. onObjectBegin: function () {
  836. var object = {};
  837. onValue(object);
  838. previousParents.push(currentParent);
  839. currentParent = object;
  840. currentProperty = null;
  841. },
  842. onObjectProperty: function (name) {
  843. currentProperty = name;
  844. },
  845. onObjectEnd: function () {
  846. currentParent = previousParents.pop();
  847. },
  848. onArrayBegin: function () {
  849. var array = [];
  850. onValue(array);
  851. previousParents.push(currentParent);
  852. currentParent = array;
  853. currentProperty = null;
  854. },
  855. onArrayEnd: function () {
  856. currentParent = previousParents.pop();
  857. },
  858. onLiteralValue: onValue,
  859. onError: function (error, offset, length) {
  860. errors.push({ error: error, offset: offset, length: length });
  861. }
  862. };
  863. visit(text, visitor, options);
  864. return currentParent[0];
  865. }
  866. exports.parse = parse;
  867. /**
  868. * 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.
  869. */
  870. function parseTree(text, errors, options) {
  871. if (errors === void 0) { errors = []; }
  872. if (options === void 0) { options = ParseOptions.DEFAULT; }
  873. var currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root
  874. function ensurePropertyComplete(endOffset) {
  875. if (currentParent.type === 'property') {
  876. currentParent.length = endOffset - currentParent.offset;
  877. currentParent = currentParent.parent;
  878. }
  879. }
  880. function onValue(valueNode) {
  881. currentParent.children.push(valueNode);
  882. return valueNode;
  883. }
  884. var visitor = {
  885. onObjectBegin: function (offset) {
  886. currentParent = onValue({ type: 'object', offset: offset, length: -1, parent: currentParent, children: [] });
  887. },
  888. onObjectProperty: function (name, offset, length) {
  889. currentParent = onValue({ type: 'property', offset: offset, length: -1, parent: currentParent, children: [] });
  890. currentParent.children.push({ type: 'string', value: name, offset: offset, length: length, parent: currentParent });
  891. },
  892. onObjectEnd: function (offset, length) {
  893. ensurePropertyComplete(offset + length); // in case of a missing value for a property: make sure property is complete
  894. currentParent.length = offset + length - currentParent.offset;
  895. currentParent = currentParent.parent;
  896. ensurePropertyComplete(offset + length);
  897. },
  898. onArrayBegin: function (offset, length) {
  899. currentParent = onValue({ type: 'array', offset: offset, length: -1, parent: currentParent, children: [] });
  900. },
  901. onArrayEnd: function (offset, length) {
  902. currentParent.length = offset + length - currentParent.offset;
  903. currentParent = currentParent.parent;
  904. ensurePropertyComplete(offset + length);
  905. },
  906. onLiteralValue: function (value, offset, length) {
  907. onValue({ type: getNodeType(value), offset: offset, length: length, parent: currentParent, value: value });
  908. ensurePropertyComplete(offset + length);
  909. },
  910. onSeparator: function (sep, offset, length) {
  911. if (currentParent.type === 'property') {
  912. if (sep === ':') {
  913. currentParent.colonOffset = offset;
  914. }
  915. else if (sep === ',') {
  916. ensurePropertyComplete(offset);
  917. }
  918. }
  919. },
  920. onError: function (error, offset, length) {
  921. errors.push({ error: error, offset: offset, length: length });
  922. }
  923. };
  924. visit(text, visitor, options);
  925. var result = currentParent.children[0];
  926. if (result) {
  927. delete result.parent;
  928. }
  929. return result;
  930. }
  931. exports.parseTree = parseTree;
  932. /**
  933. * Finds the node at the given path in a JSON DOM.
  934. */
  935. function findNodeAtLocation(root, path) {
  936. if (!root) {
  937. return undefined;
  938. }
  939. var node = root;
  940. for (var _i = 0, path_1 = path; _i < path_1.length; _i++) {
  941. var segment = path_1[_i];
  942. if (typeof segment === 'string') {
  943. if (node.type !== 'object' || !Array.isArray(node.children)) {
  944. return undefined;
  945. }
  946. var found = false;
  947. for (var _a = 0, _b = node.children; _a < _b.length; _a++) {
  948. var propertyNode = _b[_a];
  949. if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment) {
  950. node = propertyNode.children[1];
  951. found = true;
  952. break;
  953. }
  954. }
  955. if (!found) {
  956. return undefined;
  957. }
  958. }
  959. else {
  960. var index = segment;
  961. if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {
  962. return undefined;
  963. }
  964. node = node.children[index];
  965. }
  966. }
  967. return node;
  968. }
  969. exports.findNodeAtLocation = findNodeAtLocation;
  970. /**
  971. * Gets the JSON path of the given JSON DOM node
  972. */
  973. function getNodePath(node) {
  974. if (!node.parent || !node.parent.children) {
  975. return [];
  976. }
  977. var path = getNodePath(node.parent);
  978. if (node.parent.type === 'property') {
  979. var key = node.parent.children[0].value;
  980. path.push(key);
  981. }
  982. else if (node.parent.type === 'array') {
  983. var index = node.parent.children.indexOf(node);
  984. if (index !== -1) {
  985. path.push(index);
  986. }
  987. }
  988. return path;
  989. }
  990. exports.getNodePath = getNodePath;
  991. /**
  992. * Evaluates the JavaScript object of the given JSON DOM node
  993. */
  994. function getNodeValue(node) {
  995. switch (node.type) {
  996. case 'array':
  997. return node.children.map(getNodeValue);
  998. case 'object':
  999. var obj = Object.create(null);
  1000. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  1001. var prop = _a[_i];
  1002. var valueNode = prop.children[1];
  1003. if (valueNode) {
  1004. obj[prop.children[0].value] = getNodeValue(valueNode);
  1005. }
  1006. }
  1007. return obj;
  1008. case 'null':
  1009. case 'string':
  1010. case 'number':
  1011. case 'boolean':
  1012. return node.value;
  1013. default:
  1014. return undefined;
  1015. }
  1016. }
  1017. exports.getNodeValue = getNodeValue;
  1018. function contains(node, offset, includeRightBound) {
  1019. if (includeRightBound === void 0) { includeRightBound = false; }
  1020. return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length));
  1021. }
  1022. exports.contains = contains;
  1023. /**
  1024. * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.
  1025. */
  1026. function findNodeAtOffset(node, offset, includeRightBound) {
  1027. if (includeRightBound === void 0) { includeRightBound = false; }
  1028. if (contains(node, offset, includeRightBound)) {
  1029. var children = node.children;
  1030. if (Array.isArray(children)) {
  1031. for (var i = 0; i < children.length && children[i].offset <= offset; i++) {
  1032. var item = findNodeAtOffset(children[i], offset, includeRightBound);
  1033. if (item) {
  1034. return item;
  1035. }
  1036. }
  1037. }
  1038. return node;
  1039. }
  1040. return undefined;
  1041. }
  1042. exports.findNodeAtOffset = findNodeAtOffset;
  1043. /**
  1044. * Parses the given text and invokes the visitor functions for each object, array and literal reached.
  1045. */
  1046. function visit(text, visitor, options) {
  1047. if (options === void 0) { options = ParseOptions.DEFAULT; }
  1048. var _scanner = scanner_1.createScanner(text, false);
  1049. function toNoArgVisit(visitFunction) {
  1050. return visitFunction ? function () { return visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); } : function () { return true; };
  1051. }
  1052. function toOneArgVisit(visitFunction) {
  1053. return visitFunction ? function (arg) { return visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); } : function () { return true; };
  1054. }
  1055. 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);
  1056. var disallowComments = options && options.disallowComments;
  1057. var allowTrailingComma = options && options.allowTrailingComma;
  1058. function scanNext() {
  1059. while (true) {
  1060. var token = _scanner.scan();
  1061. switch (_scanner.getTokenError()) {
  1062. case 4 /* InvalidUnicode */:
  1063. handleError(14 /* InvalidUnicode */);
  1064. break;
  1065. case 5 /* InvalidEscapeCharacter */:
  1066. handleError(15 /* InvalidEscapeCharacter */);
  1067. break;
  1068. case 3 /* UnexpectedEndOfNumber */:
  1069. handleError(13 /* UnexpectedEndOfNumber */);
  1070. break;
  1071. case 1 /* UnexpectedEndOfComment */:
  1072. if (!disallowComments) {
  1073. handleError(11 /* UnexpectedEndOfComment */);
  1074. }
  1075. break;
  1076. case 2 /* UnexpectedEndOfString */:
  1077. handleError(12 /* UnexpectedEndOfString */);
  1078. break;
  1079. case 6 /* InvalidCharacter */:
  1080. handleError(16 /* InvalidCharacter */);
  1081. break;
  1082. }
  1083. switch (token) {
  1084. case 12 /* LineCommentTrivia */:
  1085. case 13 /* BlockCommentTrivia */:
  1086. if (disallowComments) {
  1087. handleError(10 /* InvalidCommentToken */);
  1088. }
  1089. else {
  1090. onComment();
  1091. }
  1092. break;
  1093. case 16 /* Unknown */:
  1094. handleError(1 /* InvalidSymbol */);
  1095. break;
  1096. case 15 /* Trivia */:
  1097. case 14 /* LineBreakTrivia */:
  1098. break;
  1099. default:
  1100. return token;
  1101. }
  1102. }
  1103. }
  1104. function handleError(error, skipUntilAfter, skipUntil) {
  1105. if (skipUntilAfter === void 0) { skipUntilAfter = []; }
  1106. if (skipUntil === void 0) { skipUntil = []; }
  1107. onError(error);
  1108. if (skipUntilAfter.length + skipUntil.length > 0) {
  1109. var token = _scanner.getToken();
  1110. while (token !== 17 /* EOF */) {
  1111. if (skipUntilAfter.indexOf(token) !== -1) {
  1112. scanNext();
  1113. break;
  1114. }
  1115. else if (skipUntil.indexOf(token) !== -1) {
  1116. break;
  1117. }
  1118. token = scanNext();
  1119. }
  1120. }
  1121. }
  1122. function parseString(isValue) {
  1123. var value = _scanner.getTokenValue();
  1124. if (isValue) {
  1125. onLiteralValue(value);
  1126. }
  1127. else {
  1128. onObjectProperty(value);
  1129. }
  1130. scanNext();
  1131. return true;
  1132. }
  1133. function parseLiteral() {
  1134. switch (_scanner.getToken()) {
  1135. case 11 /* NumericLiteral */:
  1136. var tokenValue = _scanner.getTokenValue();
  1137. var value = Number(tokenValue);
  1138. if (isNaN(value)) {
  1139. handleError(2 /* InvalidNumberFormat */);
  1140. value = 0;
  1141. }
  1142. onLiteralValue(value);
  1143. break;
  1144. case 7 /* NullKeyword */:
  1145. onLiteralValue(null);
  1146. break;
  1147. case 8 /* TrueKeyword */:
  1148. onLiteralValue(true);
  1149. break;
  1150. case 9 /* FalseKeyword */:
  1151. onLiteralValue(false);
  1152. break;
  1153. default:
  1154. return false;
  1155. }
  1156. scanNext();
  1157. return true;
  1158. }
  1159. function parseProperty() {
  1160. if (_scanner.getToken() !== 10 /* StringLiteral */) {
  1161. handleError(3 /* PropertyNameExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  1162. return false;
  1163. }
  1164. parseString(false);
  1165. if (_scanner.getToken() === 6 /* ColonToken */) {
  1166. onSeparator(':');
  1167. scanNext(); // consume colon
  1168. if (!parseValue()) {
  1169. handleError(4 /* ValueExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  1170. }
  1171. }
  1172. else {
  1173. handleError(5 /* ColonExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  1174. }
  1175. return true;
  1176. }
  1177. function parseObject() {
  1178. onObjectBegin();
  1179. scanNext(); // consume open brace
  1180. var needsComma = false;
  1181. while (_scanner.getToken() !== 2 /* CloseBraceToken */ && _scanner.getToken() !== 17 /* EOF */) {
  1182. if (_scanner.getToken() === 5 /* CommaToken */) {
  1183. if (!needsComma) {
  1184. handleError(4 /* ValueExpected */, [], []);
  1185. }
  1186. onSeparator(',');
  1187. scanNext(); // consume comma
  1188. if (_scanner.getToken() === 2 /* CloseBraceToken */ && allowTrailingComma) {
  1189. break;
  1190. }
  1191. }
  1192. else if (needsComma) {
  1193. handleError(6 /* CommaExpected */, [], []);
  1194. }
  1195. if (!parseProperty()) {
  1196. handleError(4 /* ValueExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  1197. }
  1198. needsComma = true;
  1199. }
  1200. onObjectEnd();
  1201. if (_scanner.getToken() !== 2 /* CloseBraceToken */) {
  1202. handleError(7 /* CloseBraceExpected */, [2 /* CloseBraceToken */], []);
  1203. }
  1204. else {
  1205. scanNext(); // consume close brace
  1206. }
  1207. return true;
  1208. }
  1209. function parseArray() {
  1210. onArrayBegin();
  1211. scanNext(); // consume open bracket
  1212. var needsComma = false;
  1213. while (_scanner.getToken() !== 4 /* CloseBracketToken */ && _scanner.getToken() !== 17 /* EOF */) {
  1214. if (_scanner.getToken() === 5 /* CommaToken */) {
  1215. if (!needsComma) {
  1216. handleError(4 /* ValueExpected */, [], []);
  1217. }
  1218. onSeparator(',');
  1219. scanNext(); // consume comma
  1220. if (_scanner.getToken() === 4 /* CloseBracketToken */ && allowTrailingComma) {
  1221. break;
  1222. }
  1223. }
  1224. else if (needsComma) {
  1225. handleError(6 /* CommaExpected */, [], []);
  1226. }
  1227. if (!parseValue()) {
  1228. handleError(4 /* ValueExpected */, [], [4 /* CloseBracketToken */, 5 /* CommaToken */]);
  1229. }
  1230. needsComma = true;
  1231. }
  1232. onArrayEnd();
  1233. if (_scanner.getToken() !== 4 /* CloseBracketToken */) {
  1234. handleError(8 /* CloseBracketExpected */, [4 /* CloseBracketToken */], []);
  1235. }
  1236. else {
  1237. scanNext(); // consume close bracket
  1238. }
  1239. return true;
  1240. }
  1241. function parseValue() {
  1242. switch (_scanner.getToken()) {
  1243. case 3 /* OpenBracketToken */:
  1244. return parseArray();
  1245. case 1 /* OpenBraceToken */:
  1246. return parseObject();
  1247. case 10 /* StringLiteral */:
  1248. return parseString(true);
  1249. default:
  1250. return parseLiteral();
  1251. }
  1252. }
  1253. scanNext();
  1254. if (_scanner.getToken() === 17 /* EOF */) {
  1255. if (options.allowEmptyContent) {
  1256. return true;
  1257. }
  1258. handleError(4 /* ValueExpected */, [], []);
  1259. return false;
  1260. }
  1261. if (!parseValue()) {
  1262. handleError(4 /* ValueExpected */, [], []);
  1263. return false;
  1264. }
  1265. if (_scanner.getToken() !== 17 /* EOF */) {
  1266. handleError(9 /* EndOfFileExpected */, [], []);
  1267. }
  1268. return true;
  1269. }
  1270. exports.visit = visit;
  1271. /**
  1272. * Takes JSON with JavaScript-style comments and remove
  1273. * them. Optionally replaces every none-newline character
  1274. * of comments with a replaceCharacter
  1275. */
  1276. function stripComments(text, replaceCh) {
  1277. var _scanner = scanner_1.createScanner(text), parts = [], kind, offset = 0, pos;
  1278. do {
  1279. pos = _scanner.getPosition();
  1280. kind = _scanner.scan();
  1281. switch (kind) {
  1282. case 12 /* LineCommentTrivia */:
  1283. case 13 /* BlockCommentTrivia */:
  1284. case 17 /* EOF */:
  1285. if (offset !== pos) {
  1286. parts.push(text.substring(offset, pos));
  1287. }
  1288. if (replaceCh !== undefined) {
  1289. parts.push(_scanner.getTokenValue().replace(/[^\r\n]/g, replaceCh));
  1290. }
  1291. offset = _scanner.getPosition();
  1292. break;
  1293. }
  1294. } while (kind !== 17 /* EOF */);
  1295. return parts.join('');
  1296. }
  1297. exports.stripComments = stripComments;
  1298. function getNodeType(value) {
  1299. switch (typeof value) {
  1300. case 'boolean': return 'boolean';
  1301. case 'number': return 'number';
  1302. case 'string': return 'string';
  1303. case 'object': {
  1304. if (!value) {
  1305. return 'null';
  1306. }
  1307. else if (Array.isArray(value)) {
  1308. return 'array';
  1309. }
  1310. return 'object';
  1311. }
  1312. default: return 'null';
  1313. }
  1314. }
  1315. exports.getNodeType = getNodeType;
  1316. });
  1317. (function (factory) {
  1318. if (typeof module === "object" && typeof module.exports === "object") {
  1319. var v = factory(require, exports);
  1320. if (v !== undefined) module.exports = v;
  1321. }
  1322. else if (typeof define === "function" && define.amd) {
  1323. define('jsonc-parser/impl/edit',["require", "exports", "./format", "./parser"], factory);
  1324. }
  1325. })(function (require, exports) {
  1326. /*---------------------------------------------------------------------------------------------
  1327. * Copyright (c) Microsoft Corporation. All rights reserved.
  1328. * Licensed under the MIT License. See License.txt in the project root for license information.
  1329. *--------------------------------------------------------------------------------------------*/
  1330. 'use strict';
  1331. Object.defineProperty(exports, "__esModule", { value: true });
  1332. exports.isWS = exports.applyEdit = exports.setProperty = exports.removeProperty = void 0;
  1333. var format_1 = require("./format");
  1334. var parser_1 = require("./parser");
  1335. function removeProperty(text, path, options) {
  1336. return setProperty(text, path, void 0, options);
  1337. }
  1338. exports.removeProperty = removeProperty;
  1339. function setProperty(text, originalPath, value, options) {
  1340. var _a;
  1341. var path = originalPath.slice();
  1342. var errors = [];
  1343. var root = parser_1.parseTree(text, errors);
  1344. var parent = void 0;
  1345. var lastSegment = void 0;
  1346. while (path.length > 0) {
  1347. lastSegment = path.pop();
  1348. parent = parser_1.findNodeAtLocation(root, path);
  1349. if (parent === void 0 && value !== void 0) {
  1350. if (typeof lastSegment === 'string') {
  1351. value = (_a = {}, _a[lastSegment] = value, _a);
  1352. }
  1353. else {
  1354. value = [value];
  1355. }
  1356. }
  1357. else {
  1358. break;
  1359. }
  1360. }
  1361. if (!parent) {
  1362. // empty document
  1363. if (value === void 0) { // delete
  1364. throw new Error('Can not delete in empty document');
  1365. }
  1366. return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options);
  1367. }
  1368. else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) {
  1369. var existing = parser_1.findNodeAtLocation(parent, [lastSegment]);
  1370. if (existing !== void 0) {
  1371. if (value === void 0) { // delete
  1372. if (!existing.parent) {
  1373. throw new Error('Malformed AST');
  1374. }
  1375. var propertyIndex = parent.children.indexOf(existing.parent);
  1376. var removeBegin = void 0;
  1377. var removeEnd = existing.parent.offset + existing.parent.length;
  1378. if (propertyIndex > 0) {
  1379. // remove the comma of the previous node
  1380. var previous = parent.children[propertyIndex - 1];
  1381. removeBegin = previous.offset + previous.length;
  1382. }
  1383. else {
  1384. removeBegin = parent.offset + 1;
  1385. if (parent.children.length > 1) {
  1386. // remove the comma of the next node
  1387. var next = parent.children[1];
  1388. removeEnd = next.offset;
  1389. }
  1390. }
  1391. return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, options);
  1392. }
  1393. else {
  1394. // set value of existing property
  1395. return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options);
  1396. }
  1397. }
  1398. else {
  1399. if (value === void 0) { // delete
  1400. return []; // property does not exist, nothing to do
  1401. }
  1402. var newProperty = JSON.stringify(lastSegment) + ": " + JSON.stringify(value);
  1403. var index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map(function (p) { return p.children[0].value; })) : parent.children.length;
  1404. var edit = void 0;
  1405. if (index > 0) {
  1406. var previous = parent.children[index - 1];
  1407. edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
  1408. }
  1409. else if (parent.children.length === 0) {
  1410. edit = { offset: parent.offset + 1, length: 0, content: newProperty };
  1411. }
  1412. else {
  1413. edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' };
  1414. }
  1415. return withFormatting(text, edit, options);
  1416. }
  1417. }
  1418. else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) {
  1419. var insertIndex = lastSegment;
  1420. if (insertIndex === -1) {
  1421. // Insert
  1422. var newProperty = "" + JSON.stringify(value);
  1423. var edit = void 0;
  1424. if (parent.children.length === 0) {
  1425. edit = { offset: parent.offset + 1, length: 0, content: newProperty };
  1426. }
  1427. else {
  1428. var previous = parent.children[parent.children.length - 1];
  1429. edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
  1430. }
  1431. return withFormatting(text, edit, options);
  1432. }
  1433. else if (value === void 0 && parent.children.length >= 0) {
  1434. // Removal
  1435. var removalIndex = lastSegment;
  1436. var toRemove = parent.children[removalIndex];
  1437. var edit = void 0;
  1438. if (parent.children.length === 1) {
  1439. // only item
  1440. edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' };
  1441. }
  1442. else if (parent.children.length - 1 === removalIndex) {
  1443. // last item
  1444. var previous = parent.children[removalIndex - 1];
  1445. var offset = previous.offset + previous.length;
  1446. var parentEndOffset = parent.offset + parent.length;
  1447. edit = { offset: offset, length: parentEndOffset - 2 - offset, content: '' };
  1448. }
  1449. else {
  1450. edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' };
  1451. }
  1452. return withFormatting(text, edit, options);
  1453. }
  1454. else if (value !== void 0) {
  1455. var edit = void 0;
  1456. var newProperty = "" + JSON.stringify(value);
  1457. if (!options.isArrayInsertion && parent.children.length > lastSegment) {
  1458. var toModify = parent.children[lastSegment];
  1459. edit = { offset: toModify.offset, length: toModify.length, content: newProperty };
  1460. }
  1461. else if (parent.children.length === 0 || lastSegment === 0) {
  1462. edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + ',' };
  1463. }
  1464. else {
  1465. var index = lastSegment > parent.children.length ? parent.children.length : lastSegment;
  1466. var previous = parent.children[index - 1];
  1467. edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
  1468. }
  1469. return withFormatting(text, edit, options);
  1470. }
  1471. else {
  1472. throw new Error("Can not " + (value === void 0 ? 'remove' : (options.isArrayInsertion ? 'insert' : 'modify')) + " Array index " + insertIndex + " as length is not sufficient");
  1473. }
  1474. }
  1475. else {
  1476. throw new Error("Can not add " + (typeof lastSegment !== 'number' ? 'index' : 'property') + " to parent of type " + parent.type);
  1477. }
  1478. }
  1479. exports.setProperty = setProperty;
  1480. function withFormatting(text, edit, options) {
  1481. if (!options.formattingOptions) {
  1482. return [edit];
  1483. }
  1484. // apply the edit
  1485. var newText = applyEdit(text, edit);
  1486. // format the new text
  1487. var begin = edit.offset;
  1488. var end = edit.offset + edit.content.length;
  1489. if (edit.length === 0 || edit.content.length === 0) { // insert or remove
  1490. while (begin > 0 && !format_1.isEOL(newText, begin - 1)) {
  1491. begin--;
  1492. }
  1493. while (end < newText.length && !format_1.isEOL(newText, end)) {
  1494. end++;
  1495. }
  1496. }
  1497. var edits = format_1.format(newText, { offset: begin, length: end - begin }, options.formattingOptions);
  1498. // apply the formatting edits and track the begin and end offsets of the changes
  1499. for (var i = edits.length - 1; i >= 0; i--) {
  1500. var edit_1 = edits[i];
  1501. newText = applyEdit(newText, edit_1);
  1502. begin = Math.min(begin, edit_1.offset);
  1503. end = Math.max(end, edit_1.offset + edit_1.length);
  1504. end += edit_1.content.length - edit_1.length;
  1505. }
  1506. // create a single edit with all changes
  1507. var editLength = text.length - (newText.length - end) - begin;
  1508. return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];
  1509. }
  1510. function applyEdit(text, edit) {
  1511. return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
  1512. }
  1513. exports.applyEdit = applyEdit;
  1514. function isWS(text, offset) {
  1515. return '\r\n \t'.indexOf(text.charAt(offset)) !== -1;
  1516. }
  1517. exports.isWS = isWS;
  1518. });
  1519. (function (factory) {
  1520. if (typeof module === "object" && typeof module.exports === "object") {
  1521. var v = factory(require, exports);
  1522. if (v !== undefined) module.exports = v;
  1523. }
  1524. else if (typeof define === "function" && define.amd) {
  1525. define('jsonc-parser/main',["require", "exports", "./impl/format", "./impl/edit", "./impl/scanner", "./impl/parser"], factory);
  1526. }
  1527. })(function (require, exports) {
  1528. /*---------------------------------------------------------------------------------------------
  1529. * Copyright (c) Microsoft Corporation. All rights reserved.
  1530. * Licensed under the MIT License. See License.txt in the project root for license information.
  1531. *--------------------------------------------------------------------------------------------*/
  1532. 'use strict';
  1533. Object.defineProperty(exports, "__esModule", { value: true });
  1534. 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;
  1535. var formatter = require("./impl/format");
  1536. var edit = require("./impl/edit");
  1537. var scanner = require("./impl/scanner");
  1538. var parser = require("./impl/parser");
  1539. /**
  1540. * Creates a JSON scanner on the given text.
  1541. * If ignoreTrivia is set, whitespaces or comments are ignored.
  1542. */
  1543. exports.createScanner = scanner.createScanner;
  1544. /**
  1545. * 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.
  1546. */
  1547. exports.getLocation = parser.getLocation;
  1548. /**
  1549. * 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.
  1550. * Therefore, always check the errors list to find out if the input was valid.
  1551. */
  1552. exports.parse = parser.parse;
  1553. /**
  1554. * 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.
  1555. */
  1556. exports.parseTree = parser.parseTree;
  1557. /**
  1558. * Finds the node at the given path in a JSON DOM.
  1559. */
  1560. exports.findNodeAtLocation = parser.findNodeAtLocation;
  1561. /**
  1562. * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.
  1563. */
  1564. exports.findNodeAtOffset = parser.findNodeAtOffset;
  1565. /**
  1566. * Gets the JSON path of the given JSON DOM node
  1567. */
  1568. exports.getNodePath = parser.getNodePath;
  1569. /**
  1570. * Evaluates the JavaScript object of the given JSON DOM node
  1571. */
  1572. exports.getNodeValue = parser.getNodeValue;
  1573. /**
  1574. * Parses the given text and invokes the visitor functions for each object, array and literal reached.
  1575. */
  1576. exports.visit = parser.visit;
  1577. /**
  1578. * Takes JSON with JavaScript-style comments and remove
  1579. * them. Optionally replaces every none-newline character
  1580. * of comments with a replaceCharacter
  1581. */
  1582. exports.stripComments = parser.stripComments;
  1583. function printParseErrorCode(code) {
  1584. switch (code) {
  1585. case 1 /* InvalidSymbol */: return 'InvalidSymbol';
  1586. case 2 /* InvalidNumberFormat */: return 'InvalidNumberFormat';
  1587. case 3 /* PropertyNameExpected */: return 'PropertyNameExpected';
  1588. case 4 /* ValueExpected */: return 'ValueExpected';
  1589. case 5 /* ColonExpected */: return 'ColonExpected';
  1590. case 6 /* CommaExpected */: return 'CommaExpected';
  1591. case 7 /* CloseBraceExpected */: return 'CloseBraceExpected';
  1592. case 8 /* CloseBracketExpected */: return 'CloseBracketExpected';
  1593. case 9 /* EndOfFileExpected */: return 'EndOfFileExpected';
  1594. case 10 /* InvalidCommentToken */: return 'InvalidCommentToken';
  1595. case 11 /* UnexpectedEndOfComment */: return 'UnexpectedEndOfComment';
  1596. case 12 /* UnexpectedEndOfString */: return 'UnexpectedEndOfString';
  1597. case 13 /* UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber';
  1598. case 14 /* InvalidUnicode */: return 'InvalidUnicode';
  1599. case 15 /* InvalidEscapeCharacter */: return 'InvalidEscapeCharacter';
  1600. case 16 /* InvalidCharacter */: return 'InvalidCharacter';
  1601. }
  1602. return '<unknown ParseErrorCode>';
  1603. }
  1604. exports.printParseErrorCode = printParseErrorCode;
  1605. /**
  1606. * Computes the edits needed to format a JSON document.
  1607. *
  1608. * @param documentText The input text
  1609. * @param range The range to format or `undefined` to format the full content
  1610. * @param options The formatting options
  1611. * @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
  1612. * 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
  1613. * text in the original document. However, multiple edits can have
  1614. * 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.
  1615. * To apply edits to an input, you can use `applyEdits`.
  1616. */
  1617. function format(documentText, range, options) {
  1618. return formatter.format(documentText, range, options);
  1619. }
  1620. exports.format = format;
  1621. /**
  1622. * Computes the edits needed to modify a value in the JSON document.
  1623. *
  1624. * @param documentText The input text
  1625. * @param path The path of the value to change. The path represents either to the document root, a property or an array item.
  1626. * If the path points to an non-existing property or item, it will be created.
  1627. * @param value The new value for the specified property or item. If the value is undefined,
  1628. * the property or item will be removed.
  1629. * @param options Options
  1630. * @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
  1631. * 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
  1632. * text in the original document. However, multiple edits can have
  1633. * 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.
  1634. * To apply edits to an input, you can use `applyEdits`.
  1635. */
  1636. function modify(text, path, value, options) {
  1637. return edit.setProperty(text, path, value, options);
  1638. }
  1639. exports.modify = modify;
  1640. /**
  1641. * Applies edits to a input string.
  1642. */
  1643. function applyEdits(text, edits) {
  1644. for (var i = edits.length - 1; i >= 0; i--) {
  1645. text = edit.applyEdit(text, edits[i]);
  1646. }
  1647. return text;
  1648. }
  1649. exports.applyEdits = applyEdits;
  1650. });
  1651. define('jsonc-parser', ['jsonc-parser/main'], function (main) { return main; });
  1652. /*---------------------------------------------------------------------------------------------
  1653. * Copyright (c) Microsoft Corporation. All rights reserved.
  1654. * Licensed under the MIT License. See License.txt in the project root for license information.
  1655. *--------------------------------------------------------------------------------------------*/
  1656. (function (factory) {
  1657. if (typeof module === "object" && typeof module.exports === "object") {
  1658. var v = factory(require, exports);
  1659. if (v !== undefined) module.exports = v;
  1660. }
  1661. else if (typeof define === "function" && define.amd) {
  1662. define('vscode-json-languageservice/utils/objects',["require", "exports"], factory);
  1663. }
  1664. })(function (require, exports) {
  1665. "use strict";
  1666. Object.defineProperty(exports, "__esModule", { value: true });
  1667. exports.isString = exports.isBoolean = exports.isDefined = exports.isNumber = exports.equals = void 0;
  1668. function equals(one, other) {
  1669. if (one === other) {
  1670. return true;
  1671. }
  1672. if (one === null || one === undefined || other === null || other === undefined) {
  1673. return false;
  1674. }
  1675. if (typeof one !== typeof other) {
  1676. return false;
  1677. }
  1678. if (typeof one !== 'object') {
  1679. return false;
  1680. }
  1681. if ((Array.isArray(one)) !== (Array.isArray(other))) {
  1682. return false;
  1683. }
  1684. var i, key;
  1685. if (Array.isArray(one)) {
  1686. if (one.length !== other.length) {
  1687. return false;
  1688. }
  1689. for (i = 0; i < one.length; i++) {
  1690. if (!equals(one[i], other[i])) {
  1691. return false;
  1692. }
  1693. }
  1694. }
  1695. else {
  1696. var oneKeys = [];
  1697. for (key in one) {
  1698. oneKeys.push(key);
  1699. }
  1700. oneKeys.sort();
  1701. var otherKeys = [];
  1702. for (key in other) {
  1703. otherKeys.push(key);
  1704. }
  1705. otherKeys.sort();
  1706. if (!equals(oneKeys, otherKeys)) {
  1707. return false;
  1708. }
  1709. for (i = 0; i < oneKeys.length; i++) {
  1710. if (!equals(one[oneKeys[i]], other[oneKeys[i]])) {
  1711. return false;
  1712. }
  1713. }
  1714. }
  1715. return true;
  1716. }
  1717. exports.equals = equals;
  1718. function isNumber(val) {
  1719. return typeof val === 'number';
  1720. }
  1721. exports.isNumber = isNumber;
  1722. function isDefined(val) {
  1723. return typeof val !== 'undefined';
  1724. }
  1725. exports.isDefined = isDefined;
  1726. function isBoolean(val) {
  1727. return typeof val === 'boolean';
  1728. }
  1729. exports.isBoolean = isBoolean;
  1730. function isString(val) {
  1731. return typeof val === 'string';
  1732. }
  1733. exports.isString = isString;
  1734. });
  1735. /*---------------------------------------------------------------------------------------------
  1736. * Copyright (c) Microsoft Corporation. All rights reserved.
  1737. * Licensed under the MIT License. See License.txt in the project root for license information.
  1738. *--------------------------------------------------------------------------------------------*/
  1739. (function (factory) {
  1740. if (typeof module === "object" && typeof module.exports === "object") {
  1741. var v = factory(require, exports);
  1742. if (v !== undefined) module.exports = v;
  1743. }
  1744. else if (typeof define === "function" && define.amd) {
  1745. define('vscode-json-languageservice/utils/strings',["require", "exports"], factory);
  1746. }
  1747. })(function (require, exports) {
  1748. "use strict";
  1749. Object.defineProperty(exports, "__esModule", { value: true });
  1750. exports.extendedRegExp = exports.repeat = exports.convertSimple2RegExpPattern = exports.endsWith = exports.startsWith = void 0;
  1751. function startsWith(haystack, needle) {
  1752. if (haystack.length < needle.length) {
  1753. return false;
  1754. }
  1755. for (var i = 0; i < needle.length; i++) {
  1756. if (haystack[i] !== needle[i]) {
  1757. return false;
  1758. }
  1759. }
  1760. return true;
  1761. }
  1762. exports.startsWith = startsWith;
  1763. /**
  1764. * Determines if haystack ends with needle.
  1765. */
  1766. function endsWith(haystack, needle) {
  1767. var diff = haystack.length - needle.length;
  1768. if (diff > 0) {
  1769. return haystack.lastIndexOf(needle) === diff;
  1770. }
  1771. else if (diff === 0) {
  1772. return haystack === needle;
  1773. }
  1774. else {
  1775. return false;
  1776. }
  1777. }
  1778. exports.endsWith = endsWith;
  1779. function convertSimple2RegExpPattern(pattern) {
  1780. return pattern.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&').replace(/[\*]/g, '.*');
  1781. }
  1782. exports.convertSimple2RegExpPattern = convertSimple2RegExpPattern;
  1783. function repeat(value, count) {
  1784. var s = '';
  1785. while (count > 0) {
  1786. if ((count & 1) === 1) {
  1787. s += value;
  1788. }
  1789. value += value;
  1790. count = count >>> 1;
  1791. }
  1792. return s;
  1793. }
  1794. exports.repeat = repeat;
  1795. function extendedRegExp(pattern) {
  1796. if (startsWith(pattern, '(?i)')) {
  1797. return new RegExp(pattern.substring(4), 'i');
  1798. }
  1799. else {
  1800. return new RegExp(pattern);
  1801. }
  1802. }
  1803. exports.extendedRegExp = extendedRegExp;
  1804. });
  1805. (function (factory) {
  1806. if (typeof module === "object" && typeof module.exports === "object") {
  1807. var v = factory(require, exports);
  1808. if (v !== undefined) module.exports = v;
  1809. }
  1810. else if (typeof define === "function" && define.amd) {
  1811. define('vscode-languageserver-types/main',["require", "exports"], factory);
  1812. }
  1813. })(function (require, exports) {
  1814. /* --------------------------------------------------------------------------------------------
  1815. * Copyright (c) Microsoft Corporation. All rights reserved.
  1816. * Licensed under the MIT License. See License.txt in the project root for license information.
  1817. * ------------------------------------------------------------------------------------------ */
  1818. 'use strict';
  1819. Object.defineProperty(exports, "__esModule", { value: true });
  1820. 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;
  1821. var integer;
  1822. (function (integer) {
  1823. integer.MIN_VALUE = -2147483648;
  1824. integer.MAX_VALUE = 2147483647;
  1825. })(integer = exports.integer || (exports.integer = {}));
  1826. var uinteger;
  1827. (function (uinteger) {
  1828. uinteger.MIN_VALUE = 0;
  1829. uinteger.MAX_VALUE = 2147483647;
  1830. })(uinteger = exports.uinteger || (exports.uinteger = {}));
  1831. /**
  1832. * The Position namespace provides helper functions to work with
  1833. * [Position](#Position) literals.
  1834. */
  1835. var Position;
  1836. (function (Position) {
  1837. /**
  1838. * Creates a new Position literal from the given line and character.
  1839. * @param line The position's line.
  1840. * @param character The position's character.
  1841. */
  1842. function create(line, character) {
  1843. if (line === Number.MAX_VALUE) {
  1844. line = uinteger.MAX_VALUE;
  1845. }
  1846. if (character === Number.MAX_VALUE) {
  1847. character = uinteger.MAX_VALUE;
  1848. }
  1849. return { line: line, character: character };
  1850. }
  1851. Position.create = create;
  1852. /**
  1853. * Checks whether the given literal conforms to the [Position](#Position) interface.
  1854. */
  1855. function is(value) {
  1856. var candidate = value;
  1857. return Is.objectLiteral(candidate) && Is.uinteger(candidate.line) && Is.uinteger(candidate.character);
  1858. }
  1859. Position.is = is;
  1860. })(Position = exports.Position || (exports.Position = {}));
  1861. /**
  1862. * The Range namespace provides helper functions to work with
  1863. * [Range](#Range) literals.
  1864. */
  1865. var Range;
  1866. (function (Range) {
  1867. function create(one, two, three, four) {
  1868. if (Is.uinteger(one) && Is.uinteger(two) && Is.uinteger(three) && Is.uinteger(four)) {
  1869. return { start: Position.create(one, two), end: Position.create(three, four) };
  1870. }
  1871. else if (Position.is(one) && Position.is(two)) {
  1872. return { start: one, end: two };
  1873. }
  1874. else {
  1875. throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
  1876. }
  1877. }
  1878. Range.create = create;
  1879. /**
  1880. * Checks whether the given literal conforms to the [Range](#Range) interface.
  1881. */
  1882. function is(value) {
  1883. var candidate = value;
  1884. return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
  1885. }
  1886. Range.is = is;
  1887. })(Range = exports.Range || (exports.Range = {}));
  1888. /**
  1889. * The Location namespace provides helper functions to work with
  1890. * [Location](#Location) literals.
  1891. */
  1892. var Location;
  1893. (function (Location) {
  1894. /**
  1895. * Creates a Location literal.
  1896. * @param uri The location's uri.
  1897. * @param range The location's range.
  1898. */
  1899. function create(uri, range) {
  1900. return { uri: uri, range: range };
  1901. }
  1902. Location.create = create;
  1903. /**
  1904. * Checks whether the given literal conforms to the [Location](#Location) interface.
  1905. */
  1906. function is(value) {
  1907. var candidate = value;
  1908. return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
  1909. }
  1910. Location.is = is;
  1911. })(Location = exports.Location || (exports.Location = {}));
  1912. /**
  1913. * The LocationLink namespace provides helper functions to work with
  1914. * [LocationLink](#LocationLink) literals.
  1915. */
  1916. var LocationLink;
  1917. (function (LocationLink) {
  1918. /**
  1919. * Creates a LocationLink literal.
  1920. * @param targetUri The definition's uri.
  1921. * @param targetRange The full range of the definition.
  1922. * @param targetSelectionRange The span of the symbol definition at the target.
  1923. * @param originSelectionRange The span of the symbol being defined in the originating source file.
  1924. */
  1925. function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
  1926. return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };
  1927. }
  1928. LocationLink.create = create;
  1929. /**
  1930. * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface.
  1931. */
  1932. function is(value) {
  1933. var candidate = value;
  1934. return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)
  1935. && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange))
  1936. && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
  1937. }
  1938. LocationLink.is = is;
  1939. })(LocationLink = exports.LocationLink || (exports.LocationLink = {}));
  1940. /**
  1941. * The Color namespace provides helper functions to work with
  1942. * [Color](#Color) literals.
  1943. */
  1944. var Color;
  1945. (function (Color) {
  1946. /**
  1947. * Creates a new Color literal.
  1948. */
  1949. function create(red, green, blue, alpha) {
  1950. return {
  1951. red: red,
  1952. green: green,
  1953. blue: blue,
  1954. alpha: alpha,
  1955. };
  1956. }
  1957. Color.create = create;
  1958. /**
  1959. * Checks whether the given literal conforms to the [Color](#Color) interface.
  1960. */
  1961. function is(value) {
  1962. var candidate = value;
  1963. return Is.numberRange(candidate.red, 0, 1)
  1964. && Is.numberRange(candidate.green, 0, 1)
  1965. && Is.numberRange(candidate.blue, 0, 1)
  1966. && Is.numberRange(candidate.alpha, 0, 1);
  1967. }
  1968. Color.is = is;
  1969. })(Color = exports.Color || (exports.Color = {}));
  1970. /**
  1971. * The ColorInformation namespace provides helper functions to work with
  1972. * [ColorInformation](#ColorInformation) literals.
  1973. */
  1974. var ColorInformation;
  1975. (function (ColorInformation) {
  1976. /**
  1977. * Creates a new ColorInformation literal.
  1978. */
  1979. function create(range, color) {
  1980. return {
  1981. range: range,
  1982. color: color,
  1983. };
  1984. }
  1985. ColorInformation.create = create;
  1986. /**
  1987. * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
  1988. */
  1989. function is(value) {
  1990. var candidate = value;
  1991. return Range.is(candidate.range) && Color.is(candidate.color);
  1992. }
  1993. ColorInformation.is = is;
  1994. })(ColorInformation = exports.ColorInformation || (exports.ColorInformation = {}));
  1995. /**
  1996. * The Color namespace provides helper functions to work with
  1997. * [ColorPresentation](#ColorPresentation) literals.
  1998. */
  1999. var ColorPresentation;
  2000. (function (ColorPresentation) {
  2001. /**
  2002. * Creates a new ColorInformation literal.
  2003. */
  2004. function create(label, textEdit, additionalTextEdits) {
  2005. return {
  2006. label: label,
  2007. textEdit: textEdit,
  2008. additionalTextEdits: additionalTextEdits,
  2009. };
  2010. }
  2011. ColorPresentation.create = create;
  2012. /**
  2013. * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
  2014. */
  2015. function is(value) {
  2016. var candidate = value;
  2017. return Is.string(candidate.label)
  2018. && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))
  2019. && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
  2020. }
  2021. ColorPresentation.is = is;
  2022. })(ColorPresentation = exports.ColorPresentation || (exports.ColorPresentation = {}));
  2023. /**
  2024. * Enum of known range kinds
  2025. */
  2026. var FoldingRangeKind;
  2027. (function (FoldingRangeKind) {
  2028. /**
  2029. * Folding range for a comment
  2030. */
  2031. FoldingRangeKind["Comment"] = "comment";
  2032. /**
  2033. * Folding range for a imports or includes
  2034. */
  2035. FoldingRangeKind["Imports"] = "imports";
  2036. /**
  2037. * Folding range for a region (e.g. `#region`)
  2038. */
  2039. FoldingRangeKind["Region"] = "region";
  2040. })(FoldingRangeKind = exports.FoldingRangeKind || (exports.FoldingRangeKind = {}));
  2041. /**
  2042. * The folding range namespace provides helper functions to work with
  2043. * [FoldingRange](#FoldingRange) literals.
  2044. */
  2045. var FoldingRange;
  2046. (function (FoldingRange) {
  2047. /**
  2048. * Creates a new FoldingRange literal.
  2049. */
  2050. function create(startLine, endLine, startCharacter, endCharacter, kind) {
  2051. var result = {
  2052. startLine: startLine,
  2053. endLine: endLine
  2054. };
  2055. if (Is.defined(startCharacter)) {
  2056. result.startCharacter = startCharacter;
  2057. }
  2058. if (Is.defined(endCharacter)) {
  2059. result.endCharacter = endCharacter;
  2060. }
  2061. if (Is.defined(kind)) {
  2062. result.kind = kind;
  2063. }
  2064. return result;
  2065. }
  2066. FoldingRange.create = create;
  2067. /**
  2068. * Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface.
  2069. */
  2070. function is(value) {
  2071. var candidate = value;
  2072. return Is.uinteger(candidate.startLine) && Is.uinteger(candidate.startLine)
  2073. && (Is.undefined(candidate.startCharacter) || Is.uinteger(candidate.startCharacter))
  2074. && (Is.undefined(candidate.endCharacter) || Is.uinteger(candidate.endCharacter))
  2075. && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
  2076. }
  2077. FoldingRange.is = is;
  2078. })(FoldingRange = exports.FoldingRange || (exports.FoldingRange = {}));
  2079. /**
  2080. * The DiagnosticRelatedInformation namespace provides helper functions to work with
  2081. * [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals.
  2082. */
  2083. var DiagnosticRelatedInformation;
  2084. (function (DiagnosticRelatedInformation) {
  2085. /**
  2086. * Creates a new DiagnosticRelatedInformation literal.
  2087. */
  2088. function create(location, message) {
  2089. return {
  2090. location: location,
  2091. message: message
  2092. };
  2093. }
  2094. DiagnosticRelatedInformation.create = create;
  2095. /**
  2096. * Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface.
  2097. */
  2098. function is(value) {
  2099. var candidate = value;
  2100. return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
  2101. }
  2102. DiagnosticRelatedInformation.is = is;
  2103. })(DiagnosticRelatedInformation = exports.DiagnosticRelatedInformation || (exports.DiagnosticRelatedInformation = {}));
  2104. /**
  2105. * The diagnostic's severity.
  2106. */
  2107. var DiagnosticSeverity;
  2108. (function (DiagnosticSeverity) {
  2109. /**
  2110. * Reports an error.
  2111. */
  2112. DiagnosticSeverity.Error = 1;
  2113. /**
  2114. * Reports a warning.
  2115. */
  2116. DiagnosticSeverity.Warning = 2;
  2117. /**
  2118. * Reports an information.
  2119. */
  2120. DiagnosticSeverity.Information = 3;
  2121. /**
  2122. * Reports a hint.
  2123. */
  2124. DiagnosticSeverity.Hint = 4;
  2125. })(DiagnosticSeverity = exports.DiagnosticSeverity || (exports.DiagnosticSeverity = {}));
  2126. /**
  2127. * The diagnostic tags.
  2128. *
  2129. * @since 3.15.0
  2130. */
  2131. var DiagnosticTag;
  2132. (function (DiagnosticTag) {
  2133. /**
  2134. * Unused or unnecessary code.
  2135. *
  2136. * Clients are allowed to render diagnostics with this tag faded out instead of having
  2137. * an error squiggle.
  2138. */
  2139. DiagnosticTag.Unnecessary = 1;
  2140. /**
  2141. * Deprecated or obsolete code.
  2142. *
  2143. * Clients are allowed to rendered diagnostics with this tag strike through.
  2144. */
  2145. DiagnosticTag.Deprecated = 2;
  2146. })(DiagnosticTag = exports.DiagnosticTag || (exports.DiagnosticTag = {}));
  2147. /**
  2148. * The CodeDescription namespace provides functions to deal with descriptions for diagnostic codes.
  2149. *
  2150. * @since 3.16.0
  2151. */
  2152. var CodeDescription;
  2153. (function (CodeDescription) {
  2154. function is(value) {
  2155. var candidate = value;
  2156. return candidate !== undefined && candidate !== null && Is.string(candidate.href);
  2157. }
  2158. CodeDescription.is = is;
  2159. })(CodeDescription = exports.CodeDescription || (exports.CodeDescription = {}));
  2160. /**
  2161. * The Diagnostic namespace provides helper functions to work with
  2162. * [Diagnostic](#Diagnostic) literals.
  2163. */
  2164. var Diagnostic;
  2165. (function (Diagnostic) {
  2166. /**
  2167. * Creates a new Diagnostic literal.
  2168. */
  2169. function create(range, message, severity, code, source, relatedInformation) {
  2170. var result = { range: range, message: message };
  2171. if (Is.defined(severity)) {
  2172. result.severity = severity;
  2173. }
  2174. if (Is.defined(code)) {
  2175. result.code = code;
  2176. }
  2177. if (Is.defined(source)) {
  2178. result.source = source;
  2179. }
  2180. if (Is.defined(relatedInformation)) {
  2181. result.relatedInformation = relatedInformation;
  2182. }
  2183. return result;
  2184. }
  2185. Diagnostic.create = create;
  2186. /**
  2187. * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface.
  2188. */
  2189. function is(value) {
  2190. var _a;
  2191. var candidate = value;
  2192. return Is.defined(candidate)
  2193. && Range.is(candidate.range)
  2194. && Is.string(candidate.message)
  2195. && (Is.number(candidate.severity) || Is.undefined(candidate.severity))
  2196. && (Is.integer(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))
  2197. && (Is.undefined(candidate.codeDescription) || (Is.string((_a = candidate.codeDescription) === null || _a === void 0 ? void 0 : _a.href)))
  2198. && (Is.string(candidate.source) || Is.undefined(candidate.source))
  2199. && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
  2200. }
  2201. Diagnostic.is = is;
  2202. })(Diagnostic = exports.Diagnostic || (exports.Diagnostic = {}));
  2203. /**
  2204. * The Command namespace provides helper functions to work with
  2205. * [Command](#Command) literals.
  2206. */
  2207. var Command;
  2208. (function (Command) {
  2209. /**
  2210. * Creates a new Command literal.
  2211. */
  2212. function create(title, command) {
  2213. var args = [];
  2214. for (var _i = 2; _i < arguments.length; _i++) {
  2215. args[_i - 2] = arguments[_i];
  2216. }
  2217. var result = { title: title, command: command };
  2218. if (Is.defined(args) && args.length > 0) {
  2219. result.arguments = args;
  2220. }
  2221. return result;
  2222. }
  2223. Command.create = create;
  2224. /**
  2225. * Checks whether the given literal conforms to the [Command](#Command) interface.
  2226. */
  2227. function is(value) {
  2228. var candidate = value;
  2229. return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
  2230. }
  2231. Command.is = is;
  2232. })(Command = exports.Command || (exports.Command = {}));
  2233. /**
  2234. * The TextEdit namespace provides helper function to create replace,
  2235. * insert and delete edits more easily.
  2236. */
  2237. var TextEdit;
  2238. (function (TextEdit) {
  2239. /**
  2240. * Creates a replace text edit.
  2241. * @param range The range of text to be replaced.
  2242. * @param newText The new text.
  2243. */
  2244. function replace(range, newText) {
  2245. return { range: range, newText: newText };
  2246. }
  2247. TextEdit.replace = replace;
  2248. /**
  2249. * Creates a insert text edit.
  2250. * @param position The position to insert the text at.
  2251. * @param newText The text to be inserted.
  2252. */
  2253. function insert(position, newText) {
  2254. return { range: { start: position, end: position }, newText: newText };
  2255. }
  2256. TextEdit.insert = insert;
  2257. /**
  2258. * Creates a delete text edit.
  2259. * @param range The range of text to be deleted.
  2260. */
  2261. function del(range) {
  2262. return { range: range, newText: '' };
  2263. }
  2264. TextEdit.del = del;
  2265. function is(value) {
  2266. var candidate = value;
  2267. return Is.objectLiteral(candidate)
  2268. && Is.string(candidate.newText)
  2269. && Range.is(candidate.range);
  2270. }
  2271. TextEdit.is = is;
  2272. })(TextEdit = exports.TextEdit || (exports.TextEdit = {}));
  2273. var ChangeAnnotation;
  2274. (function (ChangeAnnotation) {
  2275. function create(label, needsConfirmation, description) {
  2276. var result = { label: label };
  2277. if (needsConfirmation !== undefined) {
  2278. result.needsConfirmation = needsConfirmation;
  2279. }
  2280. if (description !== undefined) {
  2281. result.description = description;
  2282. }
  2283. return result;
  2284. }
  2285. ChangeAnnotation.create = create;
  2286. function is(value) {
  2287. var candidate = value;
  2288. return candidate !== undefined && Is.objectLiteral(candidate) && Is.string(candidate.label) &&
  2289. (Is.boolean(candidate.needsConfirmation) || candidate.needsConfirmation === undefined) &&
  2290. (Is.string(candidate.description) || candidate.description === undefined);
  2291. }
  2292. ChangeAnnotation.is = is;
  2293. })(ChangeAnnotation = exports.ChangeAnnotation || (exports.ChangeAnnotation = {}));
  2294. var ChangeAnnotationIdentifier;
  2295. (function (ChangeAnnotationIdentifier) {
  2296. function is(value) {
  2297. var candidate = value;
  2298. return typeof candidate === 'string';
  2299. }
  2300. ChangeAnnotationIdentifier.is = is;
  2301. })(ChangeAnnotationIdentifier = exports.ChangeAnnotationIdentifier || (exports.ChangeAnnotationIdentifier = {}));
  2302. var AnnotatedTextEdit;
  2303. (function (AnnotatedTextEdit) {
  2304. /**
  2305. * Creates an annotated replace text edit.
  2306. *
  2307. * @param range The range of text to be replaced.
  2308. * @param newText The new text.
  2309. * @param annotation The annotation.
  2310. */
  2311. function replace(range, newText, annotation) {
  2312. return { range: range, newText: newText, annotationId: annotation };
  2313. }
  2314. AnnotatedTextEdit.replace = replace;
  2315. /**
  2316. * Creates an annotated insert text edit.
  2317. *
  2318. * @param position The position to insert the text at.
  2319. * @param newText The text to be inserted.
  2320. * @param annotation The annotation.
  2321. */
  2322. function insert(position, newText, annotation) {
  2323. return { range: { start: position, end: position }, newText: newText, annotationId: annotation };
  2324. }
  2325. AnnotatedTextEdit.insert = insert;
  2326. /**
  2327. * Creates an annotated delete text edit.
  2328. *
  2329. * @param range The range of text to be deleted.
  2330. * @param annotation The annotation.
  2331. */
  2332. function del(range, annotation) {
  2333. return { range: range, newText: '', annotationId: annotation };
  2334. }
  2335. AnnotatedTextEdit.del = del;
  2336. function is(value) {
  2337. var candidate = value;
  2338. return TextEdit.is(candidate) && (ChangeAnnotation.is(candidate.annotationId) || ChangeAnnotationIdentifier.is(candidate.annotationId));
  2339. }
  2340. AnnotatedTextEdit.is = is;
  2341. })(AnnotatedTextEdit = exports.AnnotatedTextEdit || (exports.AnnotatedTextEdit = {}));
  2342. /**
  2343. * The TextDocumentEdit namespace provides helper function to create
  2344. * an edit that manipulates a text document.
  2345. */
  2346. var TextDocumentEdit;
  2347. (function (TextDocumentEdit) {
  2348. /**
  2349. * Creates a new `TextDocumentEdit`
  2350. */
  2351. function create(textDocument, edits) {
  2352. return { textDocument: textDocument, edits: edits };
  2353. }
  2354. TextDocumentEdit.create = create;
  2355. function is(value) {
  2356. var candidate = value;
  2357. return Is.defined(candidate)
  2358. && OptionalVersionedTextDocumentIdentifier.is(candidate.textDocument)
  2359. && Array.isArray(candidate.edits);
  2360. }
  2361. TextDocumentEdit.is = is;
  2362. })(TextDocumentEdit = exports.TextDocumentEdit || (exports.TextDocumentEdit = {}));
  2363. var CreateFile;
  2364. (function (CreateFile) {
  2365. function create(uri, options, annotation) {
  2366. var result = {
  2367. kind: 'create',
  2368. uri: uri
  2369. };
  2370. if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) {
  2371. result.options = options;
  2372. }
  2373. if (annotation !== undefined) {
  2374. result.annotationId = annotation;
  2375. }
  2376. return result;
  2377. }
  2378. CreateFile.create = create;
  2379. function is(value) {
  2380. var candidate = value;
  2381. return candidate && candidate.kind === 'create' && Is.string(candidate.uri) && (candidate.options === undefined ||
  2382. ((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));
  2383. }
  2384. CreateFile.is = is;
  2385. })(CreateFile = exports.CreateFile || (exports.CreateFile = {}));
  2386. var RenameFile;
  2387. (function (RenameFile) {
  2388. function create(oldUri, newUri, options, annotation) {
  2389. var result = {
  2390. kind: 'rename',
  2391. oldUri: oldUri,
  2392. newUri: newUri
  2393. };
  2394. if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) {
  2395. result.options = options;
  2396. }
  2397. if (annotation !== undefined) {
  2398. result.annotationId = annotation;
  2399. }
  2400. return result;
  2401. }
  2402. RenameFile.create = create;
  2403. function is(value) {
  2404. var candidate = value;
  2405. return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) && (candidate.options === undefined ||
  2406. ((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));
  2407. }
  2408. RenameFile.is = is;
  2409. })(RenameFile = exports.RenameFile || (exports.RenameFile = {}));
  2410. var DeleteFile;
  2411. (function (DeleteFile) {
  2412. function create(uri, options, annotation) {
  2413. var result = {
  2414. kind: 'delete',
  2415. uri: uri
  2416. };
  2417. if (options !== undefined && (options.recursive !== undefined || options.ignoreIfNotExists !== undefined)) {
  2418. result.options = options;
  2419. }
  2420. if (annotation !== undefined) {
  2421. result.annotationId = annotation;
  2422. }
  2423. return result;
  2424. }
  2425. DeleteFile.create = create;
  2426. function is(value) {
  2427. var candidate = value;
  2428. return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) && (candidate.options === undefined ||
  2429. ((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));
  2430. }
  2431. DeleteFile.is = is;
  2432. })(DeleteFile = exports.DeleteFile || (exports.DeleteFile = {}));
  2433. var WorkspaceEdit;
  2434. (function (WorkspaceEdit) {
  2435. function is(value) {
  2436. var candidate = value;
  2437. return candidate &&
  2438. (candidate.changes !== undefined || candidate.documentChanges !== undefined) &&
  2439. (candidate.documentChanges === undefined || candidate.documentChanges.every(function (change) {
  2440. if (Is.string(change.kind)) {
  2441. return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
  2442. }
  2443. else {
  2444. return TextDocumentEdit.is(change);
  2445. }
  2446. }));
  2447. }
  2448. WorkspaceEdit.is = is;
  2449. })(WorkspaceEdit = exports.WorkspaceEdit || (exports.WorkspaceEdit = {}));
  2450. var TextEditChangeImpl = /** @class */ (function () {
  2451. function TextEditChangeImpl(edits, changeAnnotations) {
  2452. this.edits = edits;
  2453. this.changeAnnotations = changeAnnotations;
  2454. }
  2455. TextEditChangeImpl.prototype.insert = function (position, newText, annotation) {
  2456. var edit;
  2457. var id;
  2458. if (annotation === undefined) {
  2459. edit = TextEdit.insert(position, newText);
  2460. }
  2461. else if (ChangeAnnotationIdentifier.is(annotation)) {
  2462. id = annotation;
  2463. edit = AnnotatedTextEdit.insert(position, newText, annotation);
  2464. }
  2465. else {
  2466. this.assertChangeAnnotations(this.changeAnnotations);
  2467. id = this.changeAnnotations.manage(annotation);
  2468. edit = AnnotatedTextEdit.insert(position, newText, id);
  2469. }
  2470. this.edits.push(edit);
  2471. if (id !== undefined) {
  2472. return id;
  2473. }
  2474. };
  2475. TextEditChangeImpl.prototype.replace = function (range, newText, annotation) {
  2476. var edit;
  2477. var id;
  2478. if (annotation === undefined) {
  2479. edit = TextEdit.replace(range, newText);
  2480. }
  2481. else if (ChangeAnnotationIdentifier.is(annotation)) {
  2482. id = annotation;
  2483. edit = AnnotatedTextEdit.replace(range, newText, annotation);
  2484. }
  2485. else {
  2486. this.assertChangeAnnotations(this.changeAnnotations);
  2487. id = this.changeAnnotations.manage(annotation);
  2488. edit = AnnotatedTextEdit.replace(range, newText, id);
  2489. }
  2490. this.edits.push(edit);
  2491. if (id !== undefined) {
  2492. return id;
  2493. }
  2494. };
  2495. TextEditChangeImpl.prototype.delete = function (range, annotation) {
  2496. var edit;
  2497. var id;
  2498. if (annotation === undefined) {
  2499. edit = TextEdit.del(range);
  2500. }
  2501. else if (ChangeAnnotationIdentifier.is(annotation)) {
  2502. id = annotation;
  2503. edit = AnnotatedTextEdit.del(range, annotation);
  2504. }
  2505. else {
  2506. this.assertChangeAnnotations(this.changeAnnotations);
  2507. id = this.changeAnnotations.manage(annotation);
  2508. edit = AnnotatedTextEdit.del(range, id);
  2509. }
  2510. this.edits.push(edit);
  2511. if (id !== undefined) {
  2512. return id;
  2513. }
  2514. };
  2515. TextEditChangeImpl.prototype.add = function (edit) {
  2516. this.edits.push(edit);
  2517. };
  2518. TextEditChangeImpl.prototype.all = function () {
  2519. return this.edits;
  2520. };
  2521. TextEditChangeImpl.prototype.clear = function () {
  2522. this.edits.splice(0, this.edits.length);
  2523. };
  2524. TextEditChangeImpl.prototype.assertChangeAnnotations = function (value) {
  2525. if (value === undefined) {
  2526. throw new Error("Text edit change is not configured to manage change annotations.");
  2527. }
  2528. };
  2529. return TextEditChangeImpl;
  2530. }());
  2531. /**
  2532. * A helper class
  2533. */
  2534. var ChangeAnnotations = /** @class */ (function () {
  2535. function ChangeAnnotations(annotations) {
  2536. this._annotations = annotations === undefined ? Object.create(null) : annotations;
  2537. this._counter = 0;
  2538. this._size = 0;
  2539. }
  2540. ChangeAnnotations.prototype.all = function () {
  2541. return this._annotations;
  2542. };
  2543. Object.defineProperty(ChangeAnnotations.prototype, "size", {
  2544. get: function () {
  2545. return this._size;
  2546. },
  2547. enumerable: false,
  2548. configurable: true
  2549. });
  2550. ChangeAnnotations.prototype.manage = function (idOrAnnotation, annotation) {
  2551. var id;
  2552. if (ChangeAnnotationIdentifier.is(idOrAnnotation)) {
  2553. id = idOrAnnotation;
  2554. }
  2555. else {
  2556. id = this.nextId();
  2557. annotation = idOrAnnotation;
  2558. }
  2559. if (this._annotations[id] !== undefined) {
  2560. throw new Error("Id " + id + " is already in use.");
  2561. }
  2562. if (annotation === undefined) {
  2563. throw new Error("No annotation provided for id " + id);
  2564. }
  2565. this._annotations[id] = annotation;
  2566. this._size++;
  2567. return id;
  2568. };
  2569. ChangeAnnotations.prototype.nextId = function () {
  2570. this._counter++;
  2571. return this._counter.toString();
  2572. };
  2573. return ChangeAnnotations;
  2574. }());
  2575. /**
  2576. * A workspace change helps constructing changes to a workspace.
  2577. */
  2578. var WorkspaceChange = /** @class */ (function () {
  2579. function WorkspaceChange(workspaceEdit) {
  2580. var _this = this;
  2581. this._textEditChanges = Object.create(null);
  2582. if (workspaceEdit !== undefined) {
  2583. this._workspaceEdit = workspaceEdit;
  2584. if (workspaceEdit.documentChanges) {
  2585. this._changeAnnotations = new ChangeAnnotations(workspaceEdit.changeAnnotations);
  2586. workspaceEdit.changeAnnotations = this._changeAnnotations.all();
  2587. workspaceEdit.documentChanges.forEach(function (change) {
  2588. if (TextDocumentEdit.is(change)) {
  2589. var textEditChange = new TextEditChangeImpl(change.edits, _this._changeAnnotations);
  2590. _this._textEditChanges[change.textDocument.uri] = textEditChange;
  2591. }
  2592. });
  2593. }
  2594. else if (workspaceEdit.changes) {
  2595. Object.keys(workspaceEdit.changes).forEach(function (key) {
  2596. var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
  2597. _this._textEditChanges[key] = textEditChange;
  2598. });
  2599. }
  2600. }
  2601. else {
  2602. this._workspaceEdit = {};
  2603. }
  2604. }
  2605. Object.defineProperty(WorkspaceChange.prototype, "edit", {
  2606. /**
  2607. * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal
  2608. * use to be returned from a workspace edit operation like rename.
  2609. */
  2610. get: function () {
  2611. this.initDocumentChanges();
  2612. if (this._changeAnnotations !== undefined) {
  2613. if (this._changeAnnotations.size === 0) {
  2614. this._workspaceEdit.changeAnnotations = undefined;
  2615. }
  2616. else {
  2617. this._workspaceEdit.changeAnnotations = this._changeAnnotations.all();
  2618. }
  2619. }
  2620. return this._workspaceEdit;
  2621. },
  2622. enumerable: false,
  2623. configurable: true
  2624. });
  2625. WorkspaceChange.prototype.getTextEditChange = function (key) {
  2626. if (OptionalVersionedTextDocumentIdentifier.is(key)) {
  2627. this.initDocumentChanges();
  2628. if (this._workspaceEdit.documentChanges === undefined) {
  2629. throw new Error('Workspace edit is not configured for document changes.');
  2630. }
  2631. var textDocument = { uri: key.uri, version: key.version };
  2632. var result = this._textEditChanges[textDocument.uri];
  2633. if (!result) {
  2634. var edits = [];
  2635. var textDocumentEdit = {
  2636. textDocument: textDocument,
  2637. edits: edits
  2638. };
  2639. this._workspaceEdit.documentChanges.push(textDocumentEdit);
  2640. result = new TextEditChangeImpl(edits, this._changeAnnotations);
  2641. this._textEditChanges[textDocument.uri] = result;
  2642. }
  2643. return result;
  2644. }
  2645. else {
  2646. this.initChanges();
  2647. if (this._workspaceEdit.changes === undefined) {
  2648. throw new Error('Workspace edit is not configured for normal text edit changes.');
  2649. }
  2650. var result = this._textEditChanges[key];
  2651. if (!result) {
  2652. var edits = [];
  2653. this._workspaceEdit.changes[key] = edits;
  2654. result = new TextEditChangeImpl(edits);
  2655. this._textEditChanges[key] = result;
  2656. }
  2657. return result;
  2658. }
  2659. };
  2660. WorkspaceChange.prototype.initDocumentChanges = function () {
  2661. if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) {
  2662. this._changeAnnotations = new ChangeAnnotations();
  2663. this._workspaceEdit.documentChanges = [];
  2664. this._workspaceEdit.changeAnnotations = this._changeAnnotations.all();
  2665. }
  2666. };
  2667. WorkspaceChange.prototype.initChanges = function () {
  2668. if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) {
  2669. this._workspaceEdit.changes = Object.create(null);
  2670. }
  2671. };
  2672. WorkspaceChange.prototype.createFile = function (uri, optionsOrAnnotation, options) {
  2673. this.initDocumentChanges();
  2674. if (this._workspaceEdit.documentChanges === undefined) {
  2675. throw new Error('Workspace edit is not configured for document changes.');
  2676. }
  2677. var annotation;
  2678. if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
  2679. annotation = optionsOrAnnotation;
  2680. }
  2681. else {
  2682. options = optionsOrAnnotation;
  2683. }
  2684. var operation;
  2685. var id;
  2686. if (annotation === undefined) {
  2687. operation = CreateFile.create(uri, options);
  2688. }
  2689. else {
  2690. id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
  2691. operation = CreateFile.create(uri, options, id);
  2692. }
  2693. this._workspaceEdit.documentChanges.push(operation);
  2694. if (id !== undefined) {
  2695. return id;
  2696. }
  2697. };
  2698. WorkspaceChange.prototype.renameFile = function (oldUri, newUri, optionsOrAnnotation, options) {
  2699. this.initDocumentChanges();
  2700. if (this._workspaceEdit.documentChanges === undefined) {
  2701. throw new Error('Workspace edit is not configured for document changes.');
  2702. }
  2703. var annotation;
  2704. if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
  2705. annotation = optionsOrAnnotation;
  2706. }
  2707. else {
  2708. options = optionsOrAnnotation;
  2709. }
  2710. var operation;
  2711. var id;
  2712. if (annotation === undefined) {
  2713. operation = RenameFile.create(oldUri, newUri, options);
  2714. }
  2715. else {
  2716. id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
  2717. operation = RenameFile.create(oldUri, newUri, options, id);
  2718. }
  2719. this._workspaceEdit.documentChanges.push(operation);
  2720. if (id !== undefined) {
  2721. return id;
  2722. }
  2723. };
  2724. WorkspaceChange.prototype.deleteFile = function (uri, optionsOrAnnotation, options) {
  2725. this.initDocumentChanges();
  2726. if (this._workspaceEdit.documentChanges === undefined) {
  2727. throw new Error('Workspace edit is not configured for document changes.');
  2728. }
  2729. var annotation;
  2730. if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
  2731. annotation = optionsOrAnnotation;
  2732. }
  2733. else {
  2734. options = optionsOrAnnotation;
  2735. }
  2736. var operation;
  2737. var id;
  2738. if (annotation === undefined) {
  2739. operation = DeleteFile.create(uri, options);
  2740. }
  2741. else {
  2742. id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
  2743. operation = DeleteFile.create(uri, options, id);
  2744. }
  2745. this._workspaceEdit.documentChanges.push(operation);
  2746. if (id !== undefined) {
  2747. return id;
  2748. }
  2749. };
  2750. return WorkspaceChange;
  2751. }());
  2752. exports.WorkspaceChange = WorkspaceChange;
  2753. /**
  2754. * The TextDocumentIdentifier namespace provides helper functions to work with
  2755. * [TextDocumentIdentifier](#TextDocumentIdentifier) literals.
  2756. */
  2757. var TextDocumentIdentifier;
  2758. (function (TextDocumentIdentifier) {
  2759. /**
  2760. * Creates a new TextDocumentIdentifier literal.
  2761. * @param uri The document's uri.
  2762. */
  2763. function create(uri) {
  2764. return { uri: uri };
  2765. }
  2766. TextDocumentIdentifier.create = create;
  2767. /**
  2768. * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface.
  2769. */
  2770. function is(value) {
  2771. var candidate = value;
  2772. return Is.defined(candidate) && Is.string(candidate.uri);
  2773. }
  2774. TextDocumentIdentifier.is = is;
  2775. })(TextDocumentIdentifier = exports.TextDocumentIdentifier || (exports.TextDocumentIdentifier = {}));
  2776. /**
  2777. * The VersionedTextDocumentIdentifier namespace provides helper functions to work with
  2778. * [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals.
  2779. */
  2780. var VersionedTextDocumentIdentifier;
  2781. (function (VersionedTextDocumentIdentifier) {
  2782. /**
  2783. * Creates a new VersionedTextDocumentIdentifier literal.
  2784. * @param uri The document's uri.
  2785. * @param uri The document's text.
  2786. */
  2787. function create(uri, version) {
  2788. return { uri: uri, version: version };
  2789. }
  2790. VersionedTextDocumentIdentifier.create = create;
  2791. /**
  2792. * Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface.
  2793. */
  2794. function is(value) {
  2795. var candidate = value;
  2796. return Is.defined(candidate) && Is.string(candidate.uri) && Is.integer(candidate.version);
  2797. }
  2798. VersionedTextDocumentIdentifier.is = is;
  2799. })(VersionedTextDocumentIdentifier = exports.VersionedTextDocumentIdentifier || (exports.VersionedTextDocumentIdentifier = {}));
  2800. /**
  2801. * The OptionalVersionedTextDocumentIdentifier namespace provides helper functions to work with
  2802. * [OptionalVersionedTextDocumentIdentifier](#OptionalVersionedTextDocumentIdentifier) literals.
  2803. */
  2804. var OptionalVersionedTextDocumentIdentifier;
  2805. (function (OptionalVersionedTextDocumentIdentifier) {
  2806. /**
  2807. * Creates a new OptionalVersionedTextDocumentIdentifier literal.
  2808. * @param uri The document's uri.
  2809. * @param uri The document's text.
  2810. */
  2811. function create(uri, version) {
  2812. return { uri: uri, version: version };
  2813. }
  2814. OptionalVersionedTextDocumentIdentifier.create = create;
  2815. /**
  2816. * Checks whether the given literal conforms to the [OptionalVersionedTextDocumentIdentifier](#OptionalVersionedTextDocumentIdentifier) interface.
  2817. */
  2818. function is(value) {
  2819. var candidate = value;
  2820. return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.integer(candidate.version));
  2821. }
  2822. OptionalVersionedTextDocumentIdentifier.is = is;
  2823. })(OptionalVersionedTextDocumentIdentifier = exports.OptionalVersionedTextDocumentIdentifier || (exports.OptionalVersionedTextDocumentIdentifier = {}));
  2824. /**
  2825. * The TextDocumentItem namespace provides helper functions to work with
  2826. * [TextDocumentItem](#TextDocumentItem) literals.
  2827. */
  2828. var TextDocumentItem;
  2829. (function (TextDocumentItem) {
  2830. /**
  2831. * Creates a new TextDocumentItem literal.
  2832. * @param uri The document's uri.
  2833. * @param languageId The document's language identifier.
  2834. * @param version The document's version number.
  2835. * @param text The document's text.
  2836. */
  2837. function create(uri, languageId, version, text) {
  2838. return { uri: uri, languageId: languageId, version: version, text: text };
  2839. }
  2840. TextDocumentItem.create = create;
  2841. /**
  2842. * Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface.
  2843. */
  2844. function is(value) {
  2845. var candidate = value;
  2846. return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.integer(candidate.version) && Is.string(candidate.text);
  2847. }
  2848. TextDocumentItem.is = is;
  2849. })(TextDocumentItem = exports.TextDocumentItem || (exports.TextDocumentItem = {}));
  2850. /**
  2851. * Describes the content type that a client supports in various
  2852. * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
  2853. *
  2854. * Please note that `MarkupKinds` must not start with a `$`. This kinds
  2855. * are reserved for internal usage.
  2856. */
  2857. var MarkupKind;
  2858. (function (MarkupKind) {
  2859. /**
  2860. * Plain text is supported as a content format
  2861. */
  2862. MarkupKind.PlainText = 'plaintext';
  2863. /**
  2864. * Markdown is supported as a content format
  2865. */
  2866. MarkupKind.Markdown = 'markdown';
  2867. })(MarkupKind = exports.MarkupKind || (exports.MarkupKind = {}));
  2868. (function (MarkupKind) {
  2869. /**
  2870. * Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type.
  2871. */
  2872. function is(value) {
  2873. var candidate = value;
  2874. return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;
  2875. }
  2876. MarkupKind.is = is;
  2877. })(MarkupKind = exports.MarkupKind || (exports.MarkupKind = {}));
  2878. var MarkupContent;
  2879. (function (MarkupContent) {
  2880. /**
  2881. * Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface.
  2882. */
  2883. function is(value) {
  2884. var candidate = value;
  2885. return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
  2886. }
  2887. MarkupContent.is = is;
  2888. })(MarkupContent = exports.MarkupContent || (exports.MarkupContent = {}));
  2889. /**
  2890. * The kind of a completion entry.
  2891. */
  2892. var CompletionItemKind;
  2893. (function (CompletionItemKind) {
  2894. CompletionItemKind.Text = 1;
  2895. CompletionItemKind.Method = 2;
  2896. CompletionItemKind.Function = 3;
  2897. CompletionItemKind.Constructor = 4;
  2898. CompletionItemKind.Field = 5;
  2899. CompletionItemKind.Variable = 6;
  2900. CompletionItemKind.Class = 7;
  2901. CompletionItemKind.Interface = 8;
  2902. CompletionItemKind.Module = 9;
  2903. CompletionItemKind.Property = 10;
  2904. CompletionItemKind.Unit = 11;
  2905. CompletionItemKind.Value = 12;
  2906. CompletionItemKind.Enum = 13;
  2907. CompletionItemKind.Keyword = 14;
  2908. CompletionItemKind.Snippet = 15;
  2909. CompletionItemKind.Color = 16;
  2910. CompletionItemKind.File = 17;
  2911. CompletionItemKind.Reference = 18;
  2912. CompletionItemKind.Folder = 19;
  2913. CompletionItemKind.EnumMember = 20;
  2914. CompletionItemKind.Constant = 21;
  2915. CompletionItemKind.Struct = 22;
  2916. CompletionItemKind.Event = 23;
  2917. CompletionItemKind.Operator = 24;
  2918. CompletionItemKind.TypeParameter = 25;
  2919. })(CompletionItemKind = exports.CompletionItemKind || (exports.CompletionItemKind = {}));
  2920. /**
  2921. * Defines whether the insert text in a completion item should be interpreted as
  2922. * plain text or a snippet.
  2923. */
  2924. var InsertTextFormat;
  2925. (function (InsertTextFormat) {
  2926. /**
  2927. * The primary text to be inserted is treated as a plain string.
  2928. */
  2929. InsertTextFormat.PlainText = 1;
  2930. /**
  2931. * The primary text to be inserted is treated as a snippet.
  2932. *
  2933. * A snippet can define tab stops and placeholders with `$1`, `$2`
  2934. * and `${3:foo}`. `$0` defines the final tab stop, it defaults to
  2935. * the end of the snippet. Placeholders with equal identifiers are linked,
  2936. * that is typing in one will update others too.
  2937. *
  2938. * See also: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#snippet_syntax
  2939. */
  2940. InsertTextFormat.Snippet = 2;
  2941. })(InsertTextFormat = exports.InsertTextFormat || (exports.InsertTextFormat = {}));
  2942. /**
  2943. * Completion item tags are extra annotations that tweak the rendering of a completion
  2944. * item.
  2945. *
  2946. * @since 3.15.0
  2947. */
  2948. var CompletionItemTag;
  2949. (function (CompletionItemTag) {
  2950. /**
  2951. * Render a completion as obsolete, usually using a strike-out.
  2952. */
  2953. CompletionItemTag.Deprecated = 1;
  2954. })(CompletionItemTag = exports.CompletionItemTag || (exports.CompletionItemTag = {}));
  2955. /**
  2956. * The InsertReplaceEdit namespace provides functions to deal with insert / replace edits.
  2957. *
  2958. * @since 3.16.0
  2959. */
  2960. var InsertReplaceEdit;
  2961. (function (InsertReplaceEdit) {
  2962. /**
  2963. * Creates a new insert / replace edit
  2964. */
  2965. function create(newText, insert, replace) {
  2966. return { newText: newText, insert: insert, replace: replace };
  2967. }
  2968. InsertReplaceEdit.create = create;
  2969. /**
  2970. * Checks whether the given literal conforms to the [InsertReplaceEdit](#InsertReplaceEdit) interface.
  2971. */
  2972. function is(value) {
  2973. var candidate = value;
  2974. return candidate && Is.string(candidate.newText) && Range.is(candidate.insert) && Range.is(candidate.replace);
  2975. }
  2976. InsertReplaceEdit.is = is;
  2977. })(InsertReplaceEdit = exports.InsertReplaceEdit || (exports.InsertReplaceEdit = {}));
  2978. /**
  2979. * How whitespace and indentation is handled during completion
  2980. * item insertion.
  2981. *
  2982. * @since 3.16.0
  2983. */
  2984. var InsertTextMode;
  2985. (function (InsertTextMode) {
  2986. /**
  2987. * The insertion or replace strings is taken as it is. If the
  2988. * value is multi line the lines below the cursor will be
  2989. * inserted using the indentation defined in the string value.
  2990. * The client will not apply any kind of adjustments to the
  2991. * string.
  2992. */
  2993. InsertTextMode.asIs = 1;
  2994. /**
  2995. * The editor adjusts leading whitespace of new lines so that
  2996. * they match the indentation up to the cursor of the line for
  2997. * which the item is accepted.
  2998. *
  2999. * Consider a line like this: <2tabs><cursor><3tabs>foo. Accepting a
  3000. * multi line completion item is indented using 2 tabs and all
  3001. * following lines inserted will be indented using 2 tabs as well.
  3002. */
  3003. InsertTextMode.adjustIndentation = 2;
  3004. })(InsertTextMode = exports.InsertTextMode || (exports.InsertTextMode = {}));
  3005. /**
  3006. * The CompletionItem namespace provides functions to deal with
  3007. * completion items.
  3008. */
  3009. var CompletionItem;
  3010. (function (CompletionItem) {
  3011. /**
  3012. * Create a completion item and seed it with a label.
  3013. * @param label The completion item's label
  3014. */
  3015. function create(label) {
  3016. return { label: label };
  3017. }
  3018. CompletionItem.create = create;
  3019. })(CompletionItem = exports.CompletionItem || (exports.CompletionItem = {}));
  3020. /**
  3021. * The CompletionList namespace provides functions to deal with
  3022. * completion lists.
  3023. */
  3024. var CompletionList;
  3025. (function (CompletionList) {
  3026. /**
  3027. * Creates a new completion list.
  3028. *
  3029. * @param items The completion items.
  3030. * @param isIncomplete The list is not complete.
  3031. */
  3032. function create(items, isIncomplete) {
  3033. return { items: items ? items : [], isIncomplete: !!isIncomplete };
  3034. }
  3035. CompletionList.create = create;
  3036. })(CompletionList = exports.CompletionList || (exports.CompletionList = {}));
  3037. var MarkedString;
  3038. (function (MarkedString) {
  3039. /**
  3040. * Creates a marked string from plain text.
  3041. *
  3042. * @param plainText The plain text.
  3043. */
  3044. function fromPlainText(plainText) {
  3045. return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
  3046. }
  3047. MarkedString.fromPlainText = fromPlainText;
  3048. /**
  3049. * Checks whether the given value conforms to the [MarkedString](#MarkedString) type.
  3050. */
  3051. function is(value) {
  3052. var candidate = value;
  3053. return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));
  3054. }
  3055. MarkedString.is = is;
  3056. })(MarkedString = exports.MarkedString || (exports.MarkedString = {}));
  3057. var Hover;
  3058. (function (Hover) {
  3059. /**
  3060. * Checks whether the given value conforms to the [Hover](#Hover) interface.
  3061. */
  3062. function is(value) {
  3063. var candidate = value;
  3064. return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||
  3065. MarkedString.is(candidate.contents) ||
  3066. Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === undefined || Range.is(value.range));
  3067. }
  3068. Hover.is = is;
  3069. })(Hover = exports.Hover || (exports.Hover = {}));
  3070. /**
  3071. * The ParameterInformation namespace provides helper functions to work with
  3072. * [ParameterInformation](#ParameterInformation) literals.
  3073. */
  3074. var ParameterInformation;
  3075. (function (ParameterInformation) {
  3076. /**
  3077. * Creates a new parameter information literal.
  3078. *
  3079. * @param label A label string.
  3080. * @param documentation A doc string.
  3081. */
  3082. function create(label, documentation) {
  3083. return documentation ? { label: label, documentation: documentation } : { label: label };
  3084. }
  3085. ParameterInformation.create = create;
  3086. })(ParameterInformation = exports.ParameterInformation || (exports.ParameterInformation = {}));
  3087. /**
  3088. * The SignatureInformation namespace provides helper functions to work with
  3089. * [SignatureInformation](#SignatureInformation) literals.
  3090. */
  3091. var SignatureInformation;
  3092. (function (SignatureInformation) {
  3093. function create(label, documentation) {
  3094. var parameters = [];
  3095. for (var _i = 2; _i < arguments.length; _i++) {
  3096. parameters[_i - 2] = arguments[_i];
  3097. }
  3098. var result = { label: label };
  3099. if (Is.defined(documentation)) {
  3100. result.documentation = documentation;
  3101. }
  3102. if (Is.defined(parameters)) {
  3103. result.parameters = parameters;
  3104. }
  3105. else {
  3106. result.parameters = [];
  3107. }
  3108. return result;
  3109. }
  3110. SignatureInformation.create = create;
  3111. })(SignatureInformation = exports.SignatureInformation || (exports.SignatureInformation = {}));
  3112. /**
  3113. * A document highlight kind.
  3114. */
  3115. var DocumentHighlightKind;
  3116. (function (DocumentHighlightKind) {
  3117. /**
  3118. * A textual occurrence.
  3119. */
  3120. DocumentHighlightKind.Text = 1;
  3121. /**
  3122. * Read-access of a symbol, like reading a variable.
  3123. */
  3124. DocumentHighlightKind.Read = 2;
  3125. /**
  3126. * Write-access of a symbol, like writing to a variable.
  3127. */
  3128. DocumentHighlightKind.Write = 3;
  3129. })(DocumentHighlightKind = exports.DocumentHighlightKind || (exports.DocumentHighlightKind = {}));
  3130. /**
  3131. * DocumentHighlight namespace to provide helper functions to work with
  3132. * [DocumentHighlight](#DocumentHighlight) literals.
  3133. */
  3134. var DocumentHighlight;
  3135. (function (DocumentHighlight) {
  3136. /**
  3137. * Create a DocumentHighlight object.
  3138. * @param range The range the highlight applies to.
  3139. */
  3140. function create(range, kind) {
  3141. var result = { range: range };
  3142. if (Is.number(kind)) {
  3143. result.kind = kind;
  3144. }
  3145. return result;
  3146. }
  3147. DocumentHighlight.create = create;
  3148. })(DocumentHighlight = exports.DocumentHighlight || (exports.DocumentHighlight = {}));
  3149. /**
  3150. * A symbol kind.
  3151. */
  3152. var SymbolKind;
  3153. (function (SymbolKind) {
  3154. SymbolKind.File = 1;
  3155. SymbolKind.Module = 2;
  3156. SymbolKind.Namespace = 3;
  3157. SymbolKind.Package = 4;
  3158. SymbolKind.Class = 5;
  3159. SymbolKind.Method = 6;
  3160. SymbolKind.Property = 7;
  3161. SymbolKind.Field = 8;
  3162. SymbolKind.Constructor = 9;
  3163. SymbolKind.Enum = 10;
  3164. SymbolKind.Interface = 11;
  3165. SymbolKind.Function = 12;
  3166. SymbolKind.Variable = 13;
  3167. SymbolKind.Constant = 14;
  3168. SymbolKind.String = 15;
  3169. SymbolKind.Number = 16;
  3170. SymbolKind.Boolean = 17;
  3171. SymbolKind.Array = 18;
  3172. SymbolKind.Object = 19;
  3173. SymbolKind.Key = 20;
  3174. SymbolKind.Null = 21;
  3175. SymbolKind.EnumMember = 22;
  3176. SymbolKind.Struct = 23;
  3177. SymbolKind.Event = 24;
  3178. SymbolKind.Operator = 25;
  3179. SymbolKind.TypeParameter = 26;
  3180. })(SymbolKind = exports.SymbolKind || (exports.SymbolKind = {}));
  3181. /**
  3182. * Symbol tags are extra annotations that tweak the rendering of a symbol.
  3183. * @since 3.16
  3184. */
  3185. var SymbolTag;
  3186. (function (SymbolTag) {
  3187. /**
  3188. * Render a symbol as obsolete, usually using a strike-out.
  3189. */
  3190. SymbolTag.Deprecated = 1;
  3191. })(SymbolTag = exports.SymbolTag || (exports.SymbolTag = {}));
  3192. var SymbolInformation;
  3193. (function (SymbolInformation) {
  3194. /**
  3195. * Creates a new symbol information literal.
  3196. *
  3197. * @param name The name of the symbol.
  3198. * @param kind The kind of the symbol.
  3199. * @param range The range of the location of the symbol.
  3200. * @param uri The resource of the location of symbol, defaults to the current document.
  3201. * @param containerName The name of the symbol containing the symbol.
  3202. */
  3203. function create(name, kind, range, uri, containerName) {
  3204. var result = {
  3205. name: name,
  3206. kind: kind,
  3207. location: { uri: uri, range: range }
  3208. };
  3209. if (containerName) {
  3210. result.containerName = containerName;
  3211. }
  3212. return result;
  3213. }
  3214. SymbolInformation.create = create;
  3215. })(SymbolInformation = exports.SymbolInformation || (exports.SymbolInformation = {}));
  3216. var DocumentSymbol;
  3217. (function (DocumentSymbol) {
  3218. /**
  3219. * Creates a new symbol information literal.
  3220. *
  3221. * @param name The name of the symbol.
  3222. * @param detail The detail of the symbol.
  3223. * @param kind The kind of the symbol.
  3224. * @param range The range of the symbol.
  3225. * @param selectionRange The selectionRange of the symbol.
  3226. * @param children Children of the symbol.
  3227. */
  3228. function create(name, detail, kind, range, selectionRange, children) {
  3229. var result = {
  3230. name: name,
  3231. detail: detail,
  3232. kind: kind,
  3233. range: range,
  3234. selectionRange: selectionRange
  3235. };
  3236. if (children !== undefined) {
  3237. result.children = children;
  3238. }
  3239. return result;
  3240. }
  3241. DocumentSymbol.create = create;
  3242. /**
  3243. * Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface.
  3244. */
  3245. function is(value) {
  3246. var candidate = value;
  3247. return candidate &&
  3248. Is.string(candidate.name) && Is.number(candidate.kind) &&
  3249. Range.is(candidate.range) && Range.is(candidate.selectionRange) &&
  3250. (candidate.detail === undefined || Is.string(candidate.detail)) &&
  3251. (candidate.deprecated === undefined || Is.boolean(candidate.deprecated)) &&
  3252. (candidate.children === undefined || Array.isArray(candidate.children)) &&
  3253. (candidate.tags === undefined || Array.isArray(candidate.tags));
  3254. }
  3255. DocumentSymbol.is = is;
  3256. })(DocumentSymbol = exports.DocumentSymbol || (exports.DocumentSymbol = {}));
  3257. /**
  3258. * A set of predefined code action kinds
  3259. */
  3260. var CodeActionKind;
  3261. (function (CodeActionKind) {
  3262. /**
  3263. * Empty kind.
  3264. */
  3265. CodeActionKind.Empty = '';
  3266. /**
  3267. * Base kind for quickfix actions: 'quickfix'
  3268. */
  3269. CodeActionKind.QuickFix = 'quickfix';
  3270. /**
  3271. * Base kind for refactoring actions: 'refactor'
  3272. */
  3273. CodeActionKind.Refactor = 'refactor';
  3274. /**
  3275. * Base kind for refactoring extraction actions: 'refactor.extract'
  3276. *
  3277. * Example extract actions:
  3278. *
  3279. * - Extract method
  3280. * - Extract function
  3281. * - Extract variable
  3282. * - Extract interface from class
  3283. * - ...
  3284. */
  3285. CodeActionKind.RefactorExtract = 'refactor.extract';
  3286. /**
  3287. * Base kind for refactoring inline actions: 'refactor.inline'
  3288. *
  3289. * Example inline actions:
  3290. *
  3291. * - Inline function
  3292. * - Inline variable
  3293. * - Inline constant
  3294. * - ...
  3295. */
  3296. CodeActionKind.RefactorInline = 'refactor.inline';
  3297. /**
  3298. * Base kind for refactoring rewrite actions: 'refactor.rewrite'
  3299. *
  3300. * Example rewrite actions:
  3301. *
  3302. * - Convert JavaScript function to class
  3303. * - Add or remove parameter
  3304. * - Encapsulate field
  3305. * - Make method static
  3306. * - Move method to base class
  3307. * - ...
  3308. */
  3309. CodeActionKind.RefactorRewrite = 'refactor.rewrite';
  3310. /**
  3311. * Base kind for source actions: `source`
  3312. *
  3313. * Source code actions apply to the entire file.
  3314. */
  3315. CodeActionKind.Source = 'source';
  3316. /**
  3317. * Base kind for an organize imports source action: `source.organizeImports`
  3318. */
  3319. CodeActionKind.SourceOrganizeImports = 'source.organizeImports';
  3320. /**
  3321. * Base kind for auto-fix source actions: `source.fixAll`.
  3322. *
  3323. * Fix all actions automatically fix errors that have a clear fix that do not require user input.
  3324. * They should not suppress errors or perform unsafe fixes such as generating new types or classes.
  3325. *
  3326. * @since 3.15.0
  3327. */
  3328. CodeActionKind.SourceFixAll = 'source.fixAll';
  3329. })(CodeActionKind = exports.CodeActionKind || (exports.CodeActionKind = {}));
  3330. /**
  3331. * The CodeActionContext namespace provides helper functions to work with
  3332. * [CodeActionContext](#CodeActionContext) literals.
  3333. */
  3334. var CodeActionContext;
  3335. (function (CodeActionContext) {
  3336. /**
  3337. * Creates a new CodeActionContext literal.
  3338. */
  3339. function create(diagnostics, only) {
  3340. var result = { diagnostics: diagnostics };
  3341. if (only !== undefined && only !== null) {
  3342. result.only = only;
  3343. }
  3344. return result;
  3345. }
  3346. CodeActionContext.create = create;
  3347. /**
  3348. * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface.
  3349. */
  3350. function is(value) {
  3351. var candidate = value;
  3352. return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === undefined || Is.typedArray(candidate.only, Is.string));
  3353. }
  3354. CodeActionContext.is = is;
  3355. })(CodeActionContext = exports.CodeActionContext || (exports.CodeActionContext = {}));
  3356. var CodeAction;
  3357. (function (CodeAction) {
  3358. function create(title, kindOrCommandOrEdit, kind) {
  3359. var result = { title: title };
  3360. var checkKind = true;
  3361. if (typeof kindOrCommandOrEdit === 'string') {
  3362. checkKind = false;
  3363. result.kind = kindOrCommandOrEdit;
  3364. }
  3365. else if (Command.is(kindOrCommandOrEdit)) {
  3366. result.command = kindOrCommandOrEdit;
  3367. }
  3368. else {
  3369. result.edit = kindOrCommandOrEdit;
  3370. }
  3371. if (checkKind && kind !== undefined) {
  3372. result.kind = kind;
  3373. }
  3374. return result;
  3375. }
  3376. CodeAction.create = create;
  3377. function is(value) {
  3378. var candidate = value;
  3379. return candidate && Is.string(candidate.title) &&
  3380. (candidate.diagnostics === undefined || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&
  3381. (candidate.kind === undefined || Is.string(candidate.kind)) &&
  3382. (candidate.edit !== undefined || candidate.command !== undefined) &&
  3383. (candidate.command === undefined || Command.is(candidate.command)) &&
  3384. (candidate.isPreferred === undefined || Is.boolean(candidate.isPreferred)) &&
  3385. (candidate.edit === undefined || WorkspaceEdit.is(candidate.edit));
  3386. }
  3387. CodeAction.is = is;
  3388. })(CodeAction = exports.CodeAction || (exports.CodeAction = {}));
  3389. /**
  3390. * The CodeLens namespace provides helper functions to work with
  3391. * [CodeLens](#CodeLens) literals.
  3392. */
  3393. var CodeLens;
  3394. (function (CodeLens) {
  3395. /**
  3396. * Creates a new CodeLens literal.
  3397. */
  3398. function create(range, data) {
  3399. var result = { range: range };
  3400. if (Is.defined(data)) {
  3401. result.data = data;
  3402. }
  3403. return result;
  3404. }
  3405. CodeLens.create = create;
  3406. /**
  3407. * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface.
  3408. */
  3409. function is(value) {
  3410. var candidate = value;
  3411. return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
  3412. }
  3413. CodeLens.is = is;
  3414. })(CodeLens = exports.CodeLens || (exports.CodeLens = {}));
  3415. /**
  3416. * The FormattingOptions namespace provides helper functions to work with
  3417. * [FormattingOptions](#FormattingOptions) literals.
  3418. */
  3419. var FormattingOptions;
  3420. (function (FormattingOptions) {
  3421. /**
  3422. * Creates a new FormattingOptions literal.
  3423. */
  3424. function create(tabSize, insertSpaces) {
  3425. return { tabSize: tabSize, insertSpaces: insertSpaces };
  3426. }
  3427. FormattingOptions.create = create;
  3428. /**
  3429. * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface.
  3430. */
  3431. function is(value) {
  3432. var candidate = value;
  3433. return Is.defined(candidate) && Is.uinteger(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
  3434. }
  3435. FormattingOptions.is = is;
  3436. })(FormattingOptions = exports.FormattingOptions || (exports.FormattingOptions = {}));
  3437. /**
  3438. * The DocumentLink namespace provides helper functions to work with
  3439. * [DocumentLink](#DocumentLink) literals.
  3440. */
  3441. var DocumentLink;
  3442. (function (DocumentLink) {
  3443. /**
  3444. * Creates a new DocumentLink literal.
  3445. */
  3446. function create(range, target, data) {
  3447. return { range: range, target: target, data: data };
  3448. }
  3449. DocumentLink.create = create;
  3450. /**
  3451. * Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface.
  3452. */
  3453. function is(value) {
  3454. var candidate = value;
  3455. return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
  3456. }
  3457. DocumentLink.is = is;
  3458. })(DocumentLink = exports.DocumentLink || (exports.DocumentLink = {}));
  3459. /**
  3460. * The SelectionRange namespace provides helper function to work with
  3461. * SelectionRange literals.
  3462. */
  3463. var SelectionRange;
  3464. (function (SelectionRange) {
  3465. /**
  3466. * Creates a new SelectionRange
  3467. * @param range the range.
  3468. * @param parent an optional parent.
  3469. */
  3470. function create(range, parent) {
  3471. return { range: range, parent: parent };
  3472. }
  3473. SelectionRange.create = create;
  3474. function is(value) {
  3475. var candidate = value;
  3476. return candidate !== undefined && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));
  3477. }
  3478. SelectionRange.is = is;
  3479. })(SelectionRange = exports.SelectionRange || (exports.SelectionRange = {}));
  3480. exports.EOL = ['\n', '\r\n', '\r'];
  3481. /**
  3482. * @deprecated Use the text document from the new vscode-languageserver-textdocument package.
  3483. */
  3484. var TextDocument;
  3485. (function (TextDocument) {
  3486. /**
  3487. * Creates a new ITextDocument literal from the given uri and content.
  3488. * @param uri The document's uri.
  3489. * @param languageId The document's language Id.
  3490. * @param content The document's content.
  3491. */
  3492. function create(uri, languageId, version, content) {
  3493. return new FullTextDocument(uri, languageId, version, content);
  3494. }
  3495. TextDocument.create = create;
  3496. /**
  3497. * Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface.
  3498. */
  3499. function is(value) {
  3500. var candidate = value;
  3501. return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.uinteger(candidate.lineCount)
  3502. && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
  3503. }
  3504. TextDocument.is = is;
  3505. function applyEdits(document, edits) {
  3506. var text = document.getText();
  3507. var sortedEdits = mergeSort(edits, function (a, b) {
  3508. var diff = a.range.start.line - b.range.start.line;
  3509. if (diff === 0) {
  3510. return a.range.start.character - b.range.start.character;
  3511. }
  3512. return diff;
  3513. });
  3514. var lastModifiedOffset = text.length;
  3515. for (var i = sortedEdits.length - 1; i >= 0; i--) {
  3516. var e = sortedEdits[i];
  3517. var startOffset = document.offsetAt(e.range.start);
  3518. var endOffset = document.offsetAt(e.range.end);
  3519. if (endOffset <= lastModifiedOffset) {
  3520. text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
  3521. }
  3522. else {
  3523. throw new Error('Overlapping edit');
  3524. }
  3525. lastModifiedOffset = startOffset;
  3526. }
  3527. return text;
  3528. }
  3529. TextDocument.applyEdits = applyEdits;
  3530. function mergeSort(data, compare) {
  3531. if (data.length <= 1) {
  3532. // sorted
  3533. return data;
  3534. }
  3535. var p = (data.length / 2) | 0;
  3536. var left = data.slice(0, p);
  3537. var right = data.slice(p);
  3538. mergeSort(left, compare);
  3539. mergeSort(right, compare);
  3540. var leftIdx = 0;
  3541. var rightIdx = 0;
  3542. var i = 0;
  3543. while (leftIdx < left.length && rightIdx < right.length) {
  3544. var ret = compare(left[leftIdx], right[rightIdx]);
  3545. if (ret <= 0) {
  3546. // smaller_equal -> take left to preserve order
  3547. data[i++] = left[leftIdx++];
  3548. }
  3549. else {
  3550. // greater -> take right
  3551. data[i++] = right[rightIdx++];
  3552. }
  3553. }
  3554. while (leftIdx < left.length) {
  3555. data[i++] = left[leftIdx++];
  3556. }
  3557. while (rightIdx < right.length) {
  3558. data[i++] = right[rightIdx++];
  3559. }
  3560. return data;
  3561. }
  3562. })(TextDocument = exports.TextDocument || (exports.TextDocument = {}));
  3563. /**
  3564. * @deprecated Use the text document from the new vscode-languageserver-textdocument package.
  3565. */
  3566. var FullTextDocument = /** @class */ (function () {
  3567. function FullTextDocument(uri, languageId, version, content) {
  3568. this._uri = uri;
  3569. this._languageId = languageId;
  3570. this._version = version;
  3571. this._content = content;
  3572. this._lineOffsets = undefined;
  3573. }
  3574. Object.defineProperty(FullTextDocument.prototype, "uri", {
  3575. get: function () {
  3576. return this._uri;
  3577. },
  3578. enumerable: false,
  3579. configurable: true
  3580. });
  3581. Object.defineProperty(FullTextDocument.prototype, "languageId", {
  3582. get: function () {
  3583. return this._languageId;
  3584. },
  3585. enumerable: false,
  3586. configurable: true
  3587. });
  3588. Object.defineProperty(FullTextDocument.prototype, "version", {
  3589. get: function () {
  3590. return this._version;
  3591. },
  3592. enumerable: false,
  3593. configurable: true
  3594. });
  3595. FullTextDocument.prototype.getText = function (range) {
  3596. if (range) {
  3597. var start = this.offsetAt(range.start);
  3598. var end = this.offsetAt(range.end);
  3599. return this._content.substring(start, end);
  3600. }
  3601. return this._content;
  3602. };
  3603. FullTextDocument.prototype.update = function (event, version) {
  3604. this._content = event.text;
  3605. this._version = version;
  3606. this._lineOffsets = undefined;
  3607. };
  3608. FullTextDocument.prototype.getLineOffsets = function () {
  3609. if (this._lineOffsets === undefined) {
  3610. var lineOffsets = [];
  3611. var text = this._content;
  3612. var isLineStart = true;
  3613. for (var i = 0; i < text.length; i++) {
  3614. if (isLineStart) {
  3615. lineOffsets.push(i);
  3616. isLineStart = false;
  3617. }
  3618. var ch = text.charAt(i);
  3619. isLineStart = (ch === '\r' || ch === '\n');
  3620. if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {
  3621. i++;
  3622. }
  3623. }
  3624. if (isLineStart && text.length > 0) {
  3625. lineOffsets.push(text.length);
  3626. }
  3627. this._lineOffsets = lineOffsets;
  3628. }
  3629. return this._lineOffsets;
  3630. };
  3631. FullTextDocument.prototype.positionAt = function (offset) {
  3632. offset = Math.max(Math.min(offset, this._content.length), 0);
  3633. var lineOffsets = this.getLineOffsets();
  3634. var low = 0, high = lineOffsets.length;
  3635. if (high === 0) {
  3636. return Position.create(0, offset);
  3637. }
  3638. while (low < high) {
  3639. var mid = Math.floor((low + high) / 2);
  3640. if (lineOffsets[mid] > offset) {
  3641. high = mid;
  3642. }
  3643. else {
  3644. low = mid + 1;
  3645. }
  3646. }
  3647. // low is the least x for which the line offset is larger than the current offset
  3648. // or array.length if no line offset is larger than the current offset
  3649. var line = low - 1;
  3650. return Position.create(line, offset - lineOffsets[line]);
  3651. };
  3652. FullTextDocument.prototype.offsetAt = function (position) {
  3653. var lineOffsets = this.getLineOffsets();
  3654. if (position.line >= lineOffsets.length) {
  3655. return this._content.length;
  3656. }
  3657. else if (position.line < 0) {
  3658. return 0;
  3659. }
  3660. var lineOffset = lineOffsets[position.line];
  3661. var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
  3662. return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
  3663. };
  3664. Object.defineProperty(FullTextDocument.prototype, "lineCount", {
  3665. get: function () {
  3666. return this.getLineOffsets().length;
  3667. },
  3668. enumerable: false,
  3669. configurable: true
  3670. });
  3671. return FullTextDocument;
  3672. }());
  3673. var Is;
  3674. (function (Is) {
  3675. var toString = Object.prototype.toString;
  3676. function defined(value) {
  3677. return typeof value !== 'undefined';
  3678. }
  3679. Is.defined = defined;
  3680. function undefined(value) {
  3681. return typeof value === 'undefined';
  3682. }
  3683. Is.undefined = undefined;
  3684. function boolean(value) {
  3685. return value === true || value === false;
  3686. }
  3687. Is.boolean = boolean;
  3688. function string(value) {
  3689. return toString.call(value) === '[object String]';
  3690. }
  3691. Is.string = string;
  3692. function number(value) {
  3693. return toString.call(value) === '[object Number]';
  3694. }
  3695. Is.number = number;
  3696. function numberRange(value, min, max) {
  3697. return toString.call(value) === '[object Number]' && min <= value && value <= max;
  3698. }
  3699. Is.numberRange = numberRange;
  3700. function integer(value) {
  3701. return toString.call(value) === '[object Number]' && -2147483648 <= value && value <= 2147483647;
  3702. }
  3703. Is.integer = integer;
  3704. function uinteger(value) {
  3705. return toString.call(value) === '[object Number]' && 0 <= value && value <= 2147483647;
  3706. }
  3707. Is.uinteger = uinteger;
  3708. function func(value) {
  3709. return toString.call(value) === '[object Function]';
  3710. }
  3711. Is.func = func;
  3712. function objectLiteral(value) {
  3713. // Strictly speaking class instances pass this check as well. Since the LSP
  3714. // doesn't use classes we ignore this for now. If we do we need to add something
  3715. // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
  3716. return value !== null && typeof value === 'object';
  3717. }
  3718. Is.objectLiteral = objectLiteral;
  3719. function typedArray(value, check) {
  3720. return Array.isArray(value) && value.every(check);
  3721. }
  3722. Is.typedArray = typedArray;
  3723. })(Is || (Is = {}));
  3724. });
  3725. //# sourceMappingURL=main.js.map;
  3726. define('vscode-languageserver-types', ['vscode-languageserver-types/main'], function (main) { return main; });
  3727. (function (factory) {
  3728. if (typeof module === "object" && typeof module.exports === "object") {
  3729. var v = factory(require, exports);
  3730. if (v !== undefined) module.exports = v;
  3731. }
  3732. else if (typeof define === "function" && define.amd) {
  3733. define('vscode-languageserver-textdocument/main',["require", "exports"], factory);
  3734. }
  3735. })(function (require, exports) {
  3736. /* --------------------------------------------------------------------------------------------
  3737. * Copyright (c) Microsoft Corporation. All rights reserved.
  3738. * Licensed under the MIT License. See License.txt in the project root for license information.
  3739. * ------------------------------------------------------------------------------------------ */
  3740. 'use strict';
  3741. Object.defineProperty(exports, "__esModule", { value: true });
  3742. var FullTextDocument = /** @class */ (function () {
  3743. function FullTextDocument(uri, languageId, version, content) {
  3744. this._uri = uri;
  3745. this._languageId = languageId;
  3746. this._version = version;
  3747. this._content = content;
  3748. this._lineOffsets = undefined;
  3749. }
  3750. Object.defineProperty(FullTextDocument.prototype, "uri", {
  3751. get: function () {
  3752. return this._uri;
  3753. },
  3754. enumerable: true,
  3755. configurable: true
  3756. });
  3757. Object.defineProperty(FullTextDocument.prototype, "languageId", {
  3758. get: function () {
  3759. return this._languageId;
  3760. },
  3761. enumerable: true,
  3762. configurable: true
  3763. });
  3764. Object.defineProperty(FullTextDocument.prototype, "version", {
  3765. get: function () {
  3766. return this._version;
  3767. },
  3768. enumerable: true,
  3769. configurable: true
  3770. });
  3771. FullTextDocument.prototype.getText = function (range) {
  3772. if (range) {
  3773. var start = this.offsetAt(range.start);
  3774. var end = this.offsetAt(range.end);
  3775. return this._content.substring(start, end);
  3776. }
  3777. return this._content;
  3778. };
  3779. FullTextDocument.prototype.update = function (changes, version) {
  3780. for (var _i = 0, changes_1 = changes; _i < changes_1.length; _i++) {
  3781. var change = changes_1[_i];
  3782. if (FullTextDocument.isIncremental(change)) {
  3783. // makes sure start is before end
  3784. var range = getWellformedRange(change.range);
  3785. // update content
  3786. var startOffset = this.offsetAt(range.start);
  3787. var endOffset = this.offsetAt(range.end);
  3788. this._content = this._content.substring(0, startOffset) + change.text + this._content.substring(endOffset, this._content.length);
  3789. // update the offsets
  3790. var startLine = Math.max(range.start.line, 0);
  3791. var endLine = Math.max(range.end.line, 0);
  3792. var lineOffsets = this._lineOffsets;
  3793. var addedLineOffsets = computeLineOffsets(change.text, false, startOffset);
  3794. if (endLine - startLine === addedLineOffsets.length) {
  3795. for (var i = 0, len = addedLineOffsets.length; i < len; i++) {
  3796. lineOffsets[i + startLine + 1] = addedLineOffsets[i];
  3797. }
  3798. }
  3799. else {
  3800. if (addedLineOffsets.length < 10000) {
  3801. lineOffsets.splice.apply(lineOffsets, [startLine + 1, endLine - startLine].concat(addedLineOffsets));
  3802. }
  3803. else { // avoid too many arguments for splice
  3804. this._lineOffsets = lineOffsets = lineOffsets.slice(0, startLine + 1).concat(addedLineOffsets, lineOffsets.slice(endLine + 1));
  3805. }
  3806. }
  3807. var diff = change.text.length - (endOffset - startOffset);
  3808. if (diff !== 0) {
  3809. for (var i = startLine + 1 + addedLineOffsets.length, len = lineOffsets.length; i < len; i++) {
  3810. lineOffsets[i] = lineOffsets[i] + diff;
  3811. }
  3812. }
  3813. }
  3814. else if (FullTextDocument.isFull(change)) {
  3815. this._content = change.text;
  3816. this._lineOffsets = undefined;
  3817. }
  3818. else {
  3819. throw new Error('Unknown change event received');
  3820. }
  3821. }
  3822. this._version = version;
  3823. };
  3824. FullTextDocument.prototype.getLineOffsets = function () {
  3825. if (this._lineOffsets === undefined) {
  3826. this._lineOffsets = computeLineOffsets(this._content, true);
  3827. }
  3828. return this._lineOffsets;
  3829. };
  3830. FullTextDocument.prototype.positionAt = function (offset) {
  3831. offset = Math.max(Math.min(offset, this._content.length), 0);
  3832. var lineOffsets = this.getLineOffsets();
  3833. var low = 0, high = lineOffsets.length;
  3834. if (high === 0) {
  3835. return { line: 0, character: offset };
  3836. }
  3837. while (low < high) {
  3838. var mid = Math.floor((low + high) / 2);
  3839. if (lineOffsets[mid] > offset) {
  3840. high = mid;
  3841. }
  3842. else {
  3843. low = mid + 1;
  3844. }
  3845. }
  3846. // low is the least x for which the line offset is larger than the current offset
  3847. // or array.length if no line offset is larger than the current offset
  3848. var line = low - 1;
  3849. return { line: line, character: offset - lineOffsets[line] };
  3850. };
  3851. FullTextDocument.prototype.offsetAt = function (position) {
  3852. var lineOffsets = this.getLineOffsets();
  3853. if (position.line >= lineOffsets.length) {
  3854. return this._content.length;
  3855. }
  3856. else if (position.line < 0) {
  3857. return 0;
  3858. }
  3859. var lineOffset = lineOffsets[position.line];
  3860. var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
  3861. return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
  3862. };
  3863. Object.defineProperty(FullTextDocument.prototype, "lineCount", {
  3864. get: function () {
  3865. return this.getLineOffsets().length;
  3866. },
  3867. enumerable: true,
  3868. configurable: true
  3869. });
  3870. FullTextDocument.isIncremental = function (event) {
  3871. var candidate = event;
  3872. return candidate !== undefined && candidate !== null &&
  3873. typeof candidate.text === 'string' && candidate.range !== undefined &&
  3874. (candidate.rangeLength === undefined || typeof candidate.rangeLength === 'number');
  3875. };
  3876. FullTextDocument.isFull = function (event) {
  3877. var candidate = event;
  3878. return candidate !== undefined && candidate !== null &&
  3879. typeof candidate.text === 'string' && candidate.range === undefined && candidate.rangeLength === undefined;
  3880. };
  3881. return FullTextDocument;
  3882. }());
  3883. var TextDocument;
  3884. (function (TextDocument) {
  3885. /**
  3886. * Creates a new text document.
  3887. *
  3888. * @param uri The document's uri.
  3889. * @param languageId The document's language Id.
  3890. * @param version The document's initial version number.
  3891. * @param content The document's content.
  3892. */
  3893. function create(uri, languageId, version, content) {
  3894. return new FullTextDocument(uri, languageId, version, content);
  3895. }
  3896. TextDocument.create = create;
  3897. /**
  3898. * Updates a TextDocument by modifing its content.
  3899. *
  3900. * @param document the document to update. Only documents created by TextDocument.create are valid inputs.
  3901. * @param changes the changes to apply to the document.
  3902. * @returns The updated TextDocument. Note: That's the same document instance passed in as first parameter.
  3903. *
  3904. */
  3905. function update(document, changes, version) {
  3906. if (document instanceof FullTextDocument) {
  3907. document.update(changes, version);
  3908. return document;
  3909. }
  3910. else {
  3911. throw new Error('TextDocument.update: document must be created by TextDocument.create');
  3912. }
  3913. }
  3914. TextDocument.update = update;
  3915. function applyEdits(document, edits) {
  3916. var text = document.getText();
  3917. var sortedEdits = mergeSort(edits.map(getWellformedEdit), function (a, b) {
  3918. var diff = a.range.start.line - b.range.start.line;
  3919. if (diff === 0) {
  3920. return a.range.start.character - b.range.start.character;
  3921. }
  3922. return diff;
  3923. });
  3924. var lastModifiedOffset = 0;
  3925. var spans = [];
  3926. for (var _i = 0, sortedEdits_1 = sortedEdits; _i < sortedEdits_1.length; _i++) {
  3927. var e = sortedEdits_1[_i];
  3928. var startOffset = document.offsetAt(e.range.start);
  3929. if (startOffset < lastModifiedOffset) {
  3930. throw new Error('Overlapping edit');
  3931. }
  3932. else if (startOffset > lastModifiedOffset) {
  3933. spans.push(text.substring(lastModifiedOffset, startOffset));
  3934. }
  3935. if (e.newText.length) {
  3936. spans.push(e.newText);
  3937. }
  3938. lastModifiedOffset = document.offsetAt(e.range.end);
  3939. }
  3940. spans.push(text.substr(lastModifiedOffset));
  3941. return spans.join('');
  3942. }
  3943. TextDocument.applyEdits = applyEdits;
  3944. })(TextDocument = exports.TextDocument || (exports.TextDocument = {}));
  3945. function mergeSort(data, compare) {
  3946. if (data.length <= 1) {
  3947. // sorted
  3948. return data;
  3949. }
  3950. var p = (data.length / 2) | 0;
  3951. var left = data.slice(0, p);
  3952. var right = data.slice(p);
  3953. mergeSort(left, compare);
  3954. mergeSort(right, compare);
  3955. var leftIdx = 0;
  3956. var rightIdx = 0;
  3957. var i = 0;
  3958. while (leftIdx < left.length && rightIdx < right.length) {
  3959. var ret = compare(left[leftIdx], right[rightIdx]);
  3960. if (ret <= 0) {
  3961. // smaller_equal -> take left to preserve order
  3962. data[i++] = left[leftIdx++];
  3963. }
  3964. else {
  3965. // greater -> take right
  3966. data[i++] = right[rightIdx++];
  3967. }
  3968. }
  3969. while (leftIdx < left.length) {
  3970. data[i++] = left[leftIdx++];
  3971. }
  3972. while (rightIdx < right.length) {
  3973. data[i++] = right[rightIdx++];
  3974. }
  3975. return data;
  3976. }
  3977. function computeLineOffsets(text, isAtLineStart, textOffset) {
  3978. if (textOffset === void 0) { textOffset = 0; }
  3979. var result = isAtLineStart ? [textOffset] : [];
  3980. for (var i = 0; i < text.length; i++) {
  3981. var ch = text.charCodeAt(i);
  3982. if (ch === 13 /* CarriageReturn */ || ch === 10 /* LineFeed */) {
  3983. if (ch === 13 /* CarriageReturn */ && i + 1 < text.length && text.charCodeAt(i + 1) === 10 /* LineFeed */) {
  3984. i++;
  3985. }
  3986. result.push(textOffset + i + 1);
  3987. }
  3988. }
  3989. return result;
  3990. }
  3991. function getWellformedRange(range) {
  3992. var start = range.start;
  3993. var end = range.end;
  3994. if (start.line > end.line || (start.line === end.line && start.character > end.character)) {
  3995. return { start: end, end: start };
  3996. }
  3997. return range;
  3998. }
  3999. function getWellformedEdit(textEdit) {
  4000. var range = getWellformedRange(textEdit.range);
  4001. if (range !== textEdit.range) {
  4002. return { newText: textEdit.newText, range: range };
  4003. }
  4004. return textEdit;
  4005. }
  4006. });
  4007. define('vscode-languageserver-textdocument', ['vscode-languageserver-textdocument/main'], function (main) { return main; });
  4008. /*---------------------------------------------------------------------------------------------
  4009. * Copyright (c) Microsoft Corporation. All rights reserved.
  4010. * Licensed under the MIT License. See License.txt in the project root for license information.
  4011. *--------------------------------------------------------------------------------------------*/
  4012. (function (factory) {
  4013. if (typeof module === "object" && typeof module.exports === "object") {
  4014. var v = factory(require, exports);
  4015. if (v !== undefined) module.exports = v;
  4016. }
  4017. else if (typeof define === "function" && define.amd) {
  4018. define('vscode-json-languageservice/jsonLanguageTypes',["require", "exports", "vscode-languageserver-types", "vscode-languageserver-textdocument"], factory);
  4019. }
  4020. })(function (require, exports) {
  4021. "use strict";
  4022. Object.defineProperty(exports, "__esModule", { value: true });
  4023. 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;
  4024. var vscode_languageserver_types_1 = require("vscode-languageserver-types");
  4025. Object.defineProperty(exports, "Range", { enumerable: true, get: function () { return vscode_languageserver_types_1.Range; } });
  4026. Object.defineProperty(exports, "Position", { enumerable: true, get: function () { return vscode_languageserver_types_1.Position; } });
  4027. Object.defineProperty(exports, "MarkupContent", { enumerable: true, get: function () { return vscode_languageserver_types_1.MarkupContent; } });
  4028. Object.defineProperty(exports, "MarkupKind", { enumerable: true, get: function () { return vscode_languageserver_types_1.MarkupKind; } });
  4029. Object.defineProperty(exports, "Color", { enumerable: true, get: function () { return vscode_languageserver_types_1.Color; } });
  4030. Object.defineProperty(exports, "ColorInformation", { enumerable: true, get: function () { return vscode_languageserver_types_1.ColorInformation; } });
  4031. Object.defineProperty(exports, "ColorPresentation", { enumerable: true, get: function () { return vscode_languageserver_types_1.ColorPresentation; } });
  4032. Object.defineProperty(exports, "FoldingRange", { enumerable: true, get: function () { return vscode_languageserver_types_1.FoldingRange; } });
  4033. Object.defineProperty(exports, "FoldingRangeKind", { enumerable: true, get: function () { return vscode_languageserver_types_1.FoldingRangeKind; } });
  4034. Object.defineProperty(exports, "SelectionRange", { enumerable: true, get: function () { return vscode_languageserver_types_1.SelectionRange; } });
  4035. Object.defineProperty(exports, "Diagnostic", { enumerable: true, get: function () { return vscode_languageserver_types_1.Diagnostic; } });
  4036. Object.defineProperty(exports, "DiagnosticSeverity", { enumerable: true, get: function () { return vscode_languageserver_types_1.DiagnosticSeverity; } });
  4037. Object.defineProperty(exports, "CompletionItem", { enumerable: true, get: function () { return vscode_languageserver_types_1.CompletionItem; } });
  4038. Object.defineProperty(exports, "CompletionItemKind", { enumerable: true, get: function () { return vscode_languageserver_types_1.CompletionItemKind; } });
  4039. Object.defineProperty(exports, "CompletionList", { enumerable: true, get: function () { return vscode_languageserver_types_1.CompletionList; } });
  4040. Object.defineProperty(exports, "CompletionItemTag", { enumerable: true, get: function () { return vscode_languageserver_types_1.CompletionItemTag; } });
  4041. Object.defineProperty(exports, "InsertTextFormat", { enumerable: true, get: function () { return vscode_languageserver_types_1.InsertTextFormat; } });
  4042. Object.defineProperty(exports, "SymbolInformation", { enumerable: true, get: function () { return vscode_languageserver_types_1.SymbolInformation; } });
  4043. Object.defineProperty(exports, "SymbolKind", { enumerable: true, get: function () { return vscode_languageserver_types_1.SymbolKind; } });
  4044. Object.defineProperty(exports, "DocumentSymbol", { enumerable: true, get: function () { return vscode_languageserver_types_1.DocumentSymbol; } });
  4045. Object.defineProperty(exports, "Location", { enumerable: true, get: function () { return vscode_languageserver_types_1.Location; } });
  4046. Object.defineProperty(exports, "Hover", { enumerable: true, get: function () { return vscode_languageserver_types_1.Hover; } });
  4047. Object.defineProperty(exports, "MarkedString", { enumerable: true, get: function () { return vscode_languageserver_types_1.MarkedString; } });
  4048. Object.defineProperty(exports, "CodeActionContext", { enumerable: true, get: function () { return vscode_languageserver_types_1.CodeActionContext; } });
  4049. Object.defineProperty(exports, "Command", { enumerable: true, get: function () { return vscode_languageserver_types_1.Command; } });
  4050. Object.defineProperty(exports, "CodeAction", { enumerable: true, get: function () { return vscode_languageserver_types_1.CodeAction; } });
  4051. Object.defineProperty(exports, "DocumentHighlight", { enumerable: true, get: function () { return vscode_languageserver_types_1.DocumentHighlight; } });
  4052. Object.defineProperty(exports, "DocumentLink", { enumerable: true, get: function () { return vscode_languageserver_types_1.DocumentLink; } });
  4053. Object.defineProperty(exports, "WorkspaceEdit", { enumerable: true, get: function () { return vscode_languageserver_types_1.WorkspaceEdit; } });
  4054. Object.defineProperty(exports, "TextEdit", { enumerable: true, get: function () { return vscode_languageserver_types_1.TextEdit; } });
  4055. Object.defineProperty(exports, "CodeActionKind", { enumerable: true, get: function () { return vscode_languageserver_types_1.CodeActionKind; } });
  4056. Object.defineProperty(exports, "TextDocumentEdit", { enumerable: true, get: function () { return vscode_languageserver_types_1.TextDocumentEdit; } });
  4057. Object.defineProperty(exports, "VersionedTextDocumentIdentifier", { enumerable: true, get: function () { return vscode_languageserver_types_1.VersionedTextDocumentIdentifier; } });
  4058. Object.defineProperty(exports, "DocumentHighlightKind", { enumerable: true, get: function () { return vscode_languageserver_types_1.DocumentHighlightKind; } });
  4059. var vscode_languageserver_textdocument_1 = require("vscode-languageserver-textdocument");
  4060. Object.defineProperty(exports, "TextDocument", { enumerable: true, get: function () { return vscode_languageserver_textdocument_1.TextDocument; } });
  4061. /**
  4062. * Error codes used by diagnostics
  4063. */
  4064. var ErrorCode;
  4065. (function (ErrorCode) {
  4066. ErrorCode[ErrorCode["Undefined"] = 0] = "Undefined";
  4067. ErrorCode[ErrorCode["EnumValueMismatch"] = 1] = "EnumValueMismatch";
  4068. ErrorCode[ErrorCode["Deprecated"] = 2] = "Deprecated";
  4069. ErrorCode[ErrorCode["UnexpectedEndOfComment"] = 257] = "UnexpectedEndOfComment";
  4070. ErrorCode[ErrorCode["UnexpectedEndOfString"] = 258] = "UnexpectedEndOfString";
  4071. ErrorCode[ErrorCode["UnexpectedEndOfNumber"] = 259] = "UnexpectedEndOfNumber";
  4072. ErrorCode[ErrorCode["InvalidUnicode"] = 260] = "InvalidUnicode";
  4073. ErrorCode[ErrorCode["InvalidEscapeCharacter"] = 261] = "InvalidEscapeCharacter";
  4074. ErrorCode[ErrorCode["InvalidCharacter"] = 262] = "InvalidCharacter";
  4075. ErrorCode[ErrorCode["PropertyExpected"] = 513] = "PropertyExpected";
  4076. ErrorCode[ErrorCode["CommaExpected"] = 514] = "CommaExpected";
  4077. ErrorCode[ErrorCode["ColonExpected"] = 515] = "ColonExpected";
  4078. ErrorCode[ErrorCode["ValueExpected"] = 516] = "ValueExpected";
  4079. ErrorCode[ErrorCode["CommaOrCloseBacketExpected"] = 517] = "CommaOrCloseBacketExpected";
  4080. ErrorCode[ErrorCode["CommaOrCloseBraceExpected"] = 518] = "CommaOrCloseBraceExpected";
  4081. ErrorCode[ErrorCode["TrailingComma"] = 519] = "TrailingComma";
  4082. ErrorCode[ErrorCode["DuplicateKey"] = 520] = "DuplicateKey";
  4083. ErrorCode[ErrorCode["CommentNotPermitted"] = 521] = "CommentNotPermitted";
  4084. ErrorCode[ErrorCode["SchemaResolveError"] = 768] = "SchemaResolveError";
  4085. })(ErrorCode = exports.ErrorCode || (exports.ErrorCode = {}));
  4086. var ClientCapabilities;
  4087. (function (ClientCapabilities) {
  4088. ClientCapabilities.LATEST = {
  4089. textDocument: {
  4090. completion: {
  4091. completionItem: {
  4092. documentationFormat: [vscode_languageserver_types_1.MarkupKind.Markdown, vscode_languageserver_types_1.MarkupKind.PlainText],
  4093. commitCharactersSupport: true
  4094. }
  4095. }
  4096. }
  4097. };
  4098. })(ClientCapabilities = exports.ClientCapabilities || (exports.ClientCapabilities = {}));
  4099. });
  4100. /*---------------------------------------------------------------------------------------------
  4101. * Copyright (c) Microsoft Corporation. All rights reserved.
  4102. * Licensed under the MIT License. See License.txt in the project root for license information.
  4103. *--------------------------------------------------------------------------------------------*/
  4104. define('vscode-nls/vscode-nls',["require", "exports"], function (require, exports) {
  4105. "use strict";
  4106. Object.defineProperty(exports, "__esModule", { value: true });
  4107. exports.config = exports.loadMessageBundle = void 0;
  4108. function format(message, args) {
  4109. var result;
  4110. if (args.length === 0) {
  4111. result = message;
  4112. }
  4113. else {
  4114. result = message.replace(/\{(\d+)\}/g, function (match, rest) {
  4115. var index = rest[0];
  4116. return typeof args[index] !== 'undefined' ? args[index] : match;
  4117. });
  4118. }
  4119. return result;
  4120. }
  4121. function localize(key, message) {
  4122. var args = [];
  4123. for (var _i = 2; _i < arguments.length; _i++) {
  4124. args[_i - 2] = arguments[_i];
  4125. }
  4126. return format(message, args);
  4127. }
  4128. function loadMessageBundle(file) {
  4129. return localize;
  4130. }
  4131. exports.loadMessageBundle = loadMessageBundle;
  4132. function config(opt) {
  4133. return loadMessageBundle;
  4134. }
  4135. exports.config = config;
  4136. });
  4137. define('vscode-nls', ['vscode-nls/vscode-nls'], function (main) { return main; });
  4138. /*---------------------------------------------------------------------------------------------
  4139. * Copyright (c) Microsoft Corporation. All rights reserved.
  4140. * Licensed under the MIT License. See License.txt in the project root for license information.
  4141. *--------------------------------------------------------------------------------------------*/
  4142. var __extends = (this && this.__extends) || (function () {
  4143. var extendStatics = function (d, b) {
  4144. extendStatics = Object.setPrototypeOf ||
  4145. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4146. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  4147. return extendStatics(d, b);
  4148. };
  4149. return function (d, b) {
  4150. if (typeof b !== "function" && b !== null)
  4151. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  4152. extendStatics(d, b);
  4153. function __() { this.constructor = d; }
  4154. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4155. };
  4156. })();
  4157. (function (factory) {
  4158. if (typeof module === "object" && typeof module.exports === "object") {
  4159. var v = factory(require, exports);
  4160. if (v !== undefined) module.exports = v;
  4161. }
  4162. else if (typeof define === "function" && define.amd) {
  4163. define('vscode-json-languageservice/parser/jsonParser',["require", "exports", "jsonc-parser", "../utils/objects", "../utils/strings", "../jsonLanguageTypes", "vscode-nls"], factory);
  4164. }
  4165. })(function (require, exports) {
  4166. "use strict";
  4167. Object.defineProperty(exports, "__esModule", { value: true });
  4168. 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;
  4169. var Json = require("jsonc-parser");
  4170. var objects_1 = require("../utils/objects");
  4171. var strings_1 = require("../utils/strings");
  4172. var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
  4173. var nls = require("vscode-nls");
  4174. var localize = nls.loadMessageBundle();
  4175. var formats = {
  4176. '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})$/ },
  4177. '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 },
  4178. '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 },
  4179. '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 },
  4180. '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,}))$/ }
  4181. };
  4182. var ASTNodeImpl = /** @class */ (function () {
  4183. function ASTNodeImpl(parent, offset, length) {
  4184. if (length === void 0) { length = 0; }
  4185. this.offset = offset;
  4186. this.length = length;
  4187. this.parent = parent;
  4188. }
  4189. Object.defineProperty(ASTNodeImpl.prototype, "children", {
  4190. get: function () {
  4191. return [];
  4192. },
  4193. enumerable: false,
  4194. configurable: true
  4195. });
  4196. ASTNodeImpl.prototype.toString = function () {
  4197. return 'type: ' + this.type + ' (' + this.offset + '/' + this.length + ')' + (this.parent ? ' parent: {' + this.parent.toString() + '}' : '');
  4198. };
  4199. return ASTNodeImpl;
  4200. }());
  4201. exports.ASTNodeImpl = ASTNodeImpl;
  4202. var NullASTNodeImpl = /** @class */ (function (_super) {
  4203. __extends(NullASTNodeImpl, _super);
  4204. function NullASTNodeImpl(parent, offset) {
  4205. var _this = _super.call(this, parent, offset) || this;
  4206. _this.type = 'null';
  4207. _this.value = null;
  4208. return _this;
  4209. }
  4210. return NullASTNodeImpl;
  4211. }(ASTNodeImpl));
  4212. exports.NullASTNodeImpl = NullASTNodeImpl;
  4213. var BooleanASTNodeImpl = /** @class */ (function (_super) {
  4214. __extends(BooleanASTNodeImpl, _super);
  4215. function BooleanASTNodeImpl(parent, boolValue, offset) {
  4216. var _this = _super.call(this, parent, offset) || this;
  4217. _this.type = 'boolean';
  4218. _this.value = boolValue;
  4219. return _this;
  4220. }
  4221. return BooleanASTNodeImpl;
  4222. }(ASTNodeImpl));
  4223. exports.BooleanASTNodeImpl = BooleanASTNodeImpl;
  4224. var ArrayASTNodeImpl = /** @class */ (function (_super) {
  4225. __extends(ArrayASTNodeImpl, _super);
  4226. function ArrayASTNodeImpl(parent, offset) {
  4227. var _this = _super.call(this, parent, offset) || this;
  4228. _this.type = 'array';
  4229. _this.items = [];
  4230. return _this;
  4231. }
  4232. Object.defineProperty(ArrayASTNodeImpl.prototype, "children", {
  4233. get: function () {
  4234. return this.items;
  4235. },
  4236. enumerable: false,
  4237. configurable: true
  4238. });
  4239. return ArrayASTNodeImpl;
  4240. }(ASTNodeImpl));
  4241. exports.ArrayASTNodeImpl = ArrayASTNodeImpl;
  4242. var NumberASTNodeImpl = /** @class */ (function (_super) {
  4243. __extends(NumberASTNodeImpl, _super);
  4244. function NumberASTNodeImpl(parent, offset) {
  4245. var _this = _super.call(this, parent, offset) || this;
  4246. _this.type = 'number';
  4247. _this.isInteger = true;
  4248. _this.value = Number.NaN;
  4249. return _this;
  4250. }
  4251. return NumberASTNodeImpl;
  4252. }(ASTNodeImpl));
  4253. exports.NumberASTNodeImpl = NumberASTNodeImpl;
  4254. var StringASTNodeImpl = /** @class */ (function (_super) {
  4255. __extends(StringASTNodeImpl, _super);
  4256. function StringASTNodeImpl(parent, offset, length) {
  4257. var _this = _super.call(this, parent, offset, length) || this;
  4258. _this.type = 'string';
  4259. _this.value = '';
  4260. return _this;
  4261. }
  4262. return StringASTNodeImpl;
  4263. }(ASTNodeImpl));
  4264. exports.StringASTNodeImpl = StringASTNodeImpl;
  4265. var PropertyASTNodeImpl = /** @class */ (function (_super) {
  4266. __extends(PropertyASTNodeImpl, _super);
  4267. function PropertyASTNodeImpl(parent, offset, keyNode) {
  4268. var _this = _super.call(this, parent, offset) || this;
  4269. _this.type = 'property';
  4270. _this.colonOffset = -1;
  4271. _this.keyNode = keyNode;
  4272. return _this;
  4273. }
  4274. Object.defineProperty(PropertyASTNodeImpl.prototype, "children", {
  4275. get: function () {
  4276. return this.valueNode ? [this.keyNode, this.valueNode] : [this.keyNode];
  4277. },
  4278. enumerable: false,
  4279. configurable: true
  4280. });
  4281. return PropertyASTNodeImpl;
  4282. }(ASTNodeImpl));
  4283. exports.PropertyASTNodeImpl = PropertyASTNodeImpl;
  4284. var ObjectASTNodeImpl = /** @class */ (function (_super) {
  4285. __extends(ObjectASTNodeImpl, _super);
  4286. function ObjectASTNodeImpl(parent, offset) {
  4287. var _this = _super.call(this, parent, offset) || this;
  4288. _this.type = 'object';
  4289. _this.properties = [];
  4290. return _this;
  4291. }
  4292. Object.defineProperty(ObjectASTNodeImpl.prototype, "children", {
  4293. get: function () {
  4294. return this.properties;
  4295. },
  4296. enumerable: false,
  4297. configurable: true
  4298. });
  4299. return ObjectASTNodeImpl;
  4300. }(ASTNodeImpl));
  4301. exports.ObjectASTNodeImpl = ObjectASTNodeImpl;
  4302. function asSchema(schema) {
  4303. if (objects_1.isBoolean(schema)) {
  4304. return schema ? {} : { "not": {} };
  4305. }
  4306. return schema;
  4307. }
  4308. exports.asSchema = asSchema;
  4309. var EnumMatch;
  4310. (function (EnumMatch) {
  4311. EnumMatch[EnumMatch["Key"] = 0] = "Key";
  4312. EnumMatch[EnumMatch["Enum"] = 1] = "Enum";
  4313. })(EnumMatch = exports.EnumMatch || (exports.EnumMatch = {}));
  4314. var SchemaCollector = /** @class */ (function () {
  4315. function SchemaCollector(focusOffset, exclude) {
  4316. if (focusOffset === void 0) { focusOffset = -1; }
  4317. this.focusOffset = focusOffset;
  4318. this.exclude = exclude;
  4319. this.schemas = [];
  4320. }
  4321. SchemaCollector.prototype.add = function (schema) {
  4322. this.schemas.push(schema);
  4323. };
  4324. SchemaCollector.prototype.merge = function (other) {
  4325. Array.prototype.push.apply(this.schemas, other.schemas);
  4326. };
  4327. SchemaCollector.prototype.include = function (node) {
  4328. return (this.focusOffset === -1 || contains(node, this.focusOffset)) && (node !== this.exclude);
  4329. };
  4330. SchemaCollector.prototype.newSub = function () {
  4331. return new SchemaCollector(-1, this.exclude);
  4332. };
  4333. return SchemaCollector;
  4334. }());
  4335. var NoOpSchemaCollector = /** @class */ (function () {
  4336. function NoOpSchemaCollector() {
  4337. }
  4338. Object.defineProperty(NoOpSchemaCollector.prototype, "schemas", {
  4339. get: function () { return []; },
  4340. enumerable: false,
  4341. configurable: true
  4342. });
  4343. NoOpSchemaCollector.prototype.add = function (schema) { };
  4344. NoOpSchemaCollector.prototype.merge = function (other) { };
  4345. NoOpSchemaCollector.prototype.include = function (node) { return true; };
  4346. NoOpSchemaCollector.prototype.newSub = function () { return this; };
  4347. NoOpSchemaCollector.instance = new NoOpSchemaCollector();
  4348. return NoOpSchemaCollector;
  4349. }());
  4350. var ValidationResult = /** @class */ (function () {
  4351. function ValidationResult() {
  4352. this.problems = [];
  4353. this.propertiesMatches = 0;
  4354. this.propertiesValueMatches = 0;
  4355. this.primaryValueMatches = 0;
  4356. this.enumValueMatch = false;
  4357. this.enumValues = undefined;
  4358. }
  4359. ValidationResult.prototype.hasProblems = function () {
  4360. return !!this.problems.length;
  4361. };
  4362. ValidationResult.prototype.mergeAll = function (validationResults) {
  4363. for (var _i = 0, validationResults_1 = validationResults; _i < validationResults_1.length; _i++) {
  4364. var validationResult = validationResults_1[_i];
  4365. this.merge(validationResult);
  4366. }
  4367. };
  4368. ValidationResult.prototype.merge = function (validationResult) {
  4369. this.problems = this.problems.concat(validationResult.problems);
  4370. };
  4371. ValidationResult.prototype.mergeEnumValues = function (validationResult) {
  4372. if (!this.enumValueMatch && !validationResult.enumValueMatch && this.enumValues && validationResult.enumValues) {
  4373. this.enumValues = this.enumValues.concat(validationResult.enumValues);
  4374. for (var _i = 0, _a = this.problems; _i < _a.length; _i++) {
  4375. var error = _a[_i];
  4376. if (error.code === jsonLanguageTypes_1.ErrorCode.EnumValueMismatch) {
  4377. error.message = localize('enumWarning', 'Value is not accepted. Valid values: {0}.', this.enumValues.map(function (v) { return JSON.stringify(v); }).join(', '));
  4378. }
  4379. }
  4380. }
  4381. };
  4382. ValidationResult.prototype.mergePropertyMatch = function (propertyValidationResult) {
  4383. this.merge(propertyValidationResult);
  4384. this.propertiesMatches++;
  4385. if (propertyValidationResult.enumValueMatch || !propertyValidationResult.hasProblems() && propertyValidationResult.propertiesMatches) {
  4386. this.propertiesValueMatches++;
  4387. }
  4388. if (propertyValidationResult.enumValueMatch && propertyValidationResult.enumValues && propertyValidationResult.enumValues.length === 1) {
  4389. this.primaryValueMatches++;
  4390. }
  4391. };
  4392. ValidationResult.prototype.compare = function (other) {
  4393. var hasProblems = this.hasProblems();
  4394. if (hasProblems !== other.hasProblems()) {
  4395. return hasProblems ? -1 : 1;
  4396. }
  4397. if (this.enumValueMatch !== other.enumValueMatch) {
  4398. return other.enumValueMatch ? -1 : 1;
  4399. }
  4400. if (this.primaryValueMatches !== other.primaryValueMatches) {
  4401. return this.primaryValueMatches - other.primaryValueMatches;
  4402. }
  4403. if (this.propertiesValueMatches !== other.propertiesValueMatches) {
  4404. return this.propertiesValueMatches - other.propertiesValueMatches;
  4405. }
  4406. return this.propertiesMatches - other.propertiesMatches;
  4407. };
  4408. return ValidationResult;
  4409. }());
  4410. exports.ValidationResult = ValidationResult;
  4411. function newJSONDocument(root, diagnostics) {
  4412. if (diagnostics === void 0) { diagnostics = []; }
  4413. return new JSONDocument(root, diagnostics, []);
  4414. }
  4415. exports.newJSONDocument = newJSONDocument;
  4416. function getNodeValue(node) {
  4417. return Json.getNodeValue(node);
  4418. }
  4419. exports.getNodeValue = getNodeValue;
  4420. function getNodePath(node) {
  4421. return Json.getNodePath(node);
  4422. }
  4423. exports.getNodePath = getNodePath;
  4424. function contains(node, offset, includeRightBound) {
  4425. if (includeRightBound === void 0) { includeRightBound = false; }
  4426. return offset >= node.offset && offset < (node.offset + node.length) || includeRightBound && offset === (node.offset + node.length);
  4427. }
  4428. exports.contains = contains;
  4429. var JSONDocument = /** @class */ (function () {
  4430. function JSONDocument(root, syntaxErrors, comments) {
  4431. if (syntaxErrors === void 0) { syntaxErrors = []; }
  4432. if (comments === void 0) { comments = []; }
  4433. this.root = root;
  4434. this.syntaxErrors = syntaxErrors;
  4435. this.comments = comments;
  4436. }
  4437. JSONDocument.prototype.getNodeFromOffset = function (offset, includeRightBound) {
  4438. if (includeRightBound === void 0) { includeRightBound = false; }
  4439. if (this.root) {
  4440. return Json.findNodeAtOffset(this.root, offset, includeRightBound);
  4441. }
  4442. return undefined;
  4443. };
  4444. JSONDocument.prototype.visit = function (visitor) {
  4445. if (this.root) {
  4446. var doVisit_1 = function (node) {
  4447. var ctn = visitor(node);
  4448. var children = node.children;
  4449. if (Array.isArray(children)) {
  4450. for (var i = 0; i < children.length && ctn; i++) {
  4451. ctn = doVisit_1(children[i]);
  4452. }
  4453. }
  4454. return ctn;
  4455. };
  4456. doVisit_1(this.root);
  4457. }
  4458. };
  4459. JSONDocument.prototype.validate = function (textDocument, schema, severity) {
  4460. if (severity === void 0) { severity = jsonLanguageTypes_1.DiagnosticSeverity.Warning; }
  4461. if (this.root && schema) {
  4462. var validationResult = new ValidationResult();
  4463. validate(this.root, schema, validationResult, NoOpSchemaCollector.instance);
  4464. return validationResult.problems.map(function (p) {
  4465. var _a;
  4466. var range = jsonLanguageTypes_1.Range.create(textDocument.positionAt(p.location.offset), textDocument.positionAt(p.location.offset + p.location.length));
  4467. return jsonLanguageTypes_1.Diagnostic.create(range, p.message, (_a = p.severity) !== null && _a !== void 0 ? _a : severity, p.code);
  4468. });
  4469. }
  4470. return undefined;
  4471. };
  4472. JSONDocument.prototype.getMatchingSchemas = function (schema, focusOffset, exclude) {
  4473. if (focusOffset === void 0) { focusOffset = -1; }
  4474. var matchingSchemas = new SchemaCollector(focusOffset, exclude);
  4475. if (this.root && schema) {
  4476. validate(this.root, schema, new ValidationResult(), matchingSchemas);
  4477. }
  4478. return matchingSchemas.schemas;
  4479. };
  4480. return JSONDocument;
  4481. }());
  4482. exports.JSONDocument = JSONDocument;
  4483. function validate(n, schema, validationResult, matchingSchemas) {
  4484. if (!n || !matchingSchemas.include(n)) {
  4485. return;
  4486. }
  4487. var node = n;
  4488. switch (node.type) {
  4489. case 'object':
  4490. _validateObjectNode(node, schema, validationResult, matchingSchemas);
  4491. break;
  4492. case 'array':
  4493. _validateArrayNode(node, schema, validationResult, matchingSchemas);
  4494. break;
  4495. case 'string':
  4496. _validateStringNode(node, schema, validationResult, matchingSchemas);
  4497. break;
  4498. case 'number':
  4499. _validateNumberNode(node, schema, validationResult, matchingSchemas);
  4500. break;
  4501. case 'property':
  4502. return validate(node.valueNode, schema, validationResult, matchingSchemas);
  4503. }
  4504. _validateNode();
  4505. matchingSchemas.add({ node: node, schema: schema });
  4506. function _validateNode() {
  4507. function matchesType(type) {
  4508. return node.type === type || (type === 'integer' && node.type === 'number' && node.isInteger);
  4509. }
  4510. if (Array.isArray(schema.type)) {
  4511. if (!schema.type.some(matchesType)) {
  4512. validationResult.problems.push({
  4513. location: { offset: node.offset, length: node.length },
  4514. message: schema.errorMessage || localize('typeArrayMismatchWarning', 'Incorrect type. Expected one of {0}.', schema.type.join(', '))
  4515. });
  4516. }
  4517. }
  4518. else if (schema.type) {
  4519. if (!matchesType(schema.type)) {
  4520. validationResult.problems.push({
  4521. location: { offset: node.offset, length: node.length },
  4522. message: schema.errorMessage || localize('typeMismatchWarning', 'Incorrect type. Expected "{0}".', schema.type)
  4523. });
  4524. }
  4525. }
  4526. if (Array.isArray(schema.allOf)) {
  4527. for (var _i = 0, _a = schema.allOf; _i < _a.length; _i++) {
  4528. var subSchemaRef = _a[_i];
  4529. validate(node, asSchema(subSchemaRef), validationResult, matchingSchemas);
  4530. }
  4531. }
  4532. var notSchema = asSchema(schema.not);
  4533. if (notSchema) {
  4534. var subValidationResult = new ValidationResult();
  4535. var subMatchingSchemas = matchingSchemas.newSub();
  4536. validate(node, notSchema, subValidationResult, subMatchingSchemas);
  4537. if (!subValidationResult.hasProblems()) {
  4538. validationResult.problems.push({
  4539. location: { offset: node.offset, length: node.length },
  4540. message: localize('notSchemaWarning', "Matches a schema that is not allowed.")
  4541. });
  4542. }
  4543. for (var _b = 0, _c = subMatchingSchemas.schemas; _b < _c.length; _b++) {
  4544. var ms = _c[_b];
  4545. ms.inverted = !ms.inverted;
  4546. matchingSchemas.add(ms);
  4547. }
  4548. }
  4549. var testAlternatives = function (alternatives, maxOneMatch) {
  4550. var matches = [];
  4551. // remember the best match that is used for error messages
  4552. var bestMatch = undefined;
  4553. for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) {
  4554. var subSchemaRef = alternatives_1[_i];
  4555. var subSchema = asSchema(subSchemaRef);
  4556. var subValidationResult = new ValidationResult();
  4557. var subMatchingSchemas = matchingSchemas.newSub();
  4558. validate(node, subSchema, subValidationResult, subMatchingSchemas);
  4559. if (!subValidationResult.hasProblems()) {
  4560. matches.push(subSchema);
  4561. }
  4562. if (!bestMatch) {
  4563. bestMatch = { schema: subSchema, validationResult: subValidationResult, matchingSchemas: subMatchingSchemas };
  4564. }
  4565. else {
  4566. if (!maxOneMatch && !subValidationResult.hasProblems() && !bestMatch.validationResult.hasProblems()) {
  4567. // no errors, both are equally good matches
  4568. bestMatch.matchingSchemas.merge(subMatchingSchemas);
  4569. bestMatch.validationResult.propertiesMatches += subValidationResult.propertiesMatches;
  4570. bestMatch.validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches;
  4571. }
  4572. else {
  4573. var compareResult = subValidationResult.compare(bestMatch.validationResult);
  4574. if (compareResult > 0) {
  4575. // our node is the best matching so far
  4576. bestMatch = { schema: subSchema, validationResult: subValidationResult, matchingSchemas: subMatchingSchemas };
  4577. }
  4578. else if (compareResult === 0) {
  4579. // there's already a best matching but we are as good
  4580. bestMatch.matchingSchemas.merge(subMatchingSchemas);
  4581. bestMatch.validationResult.mergeEnumValues(subValidationResult);
  4582. }
  4583. }
  4584. }
  4585. }
  4586. if (matches.length > 1 && maxOneMatch) {
  4587. validationResult.problems.push({
  4588. location: { offset: node.offset, length: 1 },
  4589. message: localize('oneOfWarning', "Matches multiple schemas when only one must validate.")
  4590. });
  4591. }
  4592. if (bestMatch) {
  4593. validationResult.merge(bestMatch.validationResult);
  4594. validationResult.propertiesMatches += bestMatch.validationResult.propertiesMatches;
  4595. validationResult.propertiesValueMatches += bestMatch.validationResult.propertiesValueMatches;
  4596. matchingSchemas.merge(bestMatch.matchingSchemas);
  4597. }
  4598. return matches.length;
  4599. };
  4600. if (Array.isArray(schema.anyOf)) {
  4601. testAlternatives(schema.anyOf, false);
  4602. }
  4603. if (Array.isArray(schema.oneOf)) {
  4604. testAlternatives(schema.oneOf, true);
  4605. }
  4606. var testBranch = function (schema) {
  4607. var subValidationResult = new ValidationResult();
  4608. var subMatchingSchemas = matchingSchemas.newSub();
  4609. validate(node, asSchema(schema), subValidationResult, subMatchingSchemas);
  4610. validationResult.merge(subValidationResult);
  4611. validationResult.propertiesMatches += subValidationResult.propertiesMatches;
  4612. validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches;
  4613. matchingSchemas.merge(subMatchingSchemas);
  4614. };
  4615. var testCondition = function (ifSchema, thenSchema, elseSchema) {
  4616. var subSchema = asSchema(ifSchema);
  4617. var subValidationResult = new ValidationResult();
  4618. var subMatchingSchemas = matchingSchemas.newSub();
  4619. validate(node, subSchema, subValidationResult, subMatchingSchemas);
  4620. matchingSchemas.merge(subMatchingSchemas);
  4621. if (!subValidationResult.hasProblems()) {
  4622. if (thenSchema) {
  4623. testBranch(thenSchema);
  4624. }
  4625. }
  4626. else if (elseSchema) {
  4627. testBranch(elseSchema);
  4628. }
  4629. };
  4630. var ifSchema = asSchema(schema.if);
  4631. if (ifSchema) {
  4632. testCondition(ifSchema, asSchema(schema.then), asSchema(schema.else));
  4633. }
  4634. if (Array.isArray(schema.enum)) {
  4635. var val = getNodeValue(node);
  4636. var enumValueMatch = false;
  4637. for (var _d = 0, _e = schema.enum; _d < _e.length; _d++) {
  4638. var e = _e[_d];
  4639. if (objects_1.equals(val, e)) {
  4640. enumValueMatch = true;
  4641. break;
  4642. }
  4643. }
  4644. validationResult.enumValues = schema.enum;
  4645. validationResult.enumValueMatch = enumValueMatch;
  4646. if (!enumValueMatch) {
  4647. validationResult.problems.push({
  4648. location: { offset: node.offset, length: node.length },
  4649. code: jsonLanguageTypes_1.ErrorCode.EnumValueMismatch,
  4650. message: schema.errorMessage || localize('enumWarning', 'Value is not accepted. Valid values: {0}.', schema.enum.map(function (v) { return JSON.stringify(v); }).join(', '))
  4651. });
  4652. }
  4653. }
  4654. if (objects_1.isDefined(schema.const)) {
  4655. var val = getNodeValue(node);
  4656. if (!objects_1.equals(val, schema.const)) {
  4657. validationResult.problems.push({
  4658. location: { offset: node.offset, length: node.length },
  4659. code: jsonLanguageTypes_1.ErrorCode.EnumValueMismatch,
  4660. message: schema.errorMessage || localize('constWarning', 'Value must be {0}.', JSON.stringify(schema.const))
  4661. });
  4662. validationResult.enumValueMatch = false;
  4663. }
  4664. else {
  4665. validationResult.enumValueMatch = true;
  4666. }
  4667. validationResult.enumValues = [schema.const];
  4668. }
  4669. if (schema.deprecationMessage && node.parent) {
  4670. validationResult.problems.push({
  4671. location: { offset: node.parent.offset, length: node.parent.length },
  4672. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4673. message: schema.deprecationMessage,
  4674. code: jsonLanguageTypes_1.ErrorCode.Deprecated
  4675. });
  4676. }
  4677. }
  4678. function _validateNumberNode(node, schema, validationResult, matchingSchemas) {
  4679. var val = node.value;
  4680. function normalizeFloats(float) {
  4681. var _a;
  4682. var parts = /^(-?\d+)(?:\.(\d+))?(?:e([-+]\d+))?$/.exec(float.toString());
  4683. return parts && {
  4684. value: Number(parts[1] + (parts[2] || '')),
  4685. multiplier: (((_a = parts[2]) === null || _a === void 0 ? void 0 : _a.length) || 0) - (parseInt(parts[3]) || 0)
  4686. };
  4687. }
  4688. ;
  4689. if (objects_1.isNumber(schema.multipleOf)) {
  4690. var remainder = -1;
  4691. if (Number.isInteger(schema.multipleOf)) {
  4692. remainder = val % schema.multipleOf;
  4693. }
  4694. else {
  4695. var normMultipleOf = normalizeFloats(schema.multipleOf);
  4696. var normValue = normalizeFloats(val);
  4697. if (normMultipleOf && normValue) {
  4698. var multiplier = Math.pow(10, Math.abs(normValue.multiplier - normMultipleOf.multiplier));
  4699. if (normValue.multiplier < normMultipleOf.multiplier) {
  4700. normValue.value *= multiplier;
  4701. }
  4702. else {
  4703. normMultipleOf.value *= multiplier;
  4704. }
  4705. remainder = normValue.value % normMultipleOf.value;
  4706. }
  4707. }
  4708. if (remainder !== 0) {
  4709. validationResult.problems.push({
  4710. location: { offset: node.offset, length: node.length },
  4711. message: localize('multipleOfWarning', 'Value is not divisible by {0}.', schema.multipleOf)
  4712. });
  4713. }
  4714. }
  4715. function getExclusiveLimit(limit, exclusive) {
  4716. if (objects_1.isNumber(exclusive)) {
  4717. return exclusive;
  4718. }
  4719. if (objects_1.isBoolean(exclusive) && exclusive) {
  4720. return limit;
  4721. }
  4722. return undefined;
  4723. }
  4724. function getLimit(limit, exclusive) {
  4725. if (!objects_1.isBoolean(exclusive) || !exclusive) {
  4726. return limit;
  4727. }
  4728. return undefined;
  4729. }
  4730. var exclusiveMinimum = getExclusiveLimit(schema.minimum, schema.exclusiveMinimum);
  4731. if (objects_1.isNumber(exclusiveMinimum) && val <= exclusiveMinimum) {
  4732. validationResult.problems.push({
  4733. location: { offset: node.offset, length: node.length },
  4734. message: localize('exclusiveMinimumWarning', 'Value is below the exclusive minimum of {0}.', exclusiveMinimum)
  4735. });
  4736. }
  4737. var exclusiveMaximum = getExclusiveLimit(schema.maximum, schema.exclusiveMaximum);
  4738. if (objects_1.isNumber(exclusiveMaximum) && val >= exclusiveMaximum) {
  4739. validationResult.problems.push({
  4740. location: { offset: node.offset, length: node.length },
  4741. message: localize('exclusiveMaximumWarning', 'Value is above the exclusive maximum of {0}.', exclusiveMaximum)
  4742. });
  4743. }
  4744. var minimum = getLimit(schema.minimum, schema.exclusiveMinimum);
  4745. if (objects_1.isNumber(minimum) && val < minimum) {
  4746. validationResult.problems.push({
  4747. location: { offset: node.offset, length: node.length },
  4748. message: localize('minimumWarning', 'Value is below the minimum of {0}.', minimum)
  4749. });
  4750. }
  4751. var maximum = getLimit(schema.maximum, schema.exclusiveMaximum);
  4752. if (objects_1.isNumber(maximum) && val > maximum) {
  4753. validationResult.problems.push({
  4754. location: { offset: node.offset, length: node.length },
  4755. message: localize('maximumWarning', 'Value is above the maximum of {0}.', maximum)
  4756. });
  4757. }
  4758. }
  4759. function _validateStringNode(node, schema, validationResult, matchingSchemas) {
  4760. if (objects_1.isNumber(schema.minLength) && node.value.length < schema.minLength) {
  4761. validationResult.problems.push({
  4762. location: { offset: node.offset, length: node.length },
  4763. message: localize('minLengthWarning', 'String is shorter than the minimum length of {0}.', schema.minLength)
  4764. });
  4765. }
  4766. if (objects_1.isNumber(schema.maxLength) && node.value.length > schema.maxLength) {
  4767. validationResult.problems.push({
  4768. location: { offset: node.offset, length: node.length },
  4769. message: localize('maxLengthWarning', 'String is longer than the maximum length of {0}.', schema.maxLength)
  4770. });
  4771. }
  4772. if (objects_1.isString(schema.pattern)) {
  4773. var regex = strings_1.extendedRegExp(schema.pattern);
  4774. if (!regex.test(node.value)) {
  4775. validationResult.problems.push({
  4776. location: { offset: node.offset, length: node.length },
  4777. message: schema.patternErrorMessage || schema.errorMessage || localize('patternWarning', 'String does not match the pattern of "{0}".', schema.pattern)
  4778. });
  4779. }
  4780. }
  4781. if (schema.format) {
  4782. switch (schema.format) {
  4783. case 'uri':
  4784. case 'uri-reference':
  4785. {
  4786. var errorMessage = void 0;
  4787. if (!node.value) {
  4788. errorMessage = localize('uriEmpty', 'URI expected.');
  4789. }
  4790. else {
  4791. var match = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/.exec(node.value);
  4792. if (!match) {
  4793. errorMessage = localize('uriMissing', 'URI is expected.');
  4794. }
  4795. else if (!match[2] && schema.format === 'uri') {
  4796. errorMessage = localize('uriSchemeMissing', 'URI with a scheme is expected.');
  4797. }
  4798. }
  4799. if (errorMessage) {
  4800. validationResult.problems.push({
  4801. location: { offset: node.offset, length: node.length },
  4802. message: schema.patternErrorMessage || schema.errorMessage || localize('uriFormatWarning', 'String is not a URI: {0}', errorMessage)
  4803. });
  4804. }
  4805. }
  4806. break;
  4807. case 'color-hex':
  4808. case 'date-time':
  4809. case 'date':
  4810. case 'time':
  4811. case 'email':
  4812. var format = formats[schema.format];
  4813. if (!node.value || !format.pattern.exec(node.value)) {
  4814. validationResult.problems.push({
  4815. location: { offset: node.offset, length: node.length },
  4816. message: schema.patternErrorMessage || schema.errorMessage || format.errorMessage
  4817. });
  4818. }
  4819. default:
  4820. }
  4821. }
  4822. }
  4823. function _validateArrayNode(node, schema, validationResult, matchingSchemas) {
  4824. if (Array.isArray(schema.items)) {
  4825. var subSchemas = schema.items;
  4826. for (var index = 0; index < subSchemas.length; index++) {
  4827. var subSchemaRef = subSchemas[index];
  4828. var subSchema = asSchema(subSchemaRef);
  4829. var itemValidationResult = new ValidationResult();
  4830. var item = node.items[index];
  4831. if (item) {
  4832. validate(item, subSchema, itemValidationResult, matchingSchemas);
  4833. validationResult.mergePropertyMatch(itemValidationResult);
  4834. }
  4835. else if (node.items.length >= subSchemas.length) {
  4836. validationResult.propertiesValueMatches++;
  4837. }
  4838. }
  4839. if (node.items.length > subSchemas.length) {
  4840. if (typeof schema.additionalItems === 'object') {
  4841. for (var i = subSchemas.length; i < node.items.length; i++) {
  4842. var itemValidationResult = new ValidationResult();
  4843. validate(node.items[i], schema.additionalItems, itemValidationResult, matchingSchemas);
  4844. validationResult.mergePropertyMatch(itemValidationResult);
  4845. }
  4846. }
  4847. else if (schema.additionalItems === false) {
  4848. validationResult.problems.push({
  4849. location: { offset: node.offset, length: node.length },
  4850. message: localize('additionalItemsWarning', 'Array has too many items according to schema. Expected {0} or fewer.', subSchemas.length)
  4851. });
  4852. }
  4853. }
  4854. }
  4855. else {
  4856. var itemSchema = asSchema(schema.items);
  4857. if (itemSchema) {
  4858. for (var _i = 0, _a = node.items; _i < _a.length; _i++) {
  4859. var item = _a[_i];
  4860. var itemValidationResult = new ValidationResult();
  4861. validate(item, itemSchema, itemValidationResult, matchingSchemas);
  4862. validationResult.mergePropertyMatch(itemValidationResult);
  4863. }
  4864. }
  4865. }
  4866. var containsSchema = asSchema(schema.contains);
  4867. if (containsSchema) {
  4868. var doesContain = node.items.some(function (item) {
  4869. var itemValidationResult = new ValidationResult();
  4870. validate(item, containsSchema, itemValidationResult, NoOpSchemaCollector.instance);
  4871. return !itemValidationResult.hasProblems();
  4872. });
  4873. if (!doesContain) {
  4874. validationResult.problems.push({
  4875. location: { offset: node.offset, length: node.length },
  4876. message: schema.errorMessage || localize('requiredItemMissingWarning', 'Array does not contain required item.')
  4877. });
  4878. }
  4879. }
  4880. if (objects_1.isNumber(schema.minItems) && node.items.length < schema.minItems) {
  4881. validationResult.problems.push({
  4882. location: { offset: node.offset, length: node.length },
  4883. message: localize('minItemsWarning', 'Array has too few items. Expected {0} or more.', schema.minItems)
  4884. });
  4885. }
  4886. if (objects_1.isNumber(schema.maxItems) && node.items.length > schema.maxItems) {
  4887. validationResult.problems.push({
  4888. location: { offset: node.offset, length: node.length },
  4889. message: localize('maxItemsWarning', 'Array has too many items. Expected {0} or fewer.', schema.maxItems)
  4890. });
  4891. }
  4892. if (schema.uniqueItems === true) {
  4893. var values_1 = getNodeValue(node);
  4894. var duplicates = values_1.some(function (value, index) {
  4895. return index !== values_1.lastIndexOf(value);
  4896. });
  4897. if (duplicates) {
  4898. validationResult.problems.push({
  4899. location: { offset: node.offset, length: node.length },
  4900. message: localize('uniqueItemsWarning', 'Array has duplicate items.')
  4901. });
  4902. }
  4903. }
  4904. }
  4905. function _validateObjectNode(node, schema, validationResult, matchingSchemas) {
  4906. var seenKeys = Object.create(null);
  4907. var unprocessedProperties = [];
  4908. for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
  4909. var propertyNode = _a[_i];
  4910. var key = propertyNode.keyNode.value;
  4911. seenKeys[key] = propertyNode.valueNode;
  4912. unprocessedProperties.push(key);
  4913. }
  4914. if (Array.isArray(schema.required)) {
  4915. for (var _b = 0, _c = schema.required; _b < _c.length; _b++) {
  4916. var propertyName = _c[_b];
  4917. if (!seenKeys[propertyName]) {
  4918. var keyNode = node.parent && node.parent.type === 'property' && node.parent.keyNode;
  4919. var location = keyNode ? { offset: keyNode.offset, length: keyNode.length } : { offset: node.offset, length: 1 };
  4920. validationResult.problems.push({
  4921. location: location,
  4922. message: localize('MissingRequiredPropWarning', 'Missing property "{0}".', propertyName)
  4923. });
  4924. }
  4925. }
  4926. }
  4927. var propertyProcessed = function (prop) {
  4928. var index = unprocessedProperties.indexOf(prop);
  4929. while (index >= 0) {
  4930. unprocessedProperties.splice(index, 1);
  4931. index = unprocessedProperties.indexOf(prop);
  4932. }
  4933. };
  4934. if (schema.properties) {
  4935. for (var _d = 0, _e = Object.keys(schema.properties); _d < _e.length; _d++) {
  4936. var propertyName = _e[_d];
  4937. propertyProcessed(propertyName);
  4938. var propertySchema = schema.properties[propertyName];
  4939. var child = seenKeys[propertyName];
  4940. if (child) {
  4941. if (objects_1.isBoolean(propertySchema)) {
  4942. if (!propertySchema) {
  4943. var propertyNode = child.parent;
  4944. validationResult.problems.push({
  4945. location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
  4946. message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
  4947. });
  4948. }
  4949. else {
  4950. validationResult.propertiesMatches++;
  4951. validationResult.propertiesValueMatches++;
  4952. }
  4953. }
  4954. else {
  4955. var propertyValidationResult = new ValidationResult();
  4956. validate(child, propertySchema, propertyValidationResult, matchingSchemas);
  4957. validationResult.mergePropertyMatch(propertyValidationResult);
  4958. }
  4959. }
  4960. }
  4961. }
  4962. if (schema.patternProperties) {
  4963. for (var _f = 0, _g = Object.keys(schema.patternProperties); _f < _g.length; _f++) {
  4964. var propertyPattern = _g[_f];
  4965. var regex = strings_1.extendedRegExp(propertyPattern);
  4966. for (var _h = 0, _j = unprocessedProperties.slice(0); _h < _j.length; _h++) {
  4967. var propertyName = _j[_h];
  4968. if (regex.test(propertyName)) {
  4969. propertyProcessed(propertyName);
  4970. var child = seenKeys[propertyName];
  4971. if (child) {
  4972. var propertySchema = schema.patternProperties[propertyPattern];
  4973. if (objects_1.isBoolean(propertySchema)) {
  4974. if (!propertySchema) {
  4975. var propertyNode = child.parent;
  4976. validationResult.problems.push({
  4977. location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
  4978. message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
  4979. });
  4980. }
  4981. else {
  4982. validationResult.propertiesMatches++;
  4983. validationResult.propertiesValueMatches++;
  4984. }
  4985. }
  4986. else {
  4987. var propertyValidationResult = new ValidationResult();
  4988. validate(child, propertySchema, propertyValidationResult, matchingSchemas);
  4989. validationResult.mergePropertyMatch(propertyValidationResult);
  4990. }
  4991. }
  4992. }
  4993. }
  4994. }
  4995. }
  4996. if (typeof schema.additionalProperties === 'object') {
  4997. for (var _k = 0, unprocessedProperties_1 = unprocessedProperties; _k < unprocessedProperties_1.length; _k++) {
  4998. var propertyName = unprocessedProperties_1[_k];
  4999. var child = seenKeys[propertyName];
  5000. if (child) {
  5001. var propertyValidationResult = new ValidationResult();
  5002. validate(child, schema.additionalProperties, propertyValidationResult, matchingSchemas);
  5003. validationResult.mergePropertyMatch(propertyValidationResult);
  5004. }
  5005. }
  5006. }
  5007. else if (schema.additionalProperties === false) {
  5008. if (unprocessedProperties.length > 0) {
  5009. for (var _l = 0, unprocessedProperties_2 = unprocessedProperties; _l < unprocessedProperties_2.length; _l++) {
  5010. var propertyName = unprocessedProperties_2[_l];
  5011. var child = seenKeys[propertyName];
  5012. if (child) {
  5013. var propertyNode = child.parent;
  5014. validationResult.problems.push({
  5015. location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
  5016. message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
  5017. });
  5018. }
  5019. }
  5020. }
  5021. }
  5022. if (objects_1.isNumber(schema.maxProperties)) {
  5023. if (node.properties.length > schema.maxProperties) {
  5024. validationResult.problems.push({
  5025. location: { offset: node.offset, length: node.length },
  5026. message: localize('MaxPropWarning', 'Object has more properties than limit of {0}.', schema.maxProperties)
  5027. });
  5028. }
  5029. }
  5030. if (objects_1.isNumber(schema.minProperties)) {
  5031. if (node.properties.length < schema.minProperties) {
  5032. validationResult.problems.push({
  5033. location: { offset: node.offset, length: node.length },
  5034. message: localize('MinPropWarning', 'Object has fewer properties than the required number of {0}', schema.minProperties)
  5035. });
  5036. }
  5037. }
  5038. if (schema.dependencies) {
  5039. for (var _m = 0, _o = Object.keys(schema.dependencies); _m < _o.length; _m++) {
  5040. var key = _o[_m];
  5041. var prop = seenKeys[key];
  5042. if (prop) {
  5043. var propertyDep = schema.dependencies[key];
  5044. if (Array.isArray(propertyDep)) {
  5045. for (var _p = 0, propertyDep_1 = propertyDep; _p < propertyDep_1.length; _p++) {
  5046. var requiredProp = propertyDep_1[_p];
  5047. if (!seenKeys[requiredProp]) {
  5048. validationResult.problems.push({
  5049. location: { offset: node.offset, length: node.length },
  5050. message: localize('RequiredDependentPropWarning', 'Object is missing property {0} required by property {1}.', requiredProp, key)
  5051. });
  5052. }
  5053. else {
  5054. validationResult.propertiesValueMatches++;
  5055. }
  5056. }
  5057. }
  5058. else {
  5059. var propertySchema = asSchema(propertyDep);
  5060. if (propertySchema) {
  5061. var propertyValidationResult = new ValidationResult();
  5062. validate(node, propertySchema, propertyValidationResult, matchingSchemas);
  5063. validationResult.mergePropertyMatch(propertyValidationResult);
  5064. }
  5065. }
  5066. }
  5067. }
  5068. }
  5069. var propertyNames = asSchema(schema.propertyNames);
  5070. if (propertyNames) {
  5071. for (var _q = 0, _r = node.properties; _q < _r.length; _q++) {
  5072. var f = _r[_q];
  5073. var key = f.keyNode;
  5074. if (key) {
  5075. validate(key, propertyNames, validationResult, NoOpSchemaCollector.instance);
  5076. }
  5077. }
  5078. }
  5079. }
  5080. }
  5081. function parse(textDocument, config) {
  5082. var problems = [];
  5083. var lastProblemOffset = -1;
  5084. var text = textDocument.getText();
  5085. var scanner = Json.createScanner(text, false);
  5086. var commentRanges = config && config.collectComments ? [] : undefined;
  5087. function _scanNext() {
  5088. while (true) {
  5089. var token_1 = scanner.scan();
  5090. _checkScanError();
  5091. switch (token_1) {
  5092. case 12 /* LineCommentTrivia */:
  5093. case 13 /* BlockCommentTrivia */:
  5094. if (Array.isArray(commentRanges)) {
  5095. commentRanges.push(jsonLanguageTypes_1.Range.create(textDocument.positionAt(scanner.getTokenOffset()), textDocument.positionAt(scanner.getTokenOffset() + scanner.getTokenLength())));
  5096. }
  5097. break;
  5098. case 15 /* Trivia */:
  5099. case 14 /* LineBreakTrivia */:
  5100. break;
  5101. default:
  5102. return token_1;
  5103. }
  5104. }
  5105. }
  5106. function _accept(token) {
  5107. if (scanner.getToken() === token) {
  5108. _scanNext();
  5109. return true;
  5110. }
  5111. return false;
  5112. }
  5113. function _errorAtRange(message, code, startOffset, endOffset, severity) {
  5114. if (severity === void 0) { severity = jsonLanguageTypes_1.DiagnosticSeverity.Error; }
  5115. if (problems.length === 0 || startOffset !== lastProblemOffset) {
  5116. var range = jsonLanguageTypes_1.Range.create(textDocument.positionAt(startOffset), textDocument.positionAt(endOffset));
  5117. problems.push(jsonLanguageTypes_1.Diagnostic.create(range, message, severity, code, textDocument.languageId));
  5118. lastProblemOffset = startOffset;
  5119. }
  5120. }
  5121. function _error(message, code, node, skipUntilAfter, skipUntil) {
  5122. if (node === void 0) { node = undefined; }
  5123. if (skipUntilAfter === void 0) { skipUntilAfter = []; }
  5124. if (skipUntil === void 0) { skipUntil = []; }
  5125. var start = scanner.getTokenOffset();
  5126. var end = scanner.getTokenOffset() + scanner.getTokenLength();
  5127. if (start === end && start > 0) {
  5128. start--;
  5129. while (start > 0 && /\s/.test(text.charAt(start))) {
  5130. start--;
  5131. }
  5132. end = start + 1;
  5133. }
  5134. _errorAtRange(message, code, start, end);
  5135. if (node) {
  5136. _finalize(node, false);
  5137. }
  5138. if (skipUntilAfter.length + skipUntil.length > 0) {
  5139. var token_2 = scanner.getToken();
  5140. while (token_2 !== 17 /* EOF */) {
  5141. if (skipUntilAfter.indexOf(token_2) !== -1) {
  5142. _scanNext();
  5143. break;
  5144. }
  5145. else if (skipUntil.indexOf(token_2) !== -1) {
  5146. break;
  5147. }
  5148. token_2 = _scanNext();
  5149. }
  5150. }
  5151. return node;
  5152. }
  5153. function _checkScanError() {
  5154. switch (scanner.getTokenError()) {
  5155. case 4 /* InvalidUnicode */:
  5156. _error(localize('InvalidUnicode', 'Invalid unicode sequence in string.'), jsonLanguageTypes_1.ErrorCode.InvalidUnicode);
  5157. return true;
  5158. case 5 /* InvalidEscapeCharacter */:
  5159. _error(localize('InvalidEscapeCharacter', 'Invalid escape character in string.'), jsonLanguageTypes_1.ErrorCode.InvalidEscapeCharacter);
  5160. return true;
  5161. case 3 /* UnexpectedEndOfNumber */:
  5162. _error(localize('UnexpectedEndOfNumber', 'Unexpected end of number.'), jsonLanguageTypes_1.ErrorCode.UnexpectedEndOfNumber);
  5163. return true;
  5164. case 1 /* UnexpectedEndOfComment */:
  5165. _error(localize('UnexpectedEndOfComment', 'Unexpected end of comment.'), jsonLanguageTypes_1.ErrorCode.UnexpectedEndOfComment);
  5166. return true;
  5167. case 2 /* UnexpectedEndOfString */:
  5168. _error(localize('UnexpectedEndOfString', 'Unexpected end of string.'), jsonLanguageTypes_1.ErrorCode.UnexpectedEndOfString);
  5169. return true;
  5170. case 6 /* InvalidCharacter */:
  5171. _error(localize('InvalidCharacter', 'Invalid characters in string. Control characters must be escaped.'), jsonLanguageTypes_1.ErrorCode.InvalidCharacter);
  5172. return true;
  5173. }
  5174. return false;
  5175. }
  5176. function _finalize(node, scanNext) {
  5177. node.length = scanner.getTokenOffset() + scanner.getTokenLength() - node.offset;
  5178. if (scanNext) {
  5179. _scanNext();
  5180. }
  5181. return node;
  5182. }
  5183. function _parseArray(parent) {
  5184. if (scanner.getToken() !== 3 /* OpenBracketToken */) {
  5185. return undefined;
  5186. }
  5187. var node = new ArrayASTNodeImpl(parent, scanner.getTokenOffset());
  5188. _scanNext(); // consume OpenBracketToken
  5189. var count = 0;
  5190. var needsComma = false;
  5191. while (scanner.getToken() !== 4 /* CloseBracketToken */ && scanner.getToken() !== 17 /* EOF */) {
  5192. if (scanner.getToken() === 5 /* CommaToken */) {
  5193. if (!needsComma) {
  5194. _error(localize('ValueExpected', 'Value expected'), jsonLanguageTypes_1.ErrorCode.ValueExpected);
  5195. }
  5196. var commaOffset = scanner.getTokenOffset();
  5197. _scanNext(); // consume comma
  5198. if (scanner.getToken() === 4 /* CloseBracketToken */) {
  5199. if (needsComma) {
  5200. _errorAtRange(localize('TrailingComma', 'Trailing comma'), jsonLanguageTypes_1.ErrorCode.TrailingComma, commaOffset, commaOffset + 1);
  5201. }
  5202. continue;
  5203. }
  5204. }
  5205. else if (needsComma) {
  5206. _error(localize('ExpectedComma', 'Expected comma'), jsonLanguageTypes_1.ErrorCode.CommaExpected);
  5207. }
  5208. var item = _parseValue(node);
  5209. if (!item) {
  5210. _error(localize('PropertyExpected', 'Value expected'), jsonLanguageTypes_1.ErrorCode.ValueExpected, undefined, [], [4 /* CloseBracketToken */, 5 /* CommaToken */]);
  5211. }
  5212. else {
  5213. node.items.push(item);
  5214. }
  5215. needsComma = true;
  5216. }
  5217. if (scanner.getToken() !== 4 /* CloseBracketToken */) {
  5218. return _error(localize('ExpectedCloseBracket', 'Expected comma or closing bracket'), jsonLanguageTypes_1.ErrorCode.CommaOrCloseBacketExpected, node);
  5219. }
  5220. return _finalize(node, true);
  5221. }
  5222. var keyPlaceholder = new StringASTNodeImpl(undefined, 0, 0);
  5223. function _parseProperty(parent, keysSeen) {
  5224. var node = new PropertyASTNodeImpl(parent, scanner.getTokenOffset(), keyPlaceholder);
  5225. var key = _parseString(node);
  5226. if (!key) {
  5227. if (scanner.getToken() === 16 /* Unknown */) {
  5228. // give a more helpful error message
  5229. _error(localize('DoubleQuotesExpected', 'Property keys must be doublequoted'), jsonLanguageTypes_1.ErrorCode.Undefined);
  5230. var keyNode = new StringASTNodeImpl(node, scanner.getTokenOffset(), scanner.getTokenLength());
  5231. keyNode.value = scanner.getTokenValue();
  5232. key = keyNode;
  5233. _scanNext(); // consume Unknown
  5234. }
  5235. else {
  5236. return undefined;
  5237. }
  5238. }
  5239. node.keyNode = key;
  5240. var seen = keysSeen[key.value];
  5241. if (seen) {
  5242. _errorAtRange(localize('DuplicateKeyWarning', "Duplicate object key"), jsonLanguageTypes_1.ErrorCode.DuplicateKey, node.keyNode.offset, node.keyNode.offset + node.keyNode.length, jsonLanguageTypes_1.DiagnosticSeverity.Warning);
  5243. if (typeof seen === 'object') {
  5244. _errorAtRange(localize('DuplicateKeyWarning', "Duplicate object key"), jsonLanguageTypes_1.ErrorCode.DuplicateKey, seen.keyNode.offset, seen.keyNode.offset + seen.keyNode.length, jsonLanguageTypes_1.DiagnosticSeverity.Warning);
  5245. }
  5246. keysSeen[key.value] = true; // if the same key is duplicate again, avoid duplicate error reporting
  5247. }
  5248. else {
  5249. keysSeen[key.value] = node;
  5250. }
  5251. if (scanner.getToken() === 6 /* ColonToken */) {
  5252. node.colonOffset = scanner.getTokenOffset();
  5253. _scanNext(); // consume ColonToken
  5254. }
  5255. else {
  5256. _error(localize('ColonExpected', 'Colon expected'), jsonLanguageTypes_1.ErrorCode.ColonExpected);
  5257. if (scanner.getToken() === 10 /* StringLiteral */ && textDocument.positionAt(key.offset + key.length).line < textDocument.positionAt(scanner.getTokenOffset()).line) {
  5258. node.length = key.length;
  5259. return node;
  5260. }
  5261. }
  5262. var value = _parseValue(node);
  5263. if (!value) {
  5264. return _error(localize('ValueExpected', 'Value expected'), jsonLanguageTypes_1.ErrorCode.ValueExpected, node, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  5265. }
  5266. node.valueNode = value;
  5267. node.length = value.offset + value.length - node.offset;
  5268. return node;
  5269. }
  5270. function _parseObject(parent) {
  5271. if (scanner.getToken() !== 1 /* OpenBraceToken */) {
  5272. return undefined;
  5273. }
  5274. var node = new ObjectASTNodeImpl(parent, scanner.getTokenOffset());
  5275. var keysSeen = Object.create(null);
  5276. _scanNext(); // consume OpenBraceToken
  5277. var needsComma = false;
  5278. while (scanner.getToken() !== 2 /* CloseBraceToken */ && scanner.getToken() !== 17 /* EOF */) {
  5279. if (scanner.getToken() === 5 /* CommaToken */) {
  5280. if (!needsComma) {
  5281. _error(localize('PropertyExpected', 'Property expected'), jsonLanguageTypes_1.ErrorCode.PropertyExpected);
  5282. }
  5283. var commaOffset = scanner.getTokenOffset();
  5284. _scanNext(); // consume comma
  5285. if (scanner.getToken() === 2 /* CloseBraceToken */) {
  5286. if (needsComma) {
  5287. _errorAtRange(localize('TrailingComma', 'Trailing comma'), jsonLanguageTypes_1.ErrorCode.TrailingComma, commaOffset, commaOffset + 1);
  5288. }
  5289. continue;
  5290. }
  5291. }
  5292. else if (needsComma) {
  5293. _error(localize('ExpectedComma', 'Expected comma'), jsonLanguageTypes_1.ErrorCode.CommaExpected);
  5294. }
  5295. var property = _parseProperty(node, keysSeen);
  5296. if (!property) {
  5297. _error(localize('PropertyExpected', 'Property expected'), jsonLanguageTypes_1.ErrorCode.PropertyExpected, undefined, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  5298. }
  5299. else {
  5300. node.properties.push(property);
  5301. }
  5302. needsComma = true;
  5303. }
  5304. if (scanner.getToken() !== 2 /* CloseBraceToken */) {
  5305. return _error(localize('ExpectedCloseBrace', 'Expected comma or closing brace'), jsonLanguageTypes_1.ErrorCode.CommaOrCloseBraceExpected, node);
  5306. }
  5307. return _finalize(node, true);
  5308. }
  5309. function _parseString(parent) {
  5310. if (scanner.getToken() !== 10 /* StringLiteral */) {
  5311. return undefined;
  5312. }
  5313. var node = new StringASTNodeImpl(parent, scanner.getTokenOffset());
  5314. node.value = scanner.getTokenValue();
  5315. return _finalize(node, true);
  5316. }
  5317. function _parseNumber(parent) {
  5318. if (scanner.getToken() !== 11 /* NumericLiteral */) {
  5319. return undefined;
  5320. }
  5321. var node = new NumberASTNodeImpl(parent, scanner.getTokenOffset());
  5322. if (scanner.getTokenError() === 0 /* None */) {
  5323. var tokenValue = scanner.getTokenValue();
  5324. try {
  5325. var numberValue = JSON.parse(tokenValue);
  5326. if (!objects_1.isNumber(numberValue)) {
  5327. return _error(localize('InvalidNumberFormat', 'Invalid number format.'), jsonLanguageTypes_1.ErrorCode.Undefined, node);
  5328. }
  5329. node.value = numberValue;
  5330. }
  5331. catch (e) {
  5332. return _error(localize('InvalidNumberFormat', 'Invalid number format.'), jsonLanguageTypes_1.ErrorCode.Undefined, node);
  5333. }
  5334. node.isInteger = tokenValue.indexOf('.') === -1;
  5335. }
  5336. return _finalize(node, true);
  5337. }
  5338. function _parseLiteral(parent) {
  5339. var node;
  5340. switch (scanner.getToken()) {
  5341. case 7 /* NullKeyword */:
  5342. return _finalize(new NullASTNodeImpl(parent, scanner.getTokenOffset()), true);
  5343. case 8 /* TrueKeyword */:
  5344. return _finalize(new BooleanASTNodeImpl(parent, true, scanner.getTokenOffset()), true);
  5345. case 9 /* FalseKeyword */:
  5346. return _finalize(new BooleanASTNodeImpl(parent, false, scanner.getTokenOffset()), true);
  5347. default:
  5348. return undefined;
  5349. }
  5350. }
  5351. function _parseValue(parent) {
  5352. return _parseArray(parent) || _parseObject(parent) || _parseString(parent) || _parseNumber(parent) || _parseLiteral(parent);
  5353. }
  5354. var _root = undefined;
  5355. var token = _scanNext();
  5356. if (token !== 17 /* EOF */) {
  5357. _root = _parseValue(_root);
  5358. if (!_root) {
  5359. _error(localize('Invalid symbol', 'Expected a JSON object, array or literal.'), jsonLanguageTypes_1.ErrorCode.Undefined);
  5360. }
  5361. else if (scanner.getToken() !== 17 /* EOF */) {
  5362. _error(localize('End of file expected', 'End of file expected.'), jsonLanguageTypes_1.ErrorCode.Undefined);
  5363. }
  5364. }
  5365. return new JSONDocument(_root, problems, commentRanges);
  5366. }
  5367. exports.parse = parse;
  5368. });
  5369. /*---------------------------------------------------------------------------------------------
  5370. * Copyright (c) Microsoft Corporation. All rights reserved.
  5371. * Licensed under the MIT License. See License.txt in the project root for license information.
  5372. *--------------------------------------------------------------------------------------------*/
  5373. (function (factory) {
  5374. if (typeof module === "object" && typeof module.exports === "object") {
  5375. var v = factory(require, exports);
  5376. if (v !== undefined) module.exports = v;
  5377. }
  5378. else if (typeof define === "function" && define.amd) {
  5379. define('vscode-json-languageservice/utils/json',["require", "exports"], factory);
  5380. }
  5381. })(function (require, exports) {
  5382. "use strict";
  5383. Object.defineProperty(exports, "__esModule", { value: true });
  5384. exports.stringifyObject = void 0;
  5385. function stringifyObject(obj, indent, stringifyLiteral) {
  5386. if (obj !== null && typeof obj === 'object') {
  5387. var newIndent = indent + '\t';
  5388. if (Array.isArray(obj)) {
  5389. if (obj.length === 0) {
  5390. return '[]';
  5391. }
  5392. var result = '[\n';
  5393. for (var i = 0; i < obj.length; i++) {
  5394. result += newIndent + stringifyObject(obj[i], newIndent, stringifyLiteral);
  5395. if (i < obj.length - 1) {
  5396. result += ',';
  5397. }
  5398. result += '\n';
  5399. }
  5400. result += indent + ']';
  5401. return result;
  5402. }
  5403. else {
  5404. var keys = Object.keys(obj);
  5405. if (keys.length === 0) {
  5406. return '{}';
  5407. }
  5408. var result = '{\n';
  5409. for (var i = 0; i < keys.length; i++) {
  5410. var key = keys[i];
  5411. result += newIndent + JSON.stringify(key) + ': ' + stringifyObject(obj[key], newIndent, stringifyLiteral);
  5412. if (i < keys.length - 1) {
  5413. result += ',';
  5414. }
  5415. result += '\n';
  5416. }
  5417. result += indent + '}';
  5418. return result;
  5419. }
  5420. }
  5421. return stringifyLiteral(obj);
  5422. }
  5423. exports.stringifyObject = stringifyObject;
  5424. });
  5425. /*---------------------------------------------------------------------------------------------
  5426. * Copyright (c) Microsoft Corporation. All rights reserved.
  5427. * Licensed under the MIT License. See License.txt in the project root for license information.
  5428. *--------------------------------------------------------------------------------------------*/
  5429. (function (factory) {
  5430. if (typeof module === "object" && typeof module.exports === "object") {
  5431. var v = factory(require, exports);
  5432. if (v !== undefined) module.exports = v;
  5433. }
  5434. else if (typeof define === "function" && define.amd) {
  5435. define('vscode-json-languageservice/services/jsonCompletion',["require", "exports", "../parser/jsonParser", "jsonc-parser", "../utils/json", "../utils/strings", "../utils/objects", "../jsonLanguageTypes", "vscode-nls"], factory);
  5436. }
  5437. })(function (require, exports) {
  5438. "use strict";
  5439. Object.defineProperty(exports, "__esModule", { value: true });
  5440. exports.JSONCompletion = void 0;
  5441. var Parser = require("../parser/jsonParser");
  5442. var Json = require("jsonc-parser");
  5443. var json_1 = require("../utils/json");
  5444. var strings_1 = require("../utils/strings");
  5445. var objects_1 = require("../utils/objects");
  5446. var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
  5447. var nls = require("vscode-nls");
  5448. var localize = nls.loadMessageBundle();
  5449. var valueCommitCharacters = [',', '}', ']'];
  5450. var propertyCommitCharacters = [':'];
  5451. var JSONCompletion = /** @class */ (function () {
  5452. function JSONCompletion(schemaService, contributions, promiseConstructor, clientCapabilities) {
  5453. if (contributions === void 0) { contributions = []; }
  5454. if (promiseConstructor === void 0) { promiseConstructor = Promise; }
  5455. if (clientCapabilities === void 0) { clientCapabilities = {}; }
  5456. this.schemaService = schemaService;
  5457. this.contributions = contributions;
  5458. this.promiseConstructor = promiseConstructor;
  5459. this.clientCapabilities = clientCapabilities;
  5460. }
  5461. JSONCompletion.prototype.doResolve = function (item) {
  5462. for (var i = this.contributions.length - 1; i >= 0; i--) {
  5463. var resolveCompletion = this.contributions[i].resolveCompletion;
  5464. if (resolveCompletion) {
  5465. var resolver = resolveCompletion(item);
  5466. if (resolver) {
  5467. return resolver;
  5468. }
  5469. }
  5470. }
  5471. return this.promiseConstructor.resolve(item);
  5472. };
  5473. JSONCompletion.prototype.doComplete = function (document, position, doc) {
  5474. var _this = this;
  5475. var result = {
  5476. items: [],
  5477. isIncomplete: false
  5478. };
  5479. var text = document.getText();
  5480. var offset = document.offsetAt(position);
  5481. var node = doc.getNodeFromOffset(offset, true);
  5482. if (this.isInComment(document, node ? node.offset : 0, offset)) {
  5483. return Promise.resolve(result);
  5484. }
  5485. if (node && (offset === node.offset + node.length) && offset > 0) {
  5486. var ch = text[offset - 1];
  5487. if (node.type === 'object' && ch === '}' || node.type === 'array' && ch === ']') {
  5488. // after ] or }
  5489. node = node.parent;
  5490. }
  5491. }
  5492. var currentWord = this.getCurrentWord(document, offset);
  5493. var overwriteRange;
  5494. if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
  5495. overwriteRange = jsonLanguageTypes_1.Range.create(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
  5496. }
  5497. else {
  5498. var overwriteStart = offset - currentWord.length;
  5499. if (overwriteStart > 0 && text[overwriteStart - 1] === '"') {
  5500. overwriteStart--;
  5501. }
  5502. overwriteRange = jsonLanguageTypes_1.Range.create(document.positionAt(overwriteStart), position);
  5503. }
  5504. var supportsCommitCharacters = false; //this.doesSupportsCommitCharacters(); disabled for now, waiting for new API: https://github.com/microsoft/vscode/issues/42544
  5505. var proposed = {};
  5506. var collector = {
  5507. add: function (suggestion) {
  5508. var label = suggestion.label;
  5509. var existing = proposed[label];
  5510. if (!existing) {
  5511. label = label.replace(/[\n]/g, '↵');
  5512. if (label.length > 60) {
  5513. var shortendedLabel = label.substr(0, 57).trim() + '...';
  5514. if (!proposed[shortendedLabel]) {
  5515. label = shortendedLabel;
  5516. }
  5517. }
  5518. if (overwriteRange && suggestion.insertText !== undefined) {
  5519. suggestion.textEdit = jsonLanguageTypes_1.TextEdit.replace(overwriteRange, suggestion.insertText);
  5520. }
  5521. if (supportsCommitCharacters) {
  5522. suggestion.commitCharacters = suggestion.kind === jsonLanguageTypes_1.CompletionItemKind.Property ? propertyCommitCharacters : valueCommitCharacters;
  5523. }
  5524. suggestion.label = label;
  5525. proposed[label] = suggestion;
  5526. result.items.push(suggestion);
  5527. }
  5528. else {
  5529. if (!existing.documentation) {
  5530. existing.documentation = suggestion.documentation;
  5531. }
  5532. if (!existing.detail) {
  5533. existing.detail = suggestion.detail;
  5534. }
  5535. }
  5536. },
  5537. setAsIncomplete: function () {
  5538. result.isIncomplete = true;
  5539. },
  5540. error: function (message) {
  5541. console.error(message);
  5542. },
  5543. log: function (message) {
  5544. console.log(message);
  5545. },
  5546. getNumberOfProposals: function () {
  5547. return result.items.length;
  5548. }
  5549. };
  5550. return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
  5551. var collectionPromises = [];
  5552. var addValue = true;
  5553. var currentKey = '';
  5554. var currentProperty = undefined;
  5555. if (node) {
  5556. if (node.type === 'string') {
  5557. var parent = node.parent;
  5558. if (parent && parent.type === 'property' && parent.keyNode === node) {
  5559. addValue = !parent.valueNode;
  5560. currentProperty = parent;
  5561. currentKey = text.substr(node.offset + 1, node.length - 2);
  5562. if (parent) {
  5563. node = parent.parent;
  5564. }
  5565. }
  5566. }
  5567. }
  5568. // proposals for properties
  5569. if (node && node.type === 'object') {
  5570. // don't suggest keys when the cursor is just before the opening curly brace
  5571. if (node.offset === offset) {
  5572. return result;
  5573. }
  5574. // don't suggest properties that are already present
  5575. var properties = node.properties;
  5576. properties.forEach(function (p) {
  5577. if (!currentProperty || currentProperty !== p) {
  5578. proposed[p.keyNode.value] = jsonLanguageTypes_1.CompletionItem.create('__');
  5579. }
  5580. });
  5581. var separatorAfter_1 = '';
  5582. if (addValue) {
  5583. separatorAfter_1 = _this.evaluateSeparatorAfter(document, document.offsetAt(overwriteRange.end));
  5584. }
  5585. if (schema) {
  5586. // property proposals with schema
  5587. _this.getPropertyCompletions(schema, doc, node, addValue, separatorAfter_1, collector);
  5588. }
  5589. else {
  5590. // property proposals without schema
  5591. _this.getSchemaLessPropertyCompletions(doc, node, currentKey, collector);
  5592. }
  5593. var location_1 = Parser.getNodePath(node);
  5594. _this.contributions.forEach(function (contribution) {
  5595. var collectPromise = contribution.collectPropertyCompletions(document.uri, location_1, currentWord, addValue, separatorAfter_1 === '', collector);
  5596. if (collectPromise) {
  5597. collectionPromises.push(collectPromise);
  5598. }
  5599. });
  5600. if ((!schema && currentWord.length > 0 && text.charAt(offset - currentWord.length - 1) !== '"')) {
  5601. collector.add({
  5602. kind: jsonLanguageTypes_1.CompletionItemKind.Property,
  5603. label: _this.getLabelForValue(currentWord),
  5604. insertText: _this.getInsertTextForProperty(currentWord, undefined, false, separatorAfter_1),
  5605. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet, documentation: '',
  5606. });
  5607. collector.setAsIncomplete();
  5608. }
  5609. }
  5610. // proposals for values
  5611. var types = {};
  5612. if (schema) {
  5613. // value proposals with schema
  5614. _this.getValueCompletions(schema, doc, node, offset, document, collector, types);
  5615. }
  5616. else {
  5617. // value proposals without schema
  5618. _this.getSchemaLessValueCompletions(doc, node, offset, document, collector);
  5619. }
  5620. if (_this.contributions.length > 0) {
  5621. _this.getContributedValueCompletions(doc, node, offset, document, collector, collectionPromises);
  5622. }
  5623. return _this.promiseConstructor.all(collectionPromises).then(function () {
  5624. if (collector.getNumberOfProposals() === 0) {
  5625. var offsetForSeparator = offset;
  5626. if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
  5627. offsetForSeparator = node.offset + node.length;
  5628. }
  5629. var separatorAfter = _this.evaluateSeparatorAfter(document, offsetForSeparator);
  5630. _this.addFillerValueCompletions(types, separatorAfter, collector);
  5631. }
  5632. return result;
  5633. });
  5634. });
  5635. };
  5636. JSONCompletion.prototype.getPropertyCompletions = function (schema, doc, node, addValue, separatorAfter, collector) {
  5637. var _this = this;
  5638. var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset);
  5639. matchingSchemas.forEach(function (s) {
  5640. if (s.node === node && !s.inverted) {
  5641. var schemaProperties_1 = s.schema.properties;
  5642. if (schemaProperties_1) {
  5643. Object.keys(schemaProperties_1).forEach(function (key) {
  5644. var propertySchema = schemaProperties_1[key];
  5645. if (typeof propertySchema === 'object' && !propertySchema.deprecationMessage && !propertySchema.doNotSuggest) {
  5646. var proposal = {
  5647. kind: jsonLanguageTypes_1.CompletionItemKind.Property,
  5648. label: key,
  5649. insertText: _this.getInsertTextForProperty(key, propertySchema, addValue, separatorAfter),
  5650. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5651. filterText: _this.getFilterTextForValue(key),
  5652. documentation: _this.fromMarkup(propertySchema.markdownDescription) || propertySchema.description || '',
  5653. };
  5654. if (propertySchema.suggestSortText !== undefined) {
  5655. proposal.sortText = propertySchema.suggestSortText;
  5656. }
  5657. if (proposal.insertText && strings_1.endsWith(proposal.insertText, "$1" + separatorAfter)) {
  5658. proposal.command = {
  5659. title: 'Suggest',
  5660. command: 'editor.action.triggerSuggest'
  5661. };
  5662. }
  5663. collector.add(proposal);
  5664. }
  5665. });
  5666. }
  5667. var schemaPropertyNames_1 = s.schema.propertyNames;
  5668. if (typeof schemaPropertyNames_1 === 'object' && !schemaPropertyNames_1.deprecationMessage && !schemaPropertyNames_1.doNotSuggest) {
  5669. var propertyNameCompletionItem = function (name, enumDescription) {
  5670. if (enumDescription === void 0) { enumDescription = undefined; }
  5671. var proposal = {
  5672. kind: jsonLanguageTypes_1.CompletionItemKind.Property,
  5673. label: name,
  5674. insertText: _this.getInsertTextForProperty(name, undefined, addValue, separatorAfter),
  5675. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5676. filterText: _this.getFilterTextForValue(name),
  5677. documentation: enumDescription || _this.fromMarkup(schemaPropertyNames_1.markdownDescription) || schemaPropertyNames_1.description || '',
  5678. };
  5679. if (schemaPropertyNames_1.suggestSortText !== undefined) {
  5680. proposal.sortText = schemaPropertyNames_1.suggestSortText;
  5681. }
  5682. if (proposal.insertText && strings_1.endsWith(proposal.insertText, "$1" + separatorAfter)) {
  5683. proposal.command = {
  5684. title: 'Suggest',
  5685. command: 'editor.action.triggerSuggest'
  5686. };
  5687. }
  5688. collector.add(proposal);
  5689. };
  5690. if (schemaPropertyNames_1.enum) {
  5691. for (var i = 0; i < schemaPropertyNames_1.enum.length; i++) {
  5692. var enumDescription = undefined;
  5693. if (schemaPropertyNames_1.markdownEnumDescriptions && i < schemaPropertyNames_1.markdownEnumDescriptions.length) {
  5694. enumDescription = _this.fromMarkup(schemaPropertyNames_1.markdownEnumDescriptions[i]);
  5695. }
  5696. else if (schemaPropertyNames_1.enumDescriptions && i < schemaPropertyNames_1.enumDescriptions.length) {
  5697. enumDescription = schemaPropertyNames_1.enumDescriptions[i];
  5698. }
  5699. propertyNameCompletionItem(schemaPropertyNames_1.enum[i], enumDescription);
  5700. }
  5701. }
  5702. if (schemaPropertyNames_1.const) {
  5703. propertyNameCompletionItem(schemaPropertyNames_1.const);
  5704. }
  5705. }
  5706. }
  5707. });
  5708. };
  5709. JSONCompletion.prototype.getSchemaLessPropertyCompletions = function (doc, node, currentKey, collector) {
  5710. var _this = this;
  5711. var collectCompletionsForSimilarObject = function (obj) {
  5712. obj.properties.forEach(function (p) {
  5713. var key = p.keyNode.value;
  5714. collector.add({
  5715. kind: jsonLanguageTypes_1.CompletionItemKind.Property,
  5716. label: key,
  5717. insertText: _this.getInsertTextForValue(key, ''),
  5718. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5719. filterText: _this.getFilterTextForValue(key),
  5720. documentation: ''
  5721. });
  5722. });
  5723. };
  5724. if (node.parent) {
  5725. if (node.parent.type === 'property') {
  5726. // if the object is a property value, check the tree for other objects that hang under a property of the same name
  5727. var parentKey_1 = node.parent.keyNode.value;
  5728. doc.visit(function (n) {
  5729. if (n.type === 'property' && n !== node.parent && n.keyNode.value === parentKey_1 && n.valueNode && n.valueNode.type === 'object') {
  5730. collectCompletionsForSimilarObject(n.valueNode);
  5731. }
  5732. return true;
  5733. });
  5734. }
  5735. else if (node.parent.type === 'array') {
  5736. // if the object is in an array, use all other array elements as similar objects
  5737. node.parent.items.forEach(function (n) {
  5738. if (n.type === 'object' && n !== node) {
  5739. collectCompletionsForSimilarObject(n);
  5740. }
  5741. });
  5742. }
  5743. }
  5744. else if (node.type === 'object') {
  5745. collector.add({
  5746. kind: jsonLanguageTypes_1.CompletionItemKind.Property,
  5747. label: '$schema',
  5748. insertText: this.getInsertTextForProperty('$schema', undefined, true, ''),
  5749. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet, documentation: '',
  5750. filterText: this.getFilterTextForValue("$schema")
  5751. });
  5752. }
  5753. };
  5754. JSONCompletion.prototype.getSchemaLessValueCompletions = function (doc, node, offset, document, collector) {
  5755. var _this = this;
  5756. var offsetForSeparator = offset;
  5757. if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
  5758. offsetForSeparator = node.offset + node.length;
  5759. node = node.parent;
  5760. }
  5761. if (!node) {
  5762. collector.add({
  5763. kind: this.getSuggestionKind('object'),
  5764. label: 'Empty object',
  5765. insertText: this.getInsertTextForValue({}, ''),
  5766. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5767. documentation: ''
  5768. });
  5769. collector.add({
  5770. kind: this.getSuggestionKind('array'),
  5771. label: 'Empty array',
  5772. insertText: this.getInsertTextForValue([], ''),
  5773. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5774. documentation: ''
  5775. });
  5776. return;
  5777. }
  5778. var separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator);
  5779. var collectSuggestionsForValues = function (value) {
  5780. if (value.parent && !Parser.contains(value.parent, offset, true)) {
  5781. collector.add({
  5782. kind: _this.getSuggestionKind(value.type),
  5783. label: _this.getLabelTextForMatchingNode(value, document),
  5784. insertText: _this.getInsertTextForMatchingNode(value, document, separatorAfter),
  5785. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet, documentation: ''
  5786. });
  5787. }
  5788. if (value.type === 'boolean') {
  5789. _this.addBooleanValueCompletion(!value.value, separatorAfter, collector);
  5790. }
  5791. };
  5792. if (node.type === 'property') {
  5793. if (offset > (node.colonOffset || 0)) {
  5794. var valueNode = node.valueNode;
  5795. if (valueNode && (offset > (valueNode.offset + valueNode.length) || valueNode.type === 'object' || valueNode.type === 'array')) {
  5796. return;
  5797. }
  5798. // suggest values at the same key
  5799. var parentKey_2 = node.keyNode.value;
  5800. doc.visit(function (n) {
  5801. if (n.type === 'property' && n.keyNode.value === parentKey_2 && n.valueNode) {
  5802. collectSuggestionsForValues(n.valueNode);
  5803. }
  5804. return true;
  5805. });
  5806. if (parentKey_2 === '$schema' && node.parent && !node.parent.parent) {
  5807. this.addDollarSchemaCompletions(separatorAfter, collector);
  5808. }
  5809. }
  5810. }
  5811. if (node.type === 'array') {
  5812. if (node.parent && node.parent.type === 'property') {
  5813. // suggest items of an array at the same key
  5814. var parentKey_3 = node.parent.keyNode.value;
  5815. doc.visit(function (n) {
  5816. if (n.type === 'property' && n.keyNode.value === parentKey_3 && n.valueNode && n.valueNode.type === 'array') {
  5817. n.valueNode.items.forEach(collectSuggestionsForValues);
  5818. }
  5819. return true;
  5820. });
  5821. }
  5822. else {
  5823. // suggest items in the same array
  5824. node.items.forEach(collectSuggestionsForValues);
  5825. }
  5826. }
  5827. };
  5828. JSONCompletion.prototype.getValueCompletions = function (schema, doc, node, offset, document, collector, types) {
  5829. var offsetForSeparator = offset;
  5830. var parentKey = undefined;
  5831. var valueNode = undefined;
  5832. if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
  5833. offsetForSeparator = node.offset + node.length;
  5834. valueNode = node;
  5835. node = node.parent;
  5836. }
  5837. if (!node) {
  5838. this.addSchemaValueCompletions(schema.schema, '', collector, types);
  5839. return;
  5840. }
  5841. if ((node.type === 'property') && offset > (node.colonOffset || 0)) {
  5842. var valueNode_1 = node.valueNode;
  5843. if (valueNode_1 && offset > (valueNode_1.offset + valueNode_1.length)) {
  5844. return; // we are past the value node
  5845. }
  5846. parentKey = node.keyNode.value;
  5847. node = node.parent;
  5848. }
  5849. if (node && (parentKey !== undefined || node.type === 'array')) {
  5850. var separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator);
  5851. var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset, valueNode);
  5852. for (var _i = 0, matchingSchemas_1 = matchingSchemas; _i < matchingSchemas_1.length; _i++) {
  5853. var s = matchingSchemas_1[_i];
  5854. if (s.node === node && !s.inverted && s.schema) {
  5855. if (node.type === 'array' && s.schema.items) {
  5856. if (Array.isArray(s.schema.items)) {
  5857. var index = this.findItemAtOffset(node, document, offset);
  5858. if (index < s.schema.items.length) {
  5859. this.addSchemaValueCompletions(s.schema.items[index], separatorAfter, collector, types);
  5860. }
  5861. }
  5862. else {
  5863. this.addSchemaValueCompletions(s.schema.items, separatorAfter, collector, types);
  5864. }
  5865. }
  5866. if (parentKey !== undefined) {
  5867. var propertyMatched = false;
  5868. if (s.schema.properties) {
  5869. var propertySchema = s.schema.properties[parentKey];
  5870. if (propertySchema) {
  5871. propertyMatched = true;
  5872. this.addSchemaValueCompletions(propertySchema, separatorAfter, collector, types);
  5873. }
  5874. }
  5875. if (s.schema.patternProperties && !propertyMatched) {
  5876. for (var _a = 0, _b = Object.keys(s.schema.patternProperties); _a < _b.length; _a++) {
  5877. var pattern = _b[_a];
  5878. var regex = strings_1.extendedRegExp(pattern);
  5879. if (regex.test(parentKey)) {
  5880. propertyMatched = true;
  5881. var propertySchema = s.schema.patternProperties[pattern];
  5882. this.addSchemaValueCompletions(propertySchema, separatorAfter, collector, types);
  5883. }
  5884. }
  5885. }
  5886. if (s.schema.additionalProperties && !propertyMatched) {
  5887. var propertySchema = s.schema.additionalProperties;
  5888. this.addSchemaValueCompletions(propertySchema, separatorAfter, collector, types);
  5889. }
  5890. }
  5891. }
  5892. }
  5893. if (parentKey === '$schema' && !node.parent) {
  5894. this.addDollarSchemaCompletions(separatorAfter, collector);
  5895. }
  5896. if (types['boolean']) {
  5897. this.addBooleanValueCompletion(true, separatorAfter, collector);
  5898. this.addBooleanValueCompletion(false, separatorAfter, collector);
  5899. }
  5900. if (types['null']) {
  5901. this.addNullValueCompletion(separatorAfter, collector);
  5902. }
  5903. }
  5904. };
  5905. JSONCompletion.prototype.getContributedValueCompletions = function (doc, node, offset, document, collector, collectionPromises) {
  5906. if (!node) {
  5907. this.contributions.forEach(function (contribution) {
  5908. var collectPromise = contribution.collectDefaultCompletions(document.uri, collector);
  5909. if (collectPromise) {
  5910. collectionPromises.push(collectPromise);
  5911. }
  5912. });
  5913. }
  5914. else {
  5915. if (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null') {
  5916. node = node.parent;
  5917. }
  5918. if (node && (node.type === 'property') && offset > (node.colonOffset || 0)) {
  5919. var parentKey_4 = node.keyNode.value;
  5920. var valueNode = node.valueNode;
  5921. if ((!valueNode || offset <= (valueNode.offset + valueNode.length)) && node.parent) {
  5922. var location_2 = Parser.getNodePath(node.parent);
  5923. this.contributions.forEach(function (contribution) {
  5924. var collectPromise = contribution.collectValueCompletions(document.uri, location_2, parentKey_4, collector);
  5925. if (collectPromise) {
  5926. collectionPromises.push(collectPromise);
  5927. }
  5928. });
  5929. }
  5930. }
  5931. }
  5932. };
  5933. JSONCompletion.prototype.addSchemaValueCompletions = function (schema, separatorAfter, collector, types) {
  5934. var _this = this;
  5935. if (typeof schema === 'object') {
  5936. this.addEnumValueCompletions(schema, separatorAfter, collector);
  5937. this.addDefaultValueCompletions(schema, separatorAfter, collector);
  5938. this.collectTypes(schema, types);
  5939. if (Array.isArray(schema.allOf)) {
  5940. schema.allOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
  5941. }
  5942. if (Array.isArray(schema.anyOf)) {
  5943. schema.anyOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
  5944. }
  5945. if (Array.isArray(schema.oneOf)) {
  5946. schema.oneOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
  5947. }
  5948. }
  5949. };
  5950. JSONCompletion.prototype.addDefaultValueCompletions = function (schema, separatorAfter, collector, arrayDepth) {
  5951. var _this = this;
  5952. if (arrayDepth === void 0) { arrayDepth = 0; }
  5953. var hasProposals = false;
  5954. if (objects_1.isDefined(schema.default)) {
  5955. var type = schema.type;
  5956. var value = schema.default;
  5957. for (var i = arrayDepth; i > 0; i--) {
  5958. value = [value];
  5959. type = 'array';
  5960. }
  5961. collector.add({
  5962. kind: this.getSuggestionKind(type),
  5963. label: this.getLabelForValue(value),
  5964. insertText: this.getInsertTextForValue(value, separatorAfter),
  5965. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5966. detail: localize('json.suggest.default', 'Default value')
  5967. });
  5968. hasProposals = true;
  5969. }
  5970. if (Array.isArray(schema.examples)) {
  5971. schema.examples.forEach(function (example) {
  5972. var type = schema.type;
  5973. var value = example;
  5974. for (var i = arrayDepth; i > 0; i--) {
  5975. value = [value];
  5976. type = 'array';
  5977. }
  5978. collector.add({
  5979. kind: _this.getSuggestionKind(type),
  5980. label: _this.getLabelForValue(value),
  5981. insertText: _this.getInsertTextForValue(value, separatorAfter),
  5982. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet
  5983. });
  5984. hasProposals = true;
  5985. });
  5986. }
  5987. if (Array.isArray(schema.defaultSnippets)) {
  5988. schema.defaultSnippets.forEach(function (s) {
  5989. var type = schema.type;
  5990. var value = s.body;
  5991. var label = s.label;
  5992. var insertText;
  5993. var filterText;
  5994. if (objects_1.isDefined(value)) {
  5995. var type_1 = schema.type;
  5996. for (var i = arrayDepth; i > 0; i--) {
  5997. value = [value];
  5998. type_1 = 'array';
  5999. }
  6000. insertText = _this.getInsertTextForSnippetValue(value, separatorAfter);
  6001. filterText = _this.getFilterTextForSnippetValue(value);
  6002. label = label || _this.getLabelForSnippetValue(value);
  6003. }
  6004. else if (typeof s.bodyText === 'string') {
  6005. var prefix = '', suffix = '', indent = '';
  6006. for (var i = arrayDepth; i > 0; i--) {
  6007. prefix = prefix + indent + '[\n';
  6008. suffix = suffix + '\n' + indent + ']';
  6009. indent += '\t';
  6010. type = 'array';
  6011. }
  6012. insertText = prefix + indent + s.bodyText.split('\n').join('\n' + indent) + suffix + separatorAfter;
  6013. label = label || insertText,
  6014. filterText = insertText.replace(/[\n]/g, ''); // remove new lines
  6015. }
  6016. else {
  6017. return;
  6018. }
  6019. collector.add({
  6020. kind: _this.getSuggestionKind(type),
  6021. label: label,
  6022. documentation: _this.fromMarkup(s.markdownDescription) || s.description,
  6023. insertText: insertText,
  6024. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  6025. filterText: filterText
  6026. });
  6027. hasProposals = true;
  6028. });
  6029. }
  6030. if (!hasProposals && typeof schema.items === 'object' && !Array.isArray(schema.items) && arrayDepth < 5 /* beware of recursion */) {
  6031. this.addDefaultValueCompletions(schema.items, separatorAfter, collector, arrayDepth + 1);
  6032. }
  6033. };
  6034. JSONCompletion.prototype.addEnumValueCompletions = function (schema, separatorAfter, collector) {
  6035. if (objects_1.isDefined(schema.const)) {
  6036. collector.add({
  6037. kind: this.getSuggestionKind(schema.type),
  6038. label: this.getLabelForValue(schema.const),
  6039. insertText: this.getInsertTextForValue(schema.const, separatorAfter),
  6040. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  6041. documentation: this.fromMarkup(schema.markdownDescription) || schema.description
  6042. });
  6043. }
  6044. if (Array.isArray(schema.enum)) {
  6045. for (var i = 0, length = schema.enum.length; i < length; i++) {
  6046. var enm = schema.enum[i];
  6047. var documentation = this.fromMarkup(schema.markdownDescription) || schema.description;
  6048. if (schema.markdownEnumDescriptions && i < schema.markdownEnumDescriptions.length && this.doesSupportMarkdown()) {
  6049. documentation = this.fromMarkup(schema.markdownEnumDescriptions[i]);
  6050. }
  6051. else if (schema.enumDescriptions && i < schema.enumDescriptions.length) {
  6052. documentation = schema.enumDescriptions[i];
  6053. }
  6054. collector.add({
  6055. kind: this.getSuggestionKind(schema.type),
  6056. label: this.getLabelForValue(enm),
  6057. insertText: this.getInsertTextForValue(enm, separatorAfter),
  6058. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  6059. documentation: documentation
  6060. });
  6061. }
  6062. }
  6063. };
  6064. JSONCompletion.prototype.collectTypes = function (schema, types) {
  6065. if (Array.isArray(schema.enum) || objects_1.isDefined(schema.const)) {
  6066. return;
  6067. }
  6068. var type = schema.type;
  6069. if (Array.isArray(type)) {
  6070. type.forEach(function (t) { return types[t] = true; });
  6071. }
  6072. else if (type) {
  6073. types[type] = true;
  6074. }
  6075. };
  6076. JSONCompletion.prototype.addFillerValueCompletions = function (types, separatorAfter, collector) {
  6077. if (types['object']) {
  6078. collector.add({
  6079. kind: this.getSuggestionKind('object'),
  6080. label: '{}',
  6081. insertText: this.getInsertTextForGuessedValue({}, separatorAfter),
  6082. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  6083. detail: localize('defaults.object', 'New object'),
  6084. documentation: ''
  6085. });
  6086. }
  6087. if (types['array']) {
  6088. collector.add({
  6089. kind: this.getSuggestionKind('array'),
  6090. label: '[]',
  6091. insertText: this.getInsertTextForGuessedValue([], separatorAfter),
  6092. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  6093. detail: localize('defaults.array', 'New array'),
  6094. documentation: ''
  6095. });
  6096. }
  6097. };
  6098. JSONCompletion.prototype.addBooleanValueCompletion = function (value, separatorAfter, collector) {
  6099. collector.add({
  6100. kind: this.getSuggestionKind('boolean'),
  6101. label: value ? 'true' : 'false',
  6102. insertText: this.getInsertTextForValue(value, separatorAfter),
  6103. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  6104. documentation: ''
  6105. });
  6106. };
  6107. JSONCompletion.prototype.addNullValueCompletion = function (separatorAfter, collector) {
  6108. collector.add({
  6109. kind: this.getSuggestionKind('null'),
  6110. label: 'null',
  6111. insertText: 'null' + separatorAfter,
  6112. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  6113. documentation: ''
  6114. });
  6115. };
  6116. JSONCompletion.prototype.addDollarSchemaCompletions = function (separatorAfter, collector) {
  6117. var _this = this;
  6118. var schemaIds = this.schemaService.getRegisteredSchemaIds(function (schema) { return schema === 'http' || schema === 'https'; });
  6119. schemaIds.forEach(function (schemaId) { return collector.add({
  6120. kind: jsonLanguageTypes_1.CompletionItemKind.Module,
  6121. label: _this.getLabelForValue(schemaId),
  6122. filterText: _this.getFilterTextForValue(schemaId),
  6123. insertText: _this.getInsertTextForValue(schemaId, separatorAfter),
  6124. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet, documentation: ''
  6125. }); });
  6126. };
  6127. JSONCompletion.prototype.getLabelForValue = function (value) {
  6128. return JSON.stringify(value);
  6129. };
  6130. JSONCompletion.prototype.getFilterTextForValue = function (value) {
  6131. return JSON.stringify(value);
  6132. };
  6133. JSONCompletion.prototype.getFilterTextForSnippetValue = function (value) {
  6134. return JSON.stringify(value).replace(/\$\{\d+:([^}]+)\}|\$\d+/g, '$1');
  6135. };
  6136. JSONCompletion.prototype.getLabelForSnippetValue = function (value) {
  6137. var label = JSON.stringify(value);
  6138. return label.replace(/\$\{\d+:([^}]+)\}|\$\d+/g, '$1');
  6139. };
  6140. JSONCompletion.prototype.getInsertTextForPlainText = function (text) {
  6141. return text.replace(/[\\\$\}]/g, '\\$&'); // escape $, \ and }
  6142. };
  6143. JSONCompletion.prototype.getInsertTextForValue = function (value, separatorAfter) {
  6144. var text = JSON.stringify(value, null, '\t');
  6145. if (text === '{}') {
  6146. return '{$1}' + separatorAfter;
  6147. }
  6148. else if (text === '[]') {
  6149. return '[$1]' + separatorAfter;
  6150. }
  6151. return this.getInsertTextForPlainText(text + separatorAfter);
  6152. };
  6153. JSONCompletion.prototype.getInsertTextForSnippetValue = function (value, separatorAfter) {
  6154. var replacer = function (value) {
  6155. if (typeof value === 'string') {
  6156. if (value[0] === '^') {
  6157. return value.substr(1);
  6158. }
  6159. }
  6160. return JSON.stringify(value);
  6161. };
  6162. return json_1.stringifyObject(value, '', replacer) + separatorAfter;
  6163. };
  6164. JSONCompletion.prototype.getInsertTextForGuessedValue = function (value, separatorAfter) {
  6165. switch (typeof value) {
  6166. case 'object':
  6167. if (value === null) {
  6168. return '${1:null}' + separatorAfter;
  6169. }
  6170. return this.getInsertTextForValue(value, separatorAfter);
  6171. case 'string':
  6172. var snippetValue = JSON.stringify(value);
  6173. snippetValue = snippetValue.substr(1, snippetValue.length - 2); // remove quotes
  6174. snippetValue = this.getInsertTextForPlainText(snippetValue); // escape \ and }
  6175. return '"${1:' + snippetValue + '}"' + separatorAfter;
  6176. case 'number':
  6177. case 'boolean':
  6178. return '${1:' + JSON.stringify(value) + '}' + separatorAfter;
  6179. }
  6180. return this.getInsertTextForValue(value, separatorAfter);
  6181. };
  6182. JSONCompletion.prototype.getSuggestionKind = function (type) {
  6183. if (Array.isArray(type)) {
  6184. var array = type;
  6185. type = array.length > 0 ? array[0] : undefined;
  6186. }
  6187. if (!type) {
  6188. return jsonLanguageTypes_1.CompletionItemKind.Value;
  6189. }
  6190. switch (type) {
  6191. case 'string': return jsonLanguageTypes_1.CompletionItemKind.Value;
  6192. case 'object': return jsonLanguageTypes_1.CompletionItemKind.Module;
  6193. case 'property': return jsonLanguageTypes_1.CompletionItemKind.Property;
  6194. default: return jsonLanguageTypes_1.CompletionItemKind.Value;
  6195. }
  6196. };
  6197. JSONCompletion.prototype.getLabelTextForMatchingNode = function (node, document) {
  6198. switch (node.type) {
  6199. case 'array':
  6200. return '[]';
  6201. case 'object':
  6202. return '{}';
  6203. default:
  6204. var content = document.getText().substr(node.offset, node.length);
  6205. return content;
  6206. }
  6207. };
  6208. JSONCompletion.prototype.getInsertTextForMatchingNode = function (node, document, separatorAfter) {
  6209. switch (node.type) {
  6210. case 'array':
  6211. return this.getInsertTextForValue([], separatorAfter);
  6212. case 'object':
  6213. return this.getInsertTextForValue({}, separatorAfter);
  6214. default:
  6215. var content = document.getText().substr(node.offset, node.length) + separatorAfter;
  6216. return this.getInsertTextForPlainText(content);
  6217. }
  6218. };
  6219. JSONCompletion.prototype.getInsertTextForProperty = function (key, propertySchema, addValue, separatorAfter) {
  6220. var propertyText = this.getInsertTextForValue(key, '');
  6221. if (!addValue) {
  6222. return propertyText;
  6223. }
  6224. var resultText = propertyText + ': ';
  6225. var value;
  6226. var nValueProposals = 0;
  6227. if (propertySchema) {
  6228. if (Array.isArray(propertySchema.defaultSnippets)) {
  6229. if (propertySchema.defaultSnippets.length === 1) {
  6230. var body = propertySchema.defaultSnippets[0].body;
  6231. if (objects_1.isDefined(body)) {
  6232. value = this.getInsertTextForSnippetValue(body, '');
  6233. }
  6234. }
  6235. nValueProposals += propertySchema.defaultSnippets.length;
  6236. }
  6237. if (propertySchema.enum) {
  6238. if (!value && propertySchema.enum.length === 1) {
  6239. value = this.getInsertTextForGuessedValue(propertySchema.enum[0], '');
  6240. }
  6241. nValueProposals += propertySchema.enum.length;
  6242. }
  6243. if (objects_1.isDefined(propertySchema.default)) {
  6244. if (!value) {
  6245. value = this.getInsertTextForGuessedValue(propertySchema.default, '');
  6246. }
  6247. nValueProposals++;
  6248. }
  6249. if (Array.isArray(propertySchema.examples) && propertySchema.examples.length) {
  6250. if (!value) {
  6251. value = this.getInsertTextForGuessedValue(propertySchema.examples[0], '');
  6252. }
  6253. nValueProposals += propertySchema.examples.length;
  6254. }
  6255. if (nValueProposals === 0) {
  6256. var type = Array.isArray(propertySchema.type) ? propertySchema.type[0] : propertySchema.type;
  6257. if (!type) {
  6258. if (propertySchema.properties) {
  6259. type = 'object';
  6260. }
  6261. else if (propertySchema.items) {
  6262. type = 'array';
  6263. }
  6264. }
  6265. switch (type) {
  6266. case 'boolean':
  6267. value = '$1';
  6268. break;
  6269. case 'string':
  6270. value = '"$1"';
  6271. break;
  6272. case 'object':
  6273. value = '{$1}';
  6274. break;
  6275. case 'array':
  6276. value = '[$1]';
  6277. break;
  6278. case 'number':
  6279. case 'integer':
  6280. value = '${1:0}';
  6281. break;
  6282. case 'null':
  6283. value = '${1:null}';
  6284. break;
  6285. default:
  6286. return propertyText;
  6287. }
  6288. }
  6289. }
  6290. if (!value || nValueProposals > 1) {
  6291. value = '$1';
  6292. }
  6293. return resultText + value + separatorAfter;
  6294. };
  6295. JSONCompletion.prototype.getCurrentWord = function (document, offset) {
  6296. var i = offset - 1;
  6297. var text = document.getText();
  6298. while (i >= 0 && ' \t\n\r\v":{[,]}'.indexOf(text.charAt(i)) === -1) {
  6299. i--;
  6300. }
  6301. return text.substring(i + 1, offset);
  6302. };
  6303. JSONCompletion.prototype.evaluateSeparatorAfter = function (document, offset) {
  6304. var scanner = Json.createScanner(document.getText(), true);
  6305. scanner.setPosition(offset);
  6306. var token = scanner.scan();
  6307. switch (token) {
  6308. case 5 /* CommaToken */:
  6309. case 2 /* CloseBraceToken */:
  6310. case 4 /* CloseBracketToken */:
  6311. case 17 /* EOF */:
  6312. return '';
  6313. default:
  6314. return ',';
  6315. }
  6316. };
  6317. JSONCompletion.prototype.findItemAtOffset = function (node, document, offset) {
  6318. var scanner = Json.createScanner(document.getText(), true);
  6319. var children = node.items;
  6320. for (var i = children.length - 1; i >= 0; i--) {
  6321. var child = children[i];
  6322. if (offset > child.offset + child.length) {
  6323. scanner.setPosition(child.offset + child.length);
  6324. var token = scanner.scan();
  6325. if (token === 5 /* CommaToken */ && offset >= scanner.getTokenOffset() + scanner.getTokenLength()) {
  6326. return i + 1;
  6327. }
  6328. return i;
  6329. }
  6330. else if (offset >= child.offset) {
  6331. return i;
  6332. }
  6333. }
  6334. return 0;
  6335. };
  6336. JSONCompletion.prototype.isInComment = function (document, start, offset) {
  6337. var scanner = Json.createScanner(document.getText(), false);
  6338. scanner.setPosition(start);
  6339. var token = scanner.scan();
  6340. while (token !== 17 /* EOF */ && (scanner.getTokenOffset() + scanner.getTokenLength() < offset)) {
  6341. token = scanner.scan();
  6342. }
  6343. return (token === 12 /* LineCommentTrivia */ || token === 13 /* BlockCommentTrivia */) && scanner.getTokenOffset() <= offset;
  6344. };
  6345. JSONCompletion.prototype.fromMarkup = function (markupString) {
  6346. if (markupString && this.doesSupportMarkdown()) {
  6347. return {
  6348. kind: jsonLanguageTypes_1.MarkupKind.Markdown,
  6349. value: markupString
  6350. };
  6351. }
  6352. return undefined;
  6353. };
  6354. JSONCompletion.prototype.doesSupportMarkdown = function () {
  6355. if (!objects_1.isDefined(this.supportsMarkdown)) {
  6356. var completion = this.clientCapabilities.textDocument && this.clientCapabilities.textDocument.completion;
  6357. this.supportsMarkdown = completion && completion.completionItem && Array.isArray(completion.completionItem.documentationFormat) && completion.completionItem.documentationFormat.indexOf(jsonLanguageTypes_1.MarkupKind.Markdown) !== -1;
  6358. }
  6359. return this.supportsMarkdown;
  6360. };
  6361. JSONCompletion.prototype.doesSupportsCommitCharacters = function () {
  6362. if (!objects_1.isDefined(this.supportsCommitCharacters)) {
  6363. var completion = this.clientCapabilities.textDocument && this.clientCapabilities.textDocument.completion;
  6364. this.supportsCommitCharacters = completion && completion.completionItem && !!completion.completionItem.commitCharactersSupport;
  6365. }
  6366. return this.supportsCommitCharacters;
  6367. };
  6368. return JSONCompletion;
  6369. }());
  6370. exports.JSONCompletion = JSONCompletion;
  6371. });
  6372. /*---------------------------------------------------------------------------------------------
  6373. * Copyright (c) Microsoft Corporation. All rights reserved.
  6374. * Licensed under the MIT License. See License.txt in the project root for license information.
  6375. *--------------------------------------------------------------------------------------------*/
  6376. (function (factory) {
  6377. if (typeof module === "object" && typeof module.exports === "object") {
  6378. var v = factory(require, exports);
  6379. if (v !== undefined) module.exports = v;
  6380. }
  6381. else if (typeof define === "function" && define.amd) {
  6382. define('vscode-json-languageservice/services/jsonHover',["require", "exports", "../parser/jsonParser", "../jsonLanguageTypes"], factory);
  6383. }
  6384. })(function (require, exports) {
  6385. "use strict";
  6386. Object.defineProperty(exports, "__esModule", { value: true });
  6387. exports.JSONHover = void 0;
  6388. var Parser = require("../parser/jsonParser");
  6389. var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
  6390. var JSONHover = /** @class */ (function () {
  6391. function JSONHover(schemaService, contributions, promiseConstructor) {
  6392. if (contributions === void 0) { contributions = []; }
  6393. this.schemaService = schemaService;
  6394. this.contributions = contributions;
  6395. this.promise = promiseConstructor || Promise;
  6396. }
  6397. JSONHover.prototype.doHover = function (document, position, doc) {
  6398. var offset = document.offsetAt(position);
  6399. var node = doc.getNodeFromOffset(offset);
  6400. if (!node || (node.type === 'object' || node.type === 'array') && offset > node.offset + 1 && offset < node.offset + node.length - 1) {
  6401. return this.promise.resolve(null);
  6402. }
  6403. var hoverRangeNode = node;
  6404. // use the property description when hovering over an object key
  6405. if (node.type === 'string') {
  6406. var parent = node.parent;
  6407. if (parent && parent.type === 'property' && parent.keyNode === node) {
  6408. node = parent.valueNode;
  6409. if (!node) {
  6410. return this.promise.resolve(null);
  6411. }
  6412. }
  6413. }
  6414. var hoverRange = jsonLanguageTypes_1.Range.create(document.positionAt(hoverRangeNode.offset), document.positionAt(hoverRangeNode.offset + hoverRangeNode.length));
  6415. var createHover = function (contents) {
  6416. var result = {
  6417. contents: contents,
  6418. range: hoverRange
  6419. };
  6420. return result;
  6421. };
  6422. var location = Parser.getNodePath(node);
  6423. for (var i = this.contributions.length - 1; i >= 0; i--) {
  6424. var contribution = this.contributions[i];
  6425. var promise = contribution.getInfoContribution(document.uri, location);
  6426. if (promise) {
  6427. return promise.then(function (htmlContent) { return createHover(htmlContent); });
  6428. }
  6429. }
  6430. return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
  6431. if (schema && node) {
  6432. var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset);
  6433. var title_1 = undefined;
  6434. var markdownDescription_1 = undefined;
  6435. var markdownEnumValueDescription_1 = undefined, enumValue_1 = undefined;
  6436. matchingSchemas.every(function (s) {
  6437. if (s.node === node && !s.inverted && s.schema) {
  6438. title_1 = title_1 || s.schema.title;
  6439. markdownDescription_1 = markdownDescription_1 || s.schema.markdownDescription || toMarkdown(s.schema.description);
  6440. if (s.schema.enum) {
  6441. var idx = s.schema.enum.indexOf(Parser.getNodeValue(node));
  6442. if (s.schema.markdownEnumDescriptions) {
  6443. markdownEnumValueDescription_1 = s.schema.markdownEnumDescriptions[idx];
  6444. }
  6445. else if (s.schema.enumDescriptions) {
  6446. markdownEnumValueDescription_1 = toMarkdown(s.schema.enumDescriptions[idx]);
  6447. }
  6448. if (markdownEnumValueDescription_1) {
  6449. enumValue_1 = s.schema.enum[idx];
  6450. if (typeof enumValue_1 !== 'string') {
  6451. enumValue_1 = JSON.stringify(enumValue_1);
  6452. }
  6453. }
  6454. }
  6455. }
  6456. return true;
  6457. });
  6458. var result = '';
  6459. if (title_1) {
  6460. result = toMarkdown(title_1);
  6461. }
  6462. if (markdownDescription_1) {
  6463. if (result.length > 0) {
  6464. result += "\n\n";
  6465. }
  6466. result += markdownDescription_1;
  6467. }
  6468. if (markdownEnumValueDescription_1) {
  6469. if (result.length > 0) {
  6470. result += "\n\n";
  6471. }
  6472. result += "`" + toMarkdownCodeBlock(enumValue_1) + "`: " + markdownEnumValueDescription_1;
  6473. }
  6474. return createHover([result]);
  6475. }
  6476. return null;
  6477. });
  6478. };
  6479. return JSONHover;
  6480. }());
  6481. exports.JSONHover = JSONHover;
  6482. function toMarkdown(plain) {
  6483. if (plain) {
  6484. var res = plain.replace(/([^\n\r])(\r?\n)([^\n\r])/gm, '$1\n\n$3'); // single new lines to \n\n (Markdown paragraph)
  6485. return res.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&"); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
  6486. }
  6487. return undefined;
  6488. }
  6489. function toMarkdownCodeBlock(content) {
  6490. // see https://daringfireball.net/projects/markdown/syntax#precode
  6491. if (content.indexOf('`') !== -1) {
  6492. return '`` ' + content + ' ``';
  6493. }
  6494. return content;
  6495. }
  6496. });
  6497. !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)})()}));
  6498. //# sourceMappingURL=index.js.map;
  6499. define('vscode-uri', ['vscode-uri/index'], function (main) { return main; });
  6500. (function (factory) {
  6501. if (typeof module === "object" && typeof module.exports === "object") {
  6502. var v = factory(require, exports);
  6503. if (v !== undefined) module.exports = v;
  6504. }
  6505. else if (typeof define === "function" && define.amd) {
  6506. define('vscode-json-languageservice/utils/glob',["require", "exports"], factory);
  6507. }
  6508. })(function (require, exports) {
  6509. "use strict";
  6510. Object.defineProperty(exports, "__esModule", { value: true });
  6511. exports.createRegex = void 0;
  6512. /*---------------------------------------------------------------------------------------------
  6513. * Copyright (c) Microsoft Corporation. All rights reserved.
  6514. * Copyright (c) 2013, Nick Fitzgerald
  6515. * Licensed under the MIT License. See LICENCE.md in the project root for license information.
  6516. *--------------------------------------------------------------------------------------------*/
  6517. function createRegex(glob, opts) {
  6518. if (typeof glob !== 'string') {
  6519. throw new TypeError('Expected a string');
  6520. }
  6521. var str = String(glob);
  6522. // The regexp we are building, as a string.
  6523. var reStr = "";
  6524. // Whether we are matching so called "extended" globs (like bash) and should
  6525. // support single character matching, matching ranges of characters, group
  6526. // matching, etc.
  6527. var extended = opts ? !!opts.extended : false;
  6528. // When globstar is _false_ (default), '/foo/*' is translated a regexp like
  6529. // '^\/foo\/.*$' which will match any string beginning with '/foo/'
  6530. // When globstar is _true_, '/foo/*' is translated to regexp like
  6531. // '^\/foo\/[^/]*$' which will match any string beginning with '/foo/' BUT
  6532. // which does not have a '/' to the right of it.
  6533. // E.g. with '/foo/*' these will match: '/foo/bar', '/foo/bar.txt' but
  6534. // these will not '/foo/bar/baz', '/foo/bar/baz.txt'
  6535. // Lastely, when globstar is _true_, '/foo/**' is equivelant to '/foo/*' when
  6536. // globstar is _false_
  6537. var globstar = opts ? !!opts.globstar : false;
  6538. // If we are doing extended matching, this boolean is true when we are inside
  6539. // a group (eg {*.html,*.js}), and false otherwise.
  6540. var inGroup = false;
  6541. // RegExp flags (eg "i" ) to pass in to RegExp constructor.
  6542. var flags = opts && typeof (opts.flags) === "string" ? opts.flags : "";
  6543. var c;
  6544. for (var i = 0, len = str.length; i < len; i++) {
  6545. c = str[i];
  6546. switch (c) {
  6547. case "/":
  6548. case "$":
  6549. case "^":
  6550. case "+":
  6551. case ".":
  6552. case "(":
  6553. case ")":
  6554. case "=":
  6555. case "!":
  6556. case "|":
  6557. reStr += "\\" + c;
  6558. break;
  6559. case "?":
  6560. if (extended) {
  6561. reStr += ".";
  6562. break;
  6563. }
  6564. case "[":
  6565. case "]":
  6566. if (extended) {
  6567. reStr += c;
  6568. break;
  6569. }
  6570. case "{":
  6571. if (extended) {
  6572. inGroup = true;
  6573. reStr += "(";
  6574. break;
  6575. }
  6576. case "}":
  6577. if (extended) {
  6578. inGroup = false;
  6579. reStr += ")";
  6580. break;
  6581. }
  6582. case ",":
  6583. if (inGroup) {
  6584. reStr += "|";
  6585. break;
  6586. }
  6587. reStr += "\\" + c;
  6588. break;
  6589. case "*":
  6590. // Move over all consecutive "*"'s.
  6591. // Also store the previous and next characters
  6592. var prevChar = str[i - 1];
  6593. var starCount = 1;
  6594. while (str[i + 1] === "*") {
  6595. starCount++;
  6596. i++;
  6597. }
  6598. var nextChar = str[i + 1];
  6599. if (!globstar) {
  6600. // globstar is disabled, so treat any number of "*" as one
  6601. reStr += ".*";
  6602. }
  6603. else {
  6604. // globstar is enabled, so determine if this is a globstar segment
  6605. var isGlobstar = starCount > 1 // multiple "*"'s
  6606. && (prevChar === "/" || prevChar === undefined || prevChar === '{' || prevChar === ',') // from the start of the segment
  6607. && (nextChar === "/" || nextChar === undefined || nextChar === ',' || nextChar === '}'); // to the end of the segment
  6608. if (isGlobstar) {
  6609. if (nextChar === "/") {
  6610. i++; // move over the "/"
  6611. }
  6612. else if (prevChar === '/' && reStr.endsWith('\\/')) {
  6613. reStr = reStr.substr(0, reStr.length - 2);
  6614. }
  6615. // it's a globstar, so match zero or more path segments
  6616. reStr += "((?:[^/]*(?:\/|$))*)";
  6617. }
  6618. else {
  6619. // it's not a globstar, so only match one path segment
  6620. reStr += "([^/]*)";
  6621. }
  6622. }
  6623. break;
  6624. default:
  6625. reStr += c;
  6626. }
  6627. }
  6628. // When regexp 'g' flag is specified don't
  6629. // constrain the regular expression with ^ & $
  6630. if (!flags || !~flags.indexOf('g')) {
  6631. reStr = "^" + reStr + "$";
  6632. }
  6633. return new RegExp(reStr, flags);
  6634. }
  6635. exports.createRegex = createRegex;
  6636. ;
  6637. });
  6638. /*---------------------------------------------------------------------------------------------
  6639. * Copyright (c) Microsoft Corporation. All rights reserved.
  6640. * Licensed under the MIT License. See License.txt in the project root for license information.
  6641. *--------------------------------------------------------------------------------------------*/
  6642. (function (factory) {
  6643. if (typeof module === "object" && typeof module.exports === "object") {
  6644. var v = factory(require, exports);
  6645. if (v !== undefined) module.exports = v;
  6646. }
  6647. else if (typeof define === "function" && define.amd) {
  6648. define('vscode-json-languageservice/services/jsonSchemaService',["require", "exports", "jsonc-parser", "vscode-uri", "../utils/strings", "../parser/jsonParser", "vscode-nls", "../utils/glob"], factory);
  6649. }
  6650. })(function (require, exports) {
  6651. "use strict";
  6652. Object.defineProperty(exports, "__esModule", { value: true });
  6653. exports.JSONSchemaService = exports.ResolvedSchema = exports.UnresolvedSchema = void 0;
  6654. var Json = require("jsonc-parser");
  6655. var vscode_uri_1 = require("vscode-uri");
  6656. var Strings = require("../utils/strings");
  6657. var Parser = require("../parser/jsonParser");
  6658. var nls = require("vscode-nls");
  6659. var glob_1 = require("../utils/glob");
  6660. var localize = nls.loadMessageBundle();
  6661. var BANG = '!';
  6662. var PATH_SEP = '/';
  6663. var FilePatternAssociation = /** @class */ (function () {
  6664. function FilePatternAssociation(pattern, uris) {
  6665. this.globWrappers = [];
  6666. try {
  6667. for (var _i = 0, pattern_1 = pattern; _i < pattern_1.length; _i++) {
  6668. var patternString = pattern_1[_i];
  6669. var include = patternString[0] !== BANG;
  6670. if (!include) {
  6671. patternString = patternString.substring(1);
  6672. }
  6673. if (patternString.length > 0) {
  6674. if (patternString[0] === PATH_SEP) {
  6675. patternString = patternString.substring(1);
  6676. }
  6677. this.globWrappers.push({
  6678. regexp: glob_1.createRegex('**/' + patternString, { extended: true, globstar: true }),
  6679. include: include,
  6680. });
  6681. }
  6682. }
  6683. ;
  6684. this.uris = uris;
  6685. }
  6686. catch (e) {
  6687. this.globWrappers.length = 0;
  6688. this.uris = [];
  6689. }
  6690. }
  6691. FilePatternAssociation.prototype.matchesPattern = function (fileName) {
  6692. var match = false;
  6693. for (var _i = 0, _a = this.globWrappers; _i < _a.length; _i++) {
  6694. var _b = _a[_i], regexp = _b.regexp, include = _b.include;
  6695. if (regexp.test(fileName)) {
  6696. match = include;
  6697. }
  6698. }
  6699. return match;
  6700. };
  6701. FilePatternAssociation.prototype.getURIs = function () {
  6702. return this.uris;
  6703. };
  6704. return FilePatternAssociation;
  6705. }());
  6706. var SchemaHandle = /** @class */ (function () {
  6707. function SchemaHandle(service, url, unresolvedSchemaContent) {
  6708. this.service = service;
  6709. this.url = url;
  6710. this.dependencies = {};
  6711. if (unresolvedSchemaContent) {
  6712. this.unresolvedSchema = this.service.promise.resolve(new UnresolvedSchema(unresolvedSchemaContent));
  6713. }
  6714. }
  6715. SchemaHandle.prototype.getUnresolvedSchema = function () {
  6716. if (!this.unresolvedSchema) {
  6717. this.unresolvedSchema = this.service.loadSchema(this.url);
  6718. }
  6719. return this.unresolvedSchema;
  6720. };
  6721. SchemaHandle.prototype.getResolvedSchema = function () {
  6722. var _this = this;
  6723. if (!this.resolvedSchema) {
  6724. this.resolvedSchema = this.getUnresolvedSchema().then(function (unresolved) {
  6725. return _this.service.resolveSchemaContent(unresolved, _this.url, _this.dependencies);
  6726. });
  6727. }
  6728. return this.resolvedSchema;
  6729. };
  6730. SchemaHandle.prototype.clearSchema = function () {
  6731. this.resolvedSchema = undefined;
  6732. this.unresolvedSchema = undefined;
  6733. this.dependencies = {};
  6734. };
  6735. return SchemaHandle;
  6736. }());
  6737. var UnresolvedSchema = /** @class */ (function () {
  6738. function UnresolvedSchema(schema, errors) {
  6739. if (errors === void 0) { errors = []; }
  6740. this.schema = schema;
  6741. this.errors = errors;
  6742. }
  6743. return UnresolvedSchema;
  6744. }());
  6745. exports.UnresolvedSchema = UnresolvedSchema;
  6746. var ResolvedSchema = /** @class */ (function () {
  6747. function ResolvedSchema(schema, errors) {
  6748. if (errors === void 0) { errors = []; }
  6749. this.schema = schema;
  6750. this.errors = errors;
  6751. }
  6752. ResolvedSchema.prototype.getSection = function (path) {
  6753. var schemaRef = this.getSectionRecursive(path, this.schema);
  6754. if (schemaRef) {
  6755. return Parser.asSchema(schemaRef);
  6756. }
  6757. return undefined;
  6758. };
  6759. ResolvedSchema.prototype.getSectionRecursive = function (path, schema) {
  6760. if (!schema || typeof schema === 'boolean' || path.length === 0) {
  6761. return schema;
  6762. }
  6763. var next = path.shift();
  6764. if (schema.properties && typeof schema.properties[next]) {
  6765. return this.getSectionRecursive(path, schema.properties[next]);
  6766. }
  6767. else if (schema.patternProperties) {
  6768. for (var _i = 0, _a = Object.keys(schema.patternProperties); _i < _a.length; _i++) {
  6769. var pattern = _a[_i];
  6770. var regex = Strings.extendedRegExp(pattern);
  6771. if (regex.test(next)) {
  6772. return this.getSectionRecursive(path, schema.patternProperties[pattern]);
  6773. }
  6774. }
  6775. }
  6776. else if (typeof schema.additionalProperties === 'object') {
  6777. return this.getSectionRecursive(path, schema.additionalProperties);
  6778. }
  6779. else if (next.match('[0-9]+')) {
  6780. if (Array.isArray(schema.items)) {
  6781. var index = parseInt(next, 10);
  6782. if (!isNaN(index) && schema.items[index]) {
  6783. return this.getSectionRecursive(path, schema.items[index]);
  6784. }
  6785. }
  6786. else if (schema.items) {
  6787. return this.getSectionRecursive(path, schema.items);
  6788. }
  6789. }
  6790. return undefined;
  6791. };
  6792. return ResolvedSchema;
  6793. }());
  6794. exports.ResolvedSchema = ResolvedSchema;
  6795. var JSONSchemaService = /** @class */ (function () {
  6796. function JSONSchemaService(requestService, contextService, promiseConstructor) {
  6797. this.contextService = contextService;
  6798. this.requestService = requestService;
  6799. this.promiseConstructor = promiseConstructor || Promise;
  6800. this.callOnDispose = [];
  6801. this.contributionSchemas = {};
  6802. this.contributionAssociations = [];
  6803. this.schemasById = {};
  6804. this.filePatternAssociations = [];
  6805. this.registeredSchemasIds = {};
  6806. }
  6807. JSONSchemaService.prototype.getRegisteredSchemaIds = function (filter) {
  6808. return Object.keys(this.registeredSchemasIds).filter(function (id) {
  6809. var scheme = vscode_uri_1.URI.parse(id).scheme;
  6810. return scheme !== 'schemaservice' && (!filter || filter(scheme));
  6811. });
  6812. };
  6813. Object.defineProperty(JSONSchemaService.prototype, "promise", {
  6814. get: function () {
  6815. return this.promiseConstructor;
  6816. },
  6817. enumerable: false,
  6818. configurable: true
  6819. });
  6820. JSONSchemaService.prototype.dispose = function () {
  6821. while (this.callOnDispose.length > 0) {
  6822. this.callOnDispose.pop()();
  6823. }
  6824. };
  6825. JSONSchemaService.prototype.onResourceChange = function (uri) {
  6826. var _this = this;
  6827. var hasChanges = false;
  6828. uri = normalizeId(uri);
  6829. var toWalk = [uri];
  6830. var all = Object.keys(this.schemasById).map(function (key) { return _this.schemasById[key]; });
  6831. while (toWalk.length) {
  6832. var curr = toWalk.pop();
  6833. for (var i = 0; i < all.length; i++) {
  6834. var handle = all[i];
  6835. if (handle && (handle.url === curr || handle.dependencies[curr])) {
  6836. if (handle.url !== curr) {
  6837. toWalk.push(handle.url);
  6838. }
  6839. handle.clearSchema();
  6840. all[i] = undefined;
  6841. hasChanges = true;
  6842. }
  6843. }
  6844. }
  6845. return hasChanges;
  6846. };
  6847. JSONSchemaService.prototype.setSchemaContributions = function (schemaContributions) {
  6848. if (schemaContributions.schemas) {
  6849. var schemas = schemaContributions.schemas;
  6850. for (var id in schemas) {
  6851. var normalizedId = normalizeId(id);
  6852. this.contributionSchemas[normalizedId] = this.addSchemaHandle(normalizedId, schemas[id]);
  6853. }
  6854. }
  6855. if (Array.isArray(schemaContributions.schemaAssociations)) {
  6856. var schemaAssociations = schemaContributions.schemaAssociations;
  6857. for (var _i = 0, schemaAssociations_1 = schemaAssociations; _i < schemaAssociations_1.length; _i++) {
  6858. var schemaAssociation = schemaAssociations_1[_i];
  6859. var uris = schemaAssociation.uris.map(normalizeId);
  6860. var association = this.addFilePatternAssociation(schemaAssociation.pattern, uris);
  6861. this.contributionAssociations.push(association);
  6862. }
  6863. }
  6864. };
  6865. JSONSchemaService.prototype.addSchemaHandle = function (id, unresolvedSchemaContent) {
  6866. var schemaHandle = new SchemaHandle(this, id, unresolvedSchemaContent);
  6867. this.schemasById[id] = schemaHandle;
  6868. return schemaHandle;
  6869. };
  6870. JSONSchemaService.prototype.getOrAddSchemaHandle = function (id, unresolvedSchemaContent) {
  6871. return this.schemasById[id] || this.addSchemaHandle(id, unresolvedSchemaContent);
  6872. };
  6873. JSONSchemaService.prototype.addFilePatternAssociation = function (pattern, uris) {
  6874. var fpa = new FilePatternAssociation(pattern, uris);
  6875. this.filePatternAssociations.push(fpa);
  6876. return fpa;
  6877. };
  6878. JSONSchemaService.prototype.registerExternalSchema = function (uri, filePatterns, unresolvedSchemaContent) {
  6879. var id = normalizeId(uri);
  6880. this.registeredSchemasIds[id] = true;
  6881. this.cachedSchemaForResource = undefined;
  6882. if (filePatterns) {
  6883. this.addFilePatternAssociation(filePatterns, [uri]);
  6884. }
  6885. return unresolvedSchemaContent ? this.addSchemaHandle(id, unresolvedSchemaContent) : this.getOrAddSchemaHandle(id);
  6886. };
  6887. JSONSchemaService.prototype.clearExternalSchemas = function () {
  6888. this.schemasById = {};
  6889. this.filePatternAssociations = [];
  6890. this.registeredSchemasIds = {};
  6891. this.cachedSchemaForResource = undefined;
  6892. for (var id in this.contributionSchemas) {
  6893. this.schemasById[id] = this.contributionSchemas[id];
  6894. this.registeredSchemasIds[id] = true;
  6895. }
  6896. for (var _i = 0, _a = this.contributionAssociations; _i < _a.length; _i++) {
  6897. var contributionAssociation = _a[_i];
  6898. this.filePatternAssociations.push(contributionAssociation);
  6899. }
  6900. };
  6901. JSONSchemaService.prototype.getResolvedSchema = function (schemaId) {
  6902. var id = normalizeId(schemaId);
  6903. var schemaHandle = this.schemasById[id];
  6904. if (schemaHandle) {
  6905. return schemaHandle.getResolvedSchema();
  6906. }
  6907. return this.promise.resolve(undefined);
  6908. };
  6909. JSONSchemaService.prototype.loadSchema = function (url) {
  6910. if (!this.requestService) {
  6911. var errorMessage = localize('json.schema.norequestservice', 'Unable to load schema from \'{0}\'. No schema request service available', toDisplayString(url));
  6912. return this.promise.resolve(new UnresolvedSchema({}, [errorMessage]));
  6913. }
  6914. return this.requestService(url).then(function (content) {
  6915. if (!content) {
  6916. var errorMessage = localize('json.schema.nocontent', 'Unable to load schema from \'{0}\': No content.', toDisplayString(url));
  6917. return new UnresolvedSchema({}, [errorMessage]);
  6918. }
  6919. var schemaContent = {};
  6920. var jsonErrors = [];
  6921. schemaContent = Json.parse(content, jsonErrors);
  6922. var errors = jsonErrors.length ? [localize('json.schema.invalidFormat', 'Unable to parse content from \'{0}\': Parse error at offset {1}.', toDisplayString(url), jsonErrors[0].offset)] : [];
  6923. return new UnresolvedSchema(schemaContent, errors);
  6924. }, function (error) {
  6925. var errorMessage = error.toString();
  6926. var errorSplit = error.toString().split('Error: ');
  6927. if (errorSplit.length > 1) {
  6928. // more concise error message, URL and context are attached by caller anyways
  6929. errorMessage = errorSplit[1];
  6930. }
  6931. if (Strings.endsWith(errorMessage, '.')) {
  6932. errorMessage = errorMessage.substr(0, errorMessage.length - 1);
  6933. }
  6934. return new UnresolvedSchema({}, [localize('json.schema.nocontent', 'Unable to load schema from \'{0}\': {1}.', toDisplayString(url), errorMessage)]);
  6935. });
  6936. };
  6937. JSONSchemaService.prototype.resolveSchemaContent = function (schemaToResolve, schemaURL, dependencies) {
  6938. var _this = this;
  6939. var resolveErrors = schemaToResolve.errors.slice(0);
  6940. var schema = schemaToResolve.schema;
  6941. if (schema.$schema) {
  6942. var id = normalizeId(schema.$schema);
  6943. if (id === 'http://json-schema.org/draft-03/schema') {
  6944. return this.promise.resolve(new ResolvedSchema({}, [localize('json.schema.draft03.notsupported', "Draft-03 schemas are not supported.")]));
  6945. }
  6946. else if (id === 'https://json-schema.org/draft/2019-09/schema') {
  6947. resolveErrors.push(localize('json.schema.draft201909.notsupported', "Draft 2019-09 schemas are not yet fully supported."));
  6948. }
  6949. }
  6950. var contextService = this.contextService;
  6951. var findSection = function (schema, path) {
  6952. if (!path) {
  6953. return schema;
  6954. }
  6955. var current = schema;
  6956. if (path[0] === '/') {
  6957. path = path.substr(1);
  6958. }
  6959. path.split('/').some(function (part) {
  6960. part = part.replace(/~1/g, '/').replace(/~0/g, '~');
  6961. current = current[part];
  6962. return !current;
  6963. });
  6964. return current;
  6965. };
  6966. var merge = function (target, sourceRoot, sourceURI, refSegment) {
  6967. var path = refSegment ? decodeURIComponent(refSegment) : undefined;
  6968. var section = findSection(sourceRoot, path);
  6969. if (section) {
  6970. for (var key in section) {
  6971. if (section.hasOwnProperty(key) && !target.hasOwnProperty(key)) {
  6972. target[key] = section[key];
  6973. }
  6974. }
  6975. }
  6976. else {
  6977. resolveErrors.push(localize('json.schema.invalidref', '$ref \'{0}\' in \'{1}\' can not be resolved.', path, sourceURI));
  6978. }
  6979. };
  6980. var resolveExternalLink = function (node, uri, refSegment, parentSchemaURL, parentSchemaDependencies) {
  6981. if (contextService && !/^[A-Za-z][A-Za-z0-9+\-.+]*:\/\/.*/.test(uri)) {
  6982. uri = contextService.resolveRelativePath(uri, parentSchemaURL);
  6983. }
  6984. uri = normalizeId(uri);
  6985. var referencedHandle = _this.getOrAddSchemaHandle(uri);
  6986. return referencedHandle.getUnresolvedSchema().then(function (unresolvedSchema) {
  6987. parentSchemaDependencies[uri] = true;
  6988. if (unresolvedSchema.errors.length) {
  6989. var loc = refSegment ? uri + '#' + refSegment : uri;
  6990. resolveErrors.push(localize('json.schema.problemloadingref', 'Problems loading reference \'{0}\': {1}', loc, unresolvedSchema.errors[0]));
  6991. }
  6992. merge(node, unresolvedSchema.schema, uri, refSegment);
  6993. return resolveRefs(node, unresolvedSchema.schema, uri, referencedHandle.dependencies);
  6994. });
  6995. };
  6996. var resolveRefs = function (node, parentSchema, parentSchemaURL, parentSchemaDependencies) {
  6997. if (!node || typeof node !== 'object') {
  6998. return Promise.resolve(null);
  6999. }
  7000. var toWalk = [node];
  7001. var seen = [];
  7002. var openPromises = [];
  7003. var collectEntries = function () {
  7004. var entries = [];
  7005. for (var _i = 0; _i < arguments.length; _i++) {
  7006. entries[_i] = arguments[_i];
  7007. }
  7008. for (var _a = 0, entries_1 = entries; _a < entries_1.length; _a++) {
  7009. var entry = entries_1[_a];
  7010. if (typeof entry === 'object') {
  7011. toWalk.push(entry);
  7012. }
  7013. }
  7014. };
  7015. var collectMapEntries = function () {
  7016. var maps = [];
  7017. for (var _i = 0; _i < arguments.length; _i++) {
  7018. maps[_i] = arguments[_i];
  7019. }
  7020. for (var _a = 0, maps_1 = maps; _a < maps_1.length; _a++) {
  7021. var map = maps_1[_a];
  7022. if (typeof map === 'object') {
  7023. for (var k in map) {
  7024. var key = k;
  7025. var entry = map[key];
  7026. if (typeof entry === 'object') {
  7027. toWalk.push(entry);
  7028. }
  7029. }
  7030. }
  7031. }
  7032. };
  7033. var collectArrayEntries = function () {
  7034. var arrays = [];
  7035. for (var _i = 0; _i < arguments.length; _i++) {
  7036. arrays[_i] = arguments[_i];
  7037. }
  7038. for (var _a = 0, arrays_1 = arrays; _a < arrays_1.length; _a++) {
  7039. var array = arrays_1[_a];
  7040. if (Array.isArray(array)) {
  7041. for (var _b = 0, array_1 = array; _b < array_1.length; _b++) {
  7042. var entry = array_1[_b];
  7043. if (typeof entry === 'object') {
  7044. toWalk.push(entry);
  7045. }
  7046. }
  7047. }
  7048. }
  7049. };
  7050. var handleRef = function (next) {
  7051. var seenRefs = [];
  7052. while (next.$ref) {
  7053. var ref = next.$ref;
  7054. var segments = ref.split('#', 2);
  7055. delete next.$ref;
  7056. if (segments[0].length > 0) {
  7057. openPromises.push(resolveExternalLink(next, segments[0], segments[1], parentSchemaURL, parentSchemaDependencies));
  7058. return;
  7059. }
  7060. else {
  7061. if (seenRefs.indexOf(ref) === -1) {
  7062. merge(next, parentSchema, parentSchemaURL, segments[1]); // can set next.$ref again, use seenRefs to avoid circle
  7063. seenRefs.push(ref);
  7064. }
  7065. }
  7066. }
  7067. collectEntries(next.items, next.additionalItems, next.additionalProperties, next.not, next.contains, next.propertyNames, next.if, next.then, next.else);
  7068. collectMapEntries(next.definitions, next.properties, next.patternProperties, next.dependencies);
  7069. collectArrayEntries(next.anyOf, next.allOf, next.oneOf, next.items);
  7070. };
  7071. while (toWalk.length) {
  7072. var next = toWalk.pop();
  7073. if (seen.indexOf(next) >= 0) {
  7074. continue;
  7075. }
  7076. seen.push(next);
  7077. handleRef(next);
  7078. }
  7079. return _this.promise.all(openPromises);
  7080. };
  7081. return resolveRefs(schema, schema, schemaURL, dependencies).then(function (_) { return new ResolvedSchema(schema, resolveErrors); });
  7082. };
  7083. JSONSchemaService.prototype.getSchemaForResource = function (resource, document) {
  7084. // first use $schema if present
  7085. if (document && document.root && document.root.type === 'object') {
  7086. var schemaProperties = document.root.properties.filter(function (p) { return (p.keyNode.value === '$schema') && p.valueNode && p.valueNode.type === 'string'; });
  7087. if (schemaProperties.length > 0) {
  7088. var valueNode = schemaProperties[0].valueNode;
  7089. if (valueNode && valueNode.type === 'string') {
  7090. var schemeId = Parser.getNodeValue(valueNode);
  7091. if (schemeId && Strings.startsWith(schemeId, '.') && this.contextService) {
  7092. schemeId = this.contextService.resolveRelativePath(schemeId, resource);
  7093. }
  7094. if (schemeId) {
  7095. var id = normalizeId(schemeId);
  7096. return this.getOrAddSchemaHandle(id).getResolvedSchema();
  7097. }
  7098. }
  7099. }
  7100. }
  7101. if (this.cachedSchemaForResource && this.cachedSchemaForResource.resource === resource) {
  7102. return this.cachedSchemaForResource.resolvedSchema;
  7103. }
  7104. var seen = Object.create(null);
  7105. var schemas = [];
  7106. var normalizedResource = normalizeResourceForMatching(resource);
  7107. for (var _i = 0, _a = this.filePatternAssociations; _i < _a.length; _i++) {
  7108. var entry = _a[_i];
  7109. if (entry.matchesPattern(normalizedResource)) {
  7110. for (var _b = 0, _c = entry.getURIs(); _b < _c.length; _b++) {
  7111. var schemaId = _c[_b];
  7112. if (!seen[schemaId]) {
  7113. schemas.push(schemaId);
  7114. seen[schemaId] = true;
  7115. }
  7116. }
  7117. }
  7118. }
  7119. var resolvedSchema = schemas.length > 0 ? this.createCombinedSchema(resource, schemas).getResolvedSchema() : this.promise.resolve(undefined);
  7120. this.cachedSchemaForResource = { resource: resource, resolvedSchema: resolvedSchema };
  7121. return resolvedSchema;
  7122. };
  7123. JSONSchemaService.prototype.createCombinedSchema = function (resource, schemaIds) {
  7124. if (schemaIds.length === 1) {
  7125. return this.getOrAddSchemaHandle(schemaIds[0]);
  7126. }
  7127. else {
  7128. var combinedSchemaId = 'schemaservice://combinedSchema/' + encodeURIComponent(resource);
  7129. var combinedSchema = {
  7130. allOf: schemaIds.map(function (schemaId) { return ({ $ref: schemaId }); })
  7131. };
  7132. return this.addSchemaHandle(combinedSchemaId, combinedSchema);
  7133. }
  7134. };
  7135. JSONSchemaService.prototype.getMatchingSchemas = function (document, jsonDocument, schema) {
  7136. if (schema) {
  7137. var id = schema.id || ('schemaservice://untitled/matchingSchemas/' + idCounter++);
  7138. return this.resolveSchemaContent(new UnresolvedSchema(schema), id, {}).then(function (resolvedSchema) {
  7139. return jsonDocument.getMatchingSchemas(resolvedSchema.schema).filter(function (s) { return !s.inverted; });
  7140. });
  7141. }
  7142. return this.getSchemaForResource(document.uri, jsonDocument).then(function (schema) {
  7143. if (schema) {
  7144. return jsonDocument.getMatchingSchemas(schema.schema).filter(function (s) { return !s.inverted; });
  7145. }
  7146. return [];
  7147. });
  7148. };
  7149. return JSONSchemaService;
  7150. }());
  7151. exports.JSONSchemaService = JSONSchemaService;
  7152. var idCounter = 0;
  7153. function normalizeId(id) {
  7154. // remove trailing '#', normalize drive capitalization
  7155. try {
  7156. return vscode_uri_1.URI.parse(id).toString();
  7157. }
  7158. catch (e) {
  7159. return id;
  7160. }
  7161. }
  7162. function normalizeResourceForMatching(resource) {
  7163. // remove queries and fragments, normalize drive capitalization
  7164. try {
  7165. return vscode_uri_1.URI.parse(resource).with({ fragment: null, query: null }).toString();
  7166. }
  7167. catch (e) {
  7168. return resource;
  7169. }
  7170. }
  7171. function toDisplayString(url) {
  7172. try {
  7173. var uri = vscode_uri_1.URI.parse(url);
  7174. if (uri.scheme === 'file') {
  7175. return uri.fsPath;
  7176. }
  7177. }
  7178. catch (e) {
  7179. // ignore
  7180. }
  7181. return url;
  7182. }
  7183. });
  7184. /*---------------------------------------------------------------------------------------------
  7185. * Copyright (c) Microsoft Corporation. All rights reserved.
  7186. * Licensed under the MIT License. See License.txt in the project root for license information.
  7187. *--------------------------------------------------------------------------------------------*/
  7188. (function (factory) {
  7189. if (typeof module === "object" && typeof module.exports === "object") {
  7190. var v = factory(require, exports);
  7191. if (v !== undefined) module.exports = v;
  7192. }
  7193. else if (typeof define === "function" && define.amd) {
  7194. define('vscode-json-languageservice/services/jsonValidation',["require", "exports", "./jsonSchemaService", "../jsonLanguageTypes", "vscode-nls", "../utils/objects"], factory);
  7195. }
  7196. })(function (require, exports) {
  7197. "use strict";
  7198. Object.defineProperty(exports, "__esModule", { value: true });
  7199. exports.JSONValidation = void 0;
  7200. var jsonSchemaService_1 = require("./jsonSchemaService");
  7201. var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
  7202. var nls = require("vscode-nls");
  7203. var objects_1 = require("../utils/objects");
  7204. var localize = nls.loadMessageBundle();
  7205. var JSONValidation = /** @class */ (function () {
  7206. function JSONValidation(jsonSchemaService, promiseConstructor) {
  7207. this.jsonSchemaService = jsonSchemaService;
  7208. this.promise = promiseConstructor;
  7209. this.validationEnabled = true;
  7210. }
  7211. JSONValidation.prototype.configure = function (raw) {
  7212. if (raw) {
  7213. this.validationEnabled = raw.validate !== false;
  7214. this.commentSeverity = raw.allowComments ? undefined : jsonLanguageTypes_1.DiagnosticSeverity.Error;
  7215. }
  7216. };
  7217. JSONValidation.prototype.doValidation = function (textDocument, jsonDocument, documentSettings, schema) {
  7218. var _this = this;
  7219. if (!this.validationEnabled) {
  7220. return this.promise.resolve([]);
  7221. }
  7222. var diagnostics = [];
  7223. var added = {};
  7224. var addProblem = function (problem) {
  7225. // remove duplicated messages
  7226. var signature = problem.range.start.line + ' ' + problem.range.start.character + ' ' + problem.message;
  7227. if (!added[signature]) {
  7228. added[signature] = true;
  7229. diagnostics.push(problem);
  7230. }
  7231. };
  7232. var getDiagnostics = function (schema) {
  7233. var trailingCommaSeverity = (documentSettings === null || documentSettings === void 0 ? void 0 : documentSettings.trailingCommas) ? toDiagnosticSeverity(documentSettings.trailingCommas) : jsonLanguageTypes_1.DiagnosticSeverity.Error;
  7234. var commentSeverity = (documentSettings === null || documentSettings === void 0 ? void 0 : documentSettings.comments) ? toDiagnosticSeverity(documentSettings.comments) : _this.commentSeverity;
  7235. var schemaValidation = (documentSettings === null || documentSettings === void 0 ? void 0 : documentSettings.schemaValidation) ? toDiagnosticSeverity(documentSettings.schemaValidation) : jsonLanguageTypes_1.DiagnosticSeverity.Warning;
  7236. var schemaRequest = (documentSettings === null || documentSettings === void 0 ? void 0 : documentSettings.schemaRequest) ? toDiagnosticSeverity(documentSettings.schemaRequest) : jsonLanguageTypes_1.DiagnosticSeverity.Warning;
  7237. if (schema) {
  7238. if (schema.errors.length && jsonDocument.root && schemaRequest) {
  7239. var astRoot = jsonDocument.root;
  7240. var property = astRoot.type === 'object' ? astRoot.properties[0] : undefined;
  7241. if (property && property.keyNode.value === '$schema') {
  7242. var node = property.valueNode || property;
  7243. var range = jsonLanguageTypes_1.Range.create(textDocument.positionAt(node.offset), textDocument.positionAt(node.offset + node.length));
  7244. addProblem(jsonLanguageTypes_1.Diagnostic.create(range, schema.errors[0], schemaRequest, jsonLanguageTypes_1.ErrorCode.SchemaResolveError));
  7245. }
  7246. else {
  7247. var range = jsonLanguageTypes_1.Range.create(textDocument.positionAt(astRoot.offset), textDocument.positionAt(astRoot.offset + 1));
  7248. addProblem(jsonLanguageTypes_1.Diagnostic.create(range, schema.errors[0], schemaRequest, jsonLanguageTypes_1.ErrorCode.SchemaResolveError));
  7249. }
  7250. }
  7251. else if (schemaValidation) {
  7252. var semanticErrors = jsonDocument.validate(textDocument, schema.schema, schemaValidation);
  7253. if (semanticErrors) {
  7254. semanticErrors.forEach(addProblem);
  7255. }
  7256. }
  7257. if (schemaAllowsComments(schema.schema)) {
  7258. commentSeverity = undefined;
  7259. }
  7260. if (schemaAllowsTrailingCommas(schema.schema)) {
  7261. trailingCommaSeverity = undefined;
  7262. }
  7263. }
  7264. for (var _i = 0, _a = jsonDocument.syntaxErrors; _i < _a.length; _i++) {
  7265. var p = _a[_i];
  7266. if (p.code === jsonLanguageTypes_1.ErrorCode.TrailingComma) {
  7267. if (typeof trailingCommaSeverity !== 'number') {
  7268. continue;
  7269. }
  7270. p.severity = trailingCommaSeverity;
  7271. }
  7272. addProblem(p);
  7273. }
  7274. if (typeof commentSeverity === 'number') {
  7275. var message_1 = localize('InvalidCommentToken', 'Comments are not permitted in JSON.');
  7276. jsonDocument.comments.forEach(function (c) {
  7277. addProblem(jsonLanguageTypes_1.Diagnostic.create(c, message_1, commentSeverity, jsonLanguageTypes_1.ErrorCode.CommentNotPermitted));
  7278. });
  7279. }
  7280. return diagnostics;
  7281. };
  7282. if (schema) {
  7283. var id = schema.id || ('schemaservice://untitled/' + idCounter++);
  7284. return this.jsonSchemaService.resolveSchemaContent(new jsonSchemaService_1.UnresolvedSchema(schema), id, {}).then(function (resolvedSchema) {
  7285. return getDiagnostics(resolvedSchema);
  7286. });
  7287. }
  7288. return this.jsonSchemaService.getSchemaForResource(textDocument.uri, jsonDocument).then(function (schema) {
  7289. return getDiagnostics(schema);
  7290. });
  7291. };
  7292. return JSONValidation;
  7293. }());
  7294. exports.JSONValidation = JSONValidation;
  7295. var idCounter = 0;
  7296. function schemaAllowsComments(schemaRef) {
  7297. if (schemaRef && typeof schemaRef === 'object') {
  7298. if (objects_1.isBoolean(schemaRef.allowComments)) {
  7299. return schemaRef.allowComments;
  7300. }
  7301. if (schemaRef.allOf) {
  7302. for (var _i = 0, _a = schemaRef.allOf; _i < _a.length; _i++) {
  7303. var schema = _a[_i];
  7304. var allow = schemaAllowsComments(schema);
  7305. if (objects_1.isBoolean(allow)) {
  7306. return allow;
  7307. }
  7308. }
  7309. }
  7310. }
  7311. return undefined;
  7312. }
  7313. function schemaAllowsTrailingCommas(schemaRef) {
  7314. if (schemaRef && typeof schemaRef === 'object') {
  7315. if (objects_1.isBoolean(schemaRef.allowTrailingCommas)) {
  7316. return schemaRef.allowTrailingCommas;
  7317. }
  7318. var deprSchemaRef = schemaRef;
  7319. if (objects_1.isBoolean(deprSchemaRef['allowsTrailingCommas'])) { // deprecated
  7320. return deprSchemaRef['allowsTrailingCommas'];
  7321. }
  7322. if (schemaRef.allOf) {
  7323. for (var _i = 0, _a = schemaRef.allOf; _i < _a.length; _i++) {
  7324. var schema = _a[_i];
  7325. var allow = schemaAllowsTrailingCommas(schema);
  7326. if (objects_1.isBoolean(allow)) {
  7327. return allow;
  7328. }
  7329. }
  7330. }
  7331. }
  7332. return undefined;
  7333. }
  7334. function toDiagnosticSeverity(severityLevel) {
  7335. switch (severityLevel) {
  7336. case 'error': return jsonLanguageTypes_1.DiagnosticSeverity.Error;
  7337. case 'warning': return jsonLanguageTypes_1.DiagnosticSeverity.Warning;
  7338. case 'ignore': return undefined;
  7339. }
  7340. return undefined;
  7341. }
  7342. });
  7343. /*---------------------------------------------------------------------------------------------
  7344. * Copyright (c) Microsoft Corporation. All rights reserved.
  7345. * Licensed under the MIT License. See License.txt in the project root for license information.
  7346. *--------------------------------------------------------------------------------------------*/
  7347. (function (factory) {
  7348. if (typeof module === "object" && typeof module.exports === "object") {
  7349. var v = factory(require, exports);
  7350. if (v !== undefined) module.exports = v;
  7351. }
  7352. else if (typeof define === "function" && define.amd) {
  7353. define('vscode-json-languageservice/utils/colors',["require", "exports"], factory);
  7354. }
  7355. })(function (require, exports) {
  7356. "use strict";
  7357. Object.defineProperty(exports, "__esModule", { value: true });
  7358. exports.colorFrom256RGB = exports.colorFromHex = exports.hexDigit = void 0;
  7359. var Digit0 = 48;
  7360. var Digit9 = 57;
  7361. var A = 65;
  7362. var a = 97;
  7363. var f = 102;
  7364. function hexDigit(charCode) {
  7365. if (charCode < Digit0) {
  7366. return 0;
  7367. }
  7368. if (charCode <= Digit9) {
  7369. return charCode - Digit0;
  7370. }
  7371. if (charCode < a) {
  7372. charCode += (a - A);
  7373. }
  7374. if (charCode >= a && charCode <= f) {
  7375. return charCode - a + 10;
  7376. }
  7377. return 0;
  7378. }
  7379. exports.hexDigit = hexDigit;
  7380. function colorFromHex(text) {
  7381. if (text[0] !== '#') {
  7382. return undefined;
  7383. }
  7384. switch (text.length) {
  7385. case 4:
  7386. return {
  7387. red: (hexDigit(text.charCodeAt(1)) * 0x11) / 255.0,
  7388. green: (hexDigit(text.charCodeAt(2)) * 0x11) / 255.0,
  7389. blue: (hexDigit(text.charCodeAt(3)) * 0x11) / 255.0,
  7390. alpha: 1
  7391. };
  7392. case 5:
  7393. return {
  7394. red: (hexDigit(text.charCodeAt(1)) * 0x11) / 255.0,
  7395. green: (hexDigit(text.charCodeAt(2)) * 0x11) / 255.0,
  7396. blue: (hexDigit(text.charCodeAt(3)) * 0x11) / 255.0,
  7397. alpha: (hexDigit(text.charCodeAt(4)) * 0x11) / 255.0,
  7398. };
  7399. case 7:
  7400. return {
  7401. red: (hexDigit(text.charCodeAt(1)) * 0x10 + hexDigit(text.charCodeAt(2))) / 255.0,
  7402. green: (hexDigit(text.charCodeAt(3)) * 0x10 + hexDigit(text.charCodeAt(4))) / 255.0,
  7403. blue: (hexDigit(text.charCodeAt(5)) * 0x10 + hexDigit(text.charCodeAt(6))) / 255.0,
  7404. alpha: 1
  7405. };
  7406. case 9:
  7407. return {
  7408. red: (hexDigit(text.charCodeAt(1)) * 0x10 + hexDigit(text.charCodeAt(2))) / 255.0,
  7409. green: (hexDigit(text.charCodeAt(3)) * 0x10 + hexDigit(text.charCodeAt(4))) / 255.0,
  7410. blue: (hexDigit(text.charCodeAt(5)) * 0x10 + hexDigit(text.charCodeAt(6))) / 255.0,
  7411. alpha: (hexDigit(text.charCodeAt(7)) * 0x10 + hexDigit(text.charCodeAt(8))) / 255.0
  7412. };
  7413. }
  7414. return undefined;
  7415. }
  7416. exports.colorFromHex = colorFromHex;
  7417. function colorFrom256RGB(red, green, blue, alpha) {
  7418. if (alpha === void 0) { alpha = 1.0; }
  7419. return {
  7420. red: red / 255.0,
  7421. green: green / 255.0,
  7422. blue: blue / 255.0,
  7423. alpha: alpha
  7424. };
  7425. }
  7426. exports.colorFrom256RGB = colorFrom256RGB;
  7427. });
  7428. /*---------------------------------------------------------------------------------------------
  7429. * Copyright (c) Microsoft Corporation. All rights reserved.
  7430. * Licensed under the MIT License. See License.txt in the project root for license information.
  7431. *--------------------------------------------------------------------------------------------*/
  7432. (function (factory) {
  7433. if (typeof module === "object" && typeof module.exports === "object") {
  7434. var v = factory(require, exports);
  7435. if (v !== undefined) module.exports = v;
  7436. }
  7437. else if (typeof define === "function" && define.amd) {
  7438. define('vscode-json-languageservice/services/jsonDocumentSymbols',["require", "exports", "../parser/jsonParser", "../utils/strings", "../utils/colors", "../jsonLanguageTypes"], factory);
  7439. }
  7440. })(function (require, exports) {
  7441. "use strict";
  7442. Object.defineProperty(exports, "__esModule", { value: true });
  7443. exports.JSONDocumentSymbols = void 0;
  7444. var Parser = require("../parser/jsonParser");
  7445. var Strings = require("../utils/strings");
  7446. var colors_1 = require("../utils/colors");
  7447. var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
  7448. var JSONDocumentSymbols = /** @class */ (function () {
  7449. function JSONDocumentSymbols(schemaService) {
  7450. this.schemaService = schemaService;
  7451. }
  7452. JSONDocumentSymbols.prototype.findDocumentSymbols = 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_1 = [];
  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 location = jsonLanguageTypes_1.Location.create(document.uri, getRange(document, item));
  7472. result_1.push({ name: Parser.getNodeValue(property.valueNode), kind: jsonLanguageTypes_1.SymbolKind.Function, location: location });
  7473. limit--;
  7474. if (limit <= 0) {
  7475. if (context && context.onResultLimitExceeded) {
  7476. context.onResultLimitExceeded(resourceString);
  7477. }
  7478. return result_1;
  7479. }
  7480. }
  7481. }
  7482. }
  7483. }
  7484. return result_1;
  7485. }
  7486. }
  7487. var toVisit = [
  7488. { node: root, containerName: '' }
  7489. ];
  7490. var nextToVisit = 0;
  7491. var limitExceeded = false;
  7492. var result = [];
  7493. var collectOutlineEntries = function (node, containerName) {
  7494. if (node.type === 'array') {
  7495. node.items.forEach(function (node) {
  7496. if (node) {
  7497. toVisit.push({ node: node, containerName: containerName });
  7498. }
  7499. });
  7500. }
  7501. else if (node.type === 'object') {
  7502. node.properties.forEach(function (property) {
  7503. var valueNode = property.valueNode;
  7504. if (valueNode) {
  7505. if (limit > 0) {
  7506. limit--;
  7507. var location = jsonLanguageTypes_1.Location.create(document.uri, getRange(document, property));
  7508. var childContainerName = containerName ? containerName + '.' + property.keyNode.value : property.keyNode.value;
  7509. result.push({ name: _this.getKeyLabel(property), kind: _this.getSymbolKind(valueNode.type), location: location, containerName: containerName });
  7510. toVisit.push({ node: valueNode, containerName: childContainerName });
  7511. }
  7512. else {
  7513. limitExceeded = true;
  7514. }
  7515. }
  7516. });
  7517. }
  7518. };
  7519. // breath first traversal
  7520. while (nextToVisit < toVisit.length) {
  7521. var next = toVisit[nextToVisit++];
  7522. collectOutlineEntries(next.node, next.containerName);
  7523. }
  7524. if (limitExceeded && context && context.onResultLimitExceeded) {
  7525. context.onResultLimitExceeded(resourceString);
  7526. }
  7527. return result;
  7528. };
  7529. JSONDocumentSymbols.prototype.findDocumentSymbols2 = function (document, doc, context) {
  7530. var _this = this;
  7531. if (context === void 0) { context = { resultLimit: Number.MAX_VALUE }; }
  7532. var root = doc.root;
  7533. if (!root) {
  7534. return [];
  7535. }
  7536. var limit = context.resultLimit || Number.MAX_VALUE;
  7537. // special handling for key bindings
  7538. var resourceString = document.uri;
  7539. if ((resourceString === 'vscode://defaultsettings/keybindings.json') || Strings.endsWith(resourceString.toLowerCase(), '/user/keybindings.json')) {
  7540. if (root.type === 'array') {
  7541. var result_2 = [];
  7542. for (var _i = 0, _a = root.items; _i < _a.length; _i++) {
  7543. var item = _a[_i];
  7544. if (item.type === 'object') {
  7545. for (var _b = 0, _c = item.properties; _b < _c.length; _b++) {
  7546. var property = _c[_b];
  7547. if (property.keyNode.value === 'key' && property.valueNode) {
  7548. var range = getRange(document, item);
  7549. var selectionRange = getRange(document, property.keyNode);
  7550. result_2.push({ name: Parser.getNodeValue(property.valueNode), kind: jsonLanguageTypes_1.SymbolKind.Function, range: range, selectionRange: selectionRange });
  7551. limit--;
  7552. if (limit <= 0) {
  7553. if (context && context.onResultLimitExceeded) {
  7554. context.onResultLimitExceeded(resourceString);
  7555. }
  7556. return result_2;
  7557. }
  7558. }
  7559. }
  7560. }
  7561. }
  7562. return result_2;
  7563. }
  7564. }
  7565. var result = [];
  7566. var toVisit = [
  7567. { node: root, result: result }
  7568. ];
  7569. var nextToVisit = 0;
  7570. var limitExceeded = false;
  7571. var collectOutlineEntries = function (node, result) {
  7572. if (node.type === 'array') {
  7573. node.items.forEach(function (node, index) {
  7574. if (node) {
  7575. if (limit > 0) {
  7576. limit--;
  7577. var range = getRange(document, node);
  7578. var selectionRange = range;
  7579. var name = String(index);
  7580. var symbol = { name: name, kind: _this.getSymbolKind(node.type), range: range, selectionRange: selectionRange, children: [] };
  7581. result.push(symbol);
  7582. toVisit.push({ result: symbol.children, node: node });
  7583. }
  7584. else {
  7585. limitExceeded = true;
  7586. }
  7587. }
  7588. });
  7589. }
  7590. else if (node.type === 'object') {
  7591. node.properties.forEach(function (property) {
  7592. var valueNode = property.valueNode;
  7593. if (valueNode) {
  7594. if (limit > 0) {
  7595. limit--;
  7596. var range = getRange(document, property);
  7597. var selectionRange = getRange(document, property.keyNode);
  7598. var children = [];
  7599. var symbol = { name: _this.getKeyLabel(property), kind: _this.getSymbolKind(valueNode.type), range: range, selectionRange: selectionRange, children: children, detail: _this.getDetail(valueNode) };
  7600. result.push(symbol);
  7601. toVisit.push({ result: children, node: valueNode });
  7602. }
  7603. else {
  7604. limitExceeded = true;
  7605. }
  7606. }
  7607. });
  7608. }
  7609. };
  7610. // breath first traversal
  7611. while (nextToVisit < toVisit.length) {
  7612. var next = toVisit[nextToVisit++];
  7613. collectOutlineEntries(next.node, next.result);
  7614. }
  7615. if (limitExceeded && context && context.onResultLimitExceeded) {
  7616. context.onResultLimitExceeded(resourceString);
  7617. }
  7618. return result;
  7619. };
  7620. JSONDocumentSymbols.prototype.getSymbolKind = function (nodeType) {
  7621. switch (nodeType) {
  7622. case 'object':
  7623. return jsonLanguageTypes_1.SymbolKind.Module;
  7624. case 'string':
  7625. return jsonLanguageTypes_1.SymbolKind.String;
  7626. case 'number':
  7627. return jsonLanguageTypes_1.SymbolKind.Number;
  7628. case 'array':
  7629. return jsonLanguageTypes_1.SymbolKind.Array;
  7630. case 'boolean':
  7631. return jsonLanguageTypes_1.SymbolKind.Boolean;
  7632. default: // 'null'
  7633. return jsonLanguageTypes_1.SymbolKind.Variable;
  7634. }
  7635. };
  7636. JSONDocumentSymbols.prototype.getKeyLabel = function (property) {
  7637. var name = property.keyNode.value;
  7638. if (name) {
  7639. name = name.replace(/[\n]/g, '↵');
  7640. }
  7641. if (name && name.trim()) {
  7642. return name;
  7643. }
  7644. return "\"" + name + "\"";
  7645. };
  7646. JSONDocumentSymbols.prototype.getDetail = function (node) {
  7647. if (!node) {
  7648. return undefined;
  7649. }
  7650. if (node.type === 'boolean' || node.type === 'number' || node.type === 'null' || node.type === 'string') {
  7651. return String(node.value);
  7652. }
  7653. else {
  7654. if (node.type === 'array') {
  7655. return node.children.length ? undefined : '[]';
  7656. }
  7657. else if (node.type === 'object') {
  7658. return node.children.length ? undefined : '{}';
  7659. }
  7660. }
  7661. return undefined;
  7662. };
  7663. JSONDocumentSymbols.prototype.findDocumentColors = function (document, doc, context) {
  7664. return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
  7665. var result = [];
  7666. if (schema) {
  7667. var limit = context && typeof context.resultLimit === 'number' ? context.resultLimit : Number.MAX_VALUE;
  7668. var matchingSchemas = doc.getMatchingSchemas(schema.schema);
  7669. var visitedNode = {};
  7670. for (var _i = 0, matchingSchemas_1 = matchingSchemas; _i < matchingSchemas_1.length; _i++) {
  7671. var s = matchingSchemas_1[_i];
  7672. if (!s.inverted && s.schema && (s.schema.format === 'color' || s.schema.format === 'color-hex') && s.node && s.node.type === 'string') {
  7673. var nodeId = String(s.node.offset);
  7674. if (!visitedNode[nodeId]) {
  7675. var color = colors_1.colorFromHex(Parser.getNodeValue(s.node));
  7676. if (color) {
  7677. var range = getRange(document, s.node);
  7678. result.push({ color: color, range: range });
  7679. }
  7680. visitedNode[nodeId] = true;
  7681. limit--;
  7682. if (limit <= 0) {
  7683. if (context && context.onResultLimitExceeded) {
  7684. context.onResultLimitExceeded(document.uri);
  7685. }
  7686. return result;
  7687. }
  7688. }
  7689. }
  7690. }
  7691. }
  7692. return result;
  7693. });
  7694. };
  7695. JSONDocumentSymbols.prototype.getColorPresentations = function (document, doc, color, range) {
  7696. var result = [];
  7697. var red256 = Math.round(color.red * 255), green256 = Math.round(color.green * 255), blue256 = Math.round(color.blue * 255);
  7698. function toTwoDigitHex(n) {
  7699. var r = n.toString(16);
  7700. return r.length !== 2 ? '0' + r : r;
  7701. }
  7702. var label;
  7703. if (color.alpha === 1) {
  7704. label = "#" + toTwoDigitHex(red256) + toTwoDigitHex(green256) + toTwoDigitHex(blue256);
  7705. }
  7706. else {
  7707. label = "#" + toTwoDigitHex(red256) + toTwoDigitHex(green256) + toTwoDigitHex(blue256) + toTwoDigitHex(Math.round(color.alpha * 255));
  7708. }
  7709. result.push({ label: label, textEdit: jsonLanguageTypes_1.TextEdit.replace(range, JSON.stringify(label)) });
  7710. return result;
  7711. };
  7712. return JSONDocumentSymbols;
  7713. }());
  7714. exports.JSONDocumentSymbols = JSONDocumentSymbols;
  7715. function getRange(document, node) {
  7716. return jsonLanguageTypes_1.Range.create(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
  7717. }
  7718. });
  7719. /*---------------------------------------------------------------------------------------------
  7720. * Copyright (c) Microsoft Corporation. All rights reserved.
  7721. * Licensed under the MIT License. See License.txt in the project root for license information.
  7722. *--------------------------------------------------------------------------------------------*/
  7723. (function (factory) {
  7724. if (typeof module === "object" && typeof module.exports === "object") {
  7725. var v = factory(require, exports);
  7726. if (v !== undefined) module.exports = v;
  7727. }
  7728. else if (typeof define === "function" && define.amd) {
  7729. define('vscode-json-languageservice/services/configuration',["require", "exports", "vscode-nls"], factory);
  7730. }
  7731. })(function (require, exports) {
  7732. "use strict";
  7733. Object.defineProperty(exports, "__esModule", { value: true });
  7734. exports.schemaContributions = void 0;
  7735. var nls = require("vscode-nls");
  7736. var localize = nls.loadMessageBundle();
  7737. exports.schemaContributions = {
  7738. schemaAssociations: [],
  7739. schemas: {
  7740. // refer to the latest schema
  7741. 'http://json-schema.org/schema#': {
  7742. $ref: 'http://json-schema.org/draft-07/schema#'
  7743. },
  7744. // bundle the schema-schema to include (localized) descriptions
  7745. 'http://json-schema.org/draft-04/schema#': {
  7746. 'title': localize('schema.json', 'Describes a JSON file using a schema. See json-schema.org for more info.'),
  7747. '$schema': 'http://json-schema.org/draft-04/schema#',
  7748. 'definitions': {
  7749. 'schemaArray': {
  7750. 'type': 'array',
  7751. 'minItems': 1,
  7752. 'items': {
  7753. '$ref': '#'
  7754. }
  7755. },
  7756. 'positiveInteger': {
  7757. 'type': 'integer',
  7758. 'minimum': 0
  7759. },
  7760. 'positiveIntegerDefault0': {
  7761. 'allOf': [
  7762. {
  7763. '$ref': '#/definitions/positiveInteger'
  7764. },
  7765. {
  7766. 'default': 0
  7767. }
  7768. ]
  7769. },
  7770. 'simpleTypes': {
  7771. 'type': 'string',
  7772. 'enum': [
  7773. 'array',
  7774. 'boolean',
  7775. 'integer',
  7776. 'null',
  7777. 'number',
  7778. 'object',
  7779. 'string'
  7780. ]
  7781. },
  7782. 'stringArray': {
  7783. 'type': 'array',
  7784. 'items': {
  7785. 'type': 'string'
  7786. },
  7787. 'minItems': 1,
  7788. 'uniqueItems': true
  7789. }
  7790. },
  7791. 'type': 'object',
  7792. 'properties': {
  7793. 'id': {
  7794. 'type': 'string',
  7795. 'format': 'uri'
  7796. },
  7797. '$schema': {
  7798. 'type': 'string',
  7799. 'format': 'uri'
  7800. },
  7801. 'title': {
  7802. 'type': 'string'
  7803. },
  7804. 'description': {
  7805. 'type': 'string'
  7806. },
  7807. 'default': {},
  7808. 'multipleOf': {
  7809. 'type': 'number',
  7810. 'minimum': 0,
  7811. 'exclusiveMinimum': true
  7812. },
  7813. 'maximum': {
  7814. 'type': 'number'
  7815. },
  7816. 'exclusiveMaximum': {
  7817. 'type': 'boolean',
  7818. 'default': false
  7819. },
  7820. 'minimum': {
  7821. 'type': 'number'
  7822. },
  7823. 'exclusiveMinimum': {
  7824. 'type': 'boolean',
  7825. 'default': false
  7826. },
  7827. 'maxLength': {
  7828. 'allOf': [
  7829. {
  7830. '$ref': '#/definitions/positiveInteger'
  7831. }
  7832. ]
  7833. },
  7834. 'minLength': {
  7835. 'allOf': [
  7836. {
  7837. '$ref': '#/definitions/positiveIntegerDefault0'
  7838. }
  7839. ]
  7840. },
  7841. 'pattern': {
  7842. 'type': 'string',
  7843. 'format': 'regex'
  7844. },
  7845. 'additionalItems': {
  7846. 'anyOf': [
  7847. {
  7848. 'type': 'boolean'
  7849. },
  7850. {
  7851. '$ref': '#'
  7852. }
  7853. ],
  7854. 'default': {}
  7855. },
  7856. 'items': {
  7857. 'anyOf': [
  7858. {
  7859. '$ref': '#'
  7860. },
  7861. {
  7862. '$ref': '#/definitions/schemaArray'
  7863. }
  7864. ],
  7865. 'default': {}
  7866. },
  7867. 'maxItems': {
  7868. 'allOf': [
  7869. {
  7870. '$ref': '#/definitions/positiveInteger'
  7871. }
  7872. ]
  7873. },
  7874. 'minItems': {
  7875. 'allOf': [
  7876. {
  7877. '$ref': '#/definitions/positiveIntegerDefault0'
  7878. }
  7879. ]
  7880. },
  7881. 'uniqueItems': {
  7882. 'type': 'boolean',
  7883. 'default': false
  7884. },
  7885. 'maxProperties': {
  7886. 'allOf': [
  7887. {
  7888. '$ref': '#/definitions/positiveInteger'
  7889. }
  7890. ]
  7891. },
  7892. 'minProperties': {
  7893. 'allOf': [
  7894. {
  7895. '$ref': '#/definitions/positiveIntegerDefault0'
  7896. }
  7897. ]
  7898. },
  7899. 'required': {
  7900. 'allOf': [
  7901. {
  7902. '$ref': '#/definitions/stringArray'
  7903. }
  7904. ]
  7905. },
  7906. 'additionalProperties': {
  7907. 'anyOf': [
  7908. {
  7909. 'type': 'boolean'
  7910. },
  7911. {
  7912. '$ref': '#'
  7913. }
  7914. ],
  7915. 'default': {}
  7916. },
  7917. 'definitions': {
  7918. 'type': 'object',
  7919. 'additionalProperties': {
  7920. '$ref': '#'
  7921. },
  7922. 'default': {}
  7923. },
  7924. 'properties': {
  7925. 'type': 'object',
  7926. 'additionalProperties': {
  7927. '$ref': '#'
  7928. },
  7929. 'default': {}
  7930. },
  7931. 'patternProperties': {
  7932. 'type': 'object',
  7933. 'additionalProperties': {
  7934. '$ref': '#'
  7935. },
  7936. 'default': {}
  7937. },
  7938. 'dependencies': {
  7939. 'type': 'object',
  7940. 'additionalProperties': {
  7941. 'anyOf': [
  7942. {
  7943. '$ref': '#'
  7944. },
  7945. {
  7946. '$ref': '#/definitions/stringArray'
  7947. }
  7948. ]
  7949. }
  7950. },
  7951. 'enum': {
  7952. 'type': 'array',
  7953. 'minItems': 1,
  7954. 'uniqueItems': true
  7955. },
  7956. 'type': {
  7957. 'anyOf': [
  7958. {
  7959. '$ref': '#/definitions/simpleTypes'
  7960. },
  7961. {
  7962. 'type': 'array',
  7963. 'items': {
  7964. '$ref': '#/definitions/simpleTypes'
  7965. },
  7966. 'minItems': 1,
  7967. 'uniqueItems': true
  7968. }
  7969. ]
  7970. },
  7971. 'format': {
  7972. 'anyOf': [
  7973. {
  7974. 'type': 'string',
  7975. 'enum': [
  7976. 'date-time',
  7977. 'uri',
  7978. 'email',
  7979. 'hostname',
  7980. 'ipv4',
  7981. 'ipv6',
  7982. 'regex'
  7983. ]
  7984. },
  7985. {
  7986. 'type': 'string'
  7987. }
  7988. ]
  7989. },
  7990. 'allOf': {
  7991. 'allOf': [
  7992. {
  7993. '$ref': '#/definitions/schemaArray'
  7994. }
  7995. ]
  7996. },
  7997. 'anyOf': {
  7998. 'allOf': [
  7999. {
  8000. '$ref': '#/definitions/schemaArray'
  8001. }
  8002. ]
  8003. },
  8004. 'oneOf': {
  8005. 'allOf': [
  8006. {
  8007. '$ref': '#/definitions/schemaArray'
  8008. }
  8009. ]
  8010. },
  8011. 'not': {
  8012. 'allOf': [
  8013. {
  8014. '$ref': '#'
  8015. }
  8016. ]
  8017. }
  8018. },
  8019. 'dependencies': {
  8020. 'exclusiveMaximum': [
  8021. 'maximum'
  8022. ],
  8023. 'exclusiveMinimum': [
  8024. 'minimum'
  8025. ]
  8026. },
  8027. 'default': {}
  8028. },
  8029. 'http://json-schema.org/draft-07/schema#': {
  8030. 'title': localize('schema.json', 'Describes a JSON file using a schema. See json-schema.org for more info.'),
  8031. 'definitions': {
  8032. 'schemaArray': {
  8033. 'type': 'array',
  8034. 'minItems': 1,
  8035. 'items': { '$ref': '#' }
  8036. },
  8037. 'nonNegativeInteger': {
  8038. 'type': 'integer',
  8039. 'minimum': 0
  8040. },
  8041. 'nonNegativeIntegerDefault0': {
  8042. 'allOf': [
  8043. { '$ref': '#/definitions/nonNegativeInteger' },
  8044. { 'default': 0 }
  8045. ]
  8046. },
  8047. 'simpleTypes': {
  8048. 'enum': [
  8049. 'array',
  8050. 'boolean',
  8051. 'integer',
  8052. 'null',
  8053. 'number',
  8054. 'object',
  8055. 'string'
  8056. ]
  8057. },
  8058. 'stringArray': {
  8059. 'type': 'array',
  8060. 'items': { 'type': 'string' },
  8061. 'uniqueItems': true,
  8062. 'default': []
  8063. }
  8064. },
  8065. 'type': ['object', 'boolean'],
  8066. 'properties': {
  8067. '$id': {
  8068. 'type': 'string',
  8069. 'format': 'uri-reference'
  8070. },
  8071. '$schema': {
  8072. 'type': 'string',
  8073. 'format': 'uri'
  8074. },
  8075. '$ref': {
  8076. 'type': 'string',
  8077. 'format': 'uri-reference'
  8078. },
  8079. '$comment': {
  8080. 'type': 'string'
  8081. },
  8082. 'title': {
  8083. 'type': 'string'
  8084. },
  8085. 'description': {
  8086. 'type': 'string'
  8087. },
  8088. 'default': true,
  8089. 'readOnly': {
  8090. 'type': 'boolean',
  8091. 'default': false
  8092. },
  8093. 'examples': {
  8094. 'type': 'array',
  8095. 'items': true
  8096. },
  8097. 'multipleOf': {
  8098. 'type': 'number',
  8099. 'exclusiveMinimum': 0
  8100. },
  8101. 'maximum': {
  8102. 'type': 'number'
  8103. },
  8104. 'exclusiveMaximum': {
  8105. 'type': 'number'
  8106. },
  8107. 'minimum': {
  8108. 'type': 'number'
  8109. },
  8110. 'exclusiveMinimum': {
  8111. 'type': 'number'
  8112. },
  8113. 'maxLength': { '$ref': '#/definitions/nonNegativeInteger' },
  8114. 'minLength': { '$ref': '#/definitions/nonNegativeIntegerDefault0' },
  8115. 'pattern': {
  8116. 'type': 'string',
  8117. 'format': 'regex'
  8118. },
  8119. 'additionalItems': { '$ref': '#' },
  8120. 'items': {
  8121. 'anyOf': [
  8122. { '$ref': '#' },
  8123. { '$ref': '#/definitions/schemaArray' }
  8124. ],
  8125. 'default': true
  8126. },
  8127. 'maxItems': { '$ref': '#/definitions/nonNegativeInteger' },
  8128. 'minItems': { '$ref': '#/definitions/nonNegativeIntegerDefault0' },
  8129. 'uniqueItems': {
  8130. 'type': 'boolean',
  8131. 'default': false
  8132. },
  8133. 'contains': { '$ref': '#' },
  8134. 'maxProperties': { '$ref': '#/definitions/nonNegativeInteger' },
  8135. 'minProperties': { '$ref': '#/definitions/nonNegativeIntegerDefault0' },
  8136. 'required': { '$ref': '#/definitions/stringArray' },
  8137. 'additionalProperties': { '$ref': '#' },
  8138. 'definitions': {
  8139. 'type': 'object',
  8140. 'additionalProperties': { '$ref': '#' },
  8141. 'default': {}
  8142. },
  8143. 'properties': {
  8144. 'type': 'object',
  8145. 'additionalProperties': { '$ref': '#' },
  8146. 'default': {}
  8147. },
  8148. 'patternProperties': {
  8149. 'type': 'object',
  8150. 'additionalProperties': { '$ref': '#' },
  8151. 'propertyNames': { 'format': 'regex' },
  8152. 'default': {}
  8153. },
  8154. 'dependencies': {
  8155. 'type': 'object',
  8156. 'additionalProperties': {
  8157. 'anyOf': [
  8158. { '$ref': '#' },
  8159. { '$ref': '#/definitions/stringArray' }
  8160. ]
  8161. }
  8162. },
  8163. 'propertyNames': { '$ref': '#' },
  8164. 'const': true,
  8165. 'enum': {
  8166. 'type': 'array',
  8167. 'items': true,
  8168. 'minItems': 1,
  8169. 'uniqueItems': true
  8170. },
  8171. 'type': {
  8172. 'anyOf': [
  8173. { '$ref': '#/definitions/simpleTypes' },
  8174. {
  8175. 'type': 'array',
  8176. 'items': { '$ref': '#/definitions/simpleTypes' },
  8177. 'minItems': 1,
  8178. 'uniqueItems': true
  8179. }
  8180. ]
  8181. },
  8182. 'format': { 'type': 'string' },
  8183. 'contentMediaType': { 'type': 'string' },
  8184. 'contentEncoding': { 'type': 'string' },
  8185. 'if': { '$ref': '#' },
  8186. 'then': { '$ref': '#' },
  8187. 'else': { '$ref': '#' },
  8188. 'allOf': { '$ref': '#/definitions/schemaArray' },
  8189. 'anyOf': { '$ref': '#/definitions/schemaArray' },
  8190. 'oneOf': { '$ref': '#/definitions/schemaArray' },
  8191. 'not': { '$ref': '#' }
  8192. },
  8193. 'default': true
  8194. }
  8195. }
  8196. };
  8197. var descriptions = {
  8198. id: localize('schema.json.id', "A unique identifier for the schema."),
  8199. $schema: localize('schema.json.$schema', "The schema to verify this document against."),
  8200. title: localize('schema.json.title', "A descriptive title of the element."),
  8201. description: localize('schema.json.description', "A long description of the element. Used in hover menus and suggestions."),
  8202. default: localize('schema.json.default', "A default value. Used by suggestions."),
  8203. multipleOf: localize('schema.json.multipleOf', "A number that should cleanly divide the current value (i.e. have no remainder)."),
  8204. maximum: localize('schema.json.maximum', "The maximum numerical value, inclusive by default."),
  8205. exclusiveMaximum: localize('schema.json.exclusiveMaximum', "Makes the maximum property exclusive."),
  8206. minimum: localize('schema.json.minimum', "The minimum numerical value, inclusive by default."),
  8207. exclusiveMinimum: localize('schema.json.exclusiveMininum', "Makes the minimum property exclusive."),
  8208. maxLength: localize('schema.json.maxLength', "The maximum length of a string."),
  8209. minLength: localize('schema.json.minLength', "The minimum length of a string."),
  8210. pattern: localize('schema.json.pattern', "A regular expression to match the string against. It is not implicitly anchored."),
  8211. 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."),
  8212. 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."),
  8213. maxItems: localize('schema.json.maxItems', "The maximum number of items that can be inside an array. Inclusive."),
  8214. minItems: localize('schema.json.minItems', "The minimum number of items that can be inside an array. Inclusive."),
  8215. uniqueItems: localize('schema.json.uniqueItems', "If all of the items in the array must be unique. Defaults to false."),
  8216. maxProperties: localize('schema.json.maxProperties', "The maximum number of properties an object can have. Inclusive."),
  8217. minProperties: localize('schema.json.minProperties', "The minimum number of properties an object can have. Inclusive."),
  8218. required: localize('schema.json.required', "An array of strings that lists the names of all properties required on this object."),
  8219. 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."),
  8220. definitions: localize('schema.json.definitions', "Not used for validation. Place subschemas here that you wish to reference inline with $ref."),
  8221. properties: localize('schema.json.properties', "A map of property names to schemas for each property."),
  8222. patternProperties: localize('schema.json.patternProperties', "A map of regular expressions on property names to schemas for matching properties."),
  8223. 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."),
  8224. enum: localize('schema.json.enum', "The set of literal values that are valid."),
  8225. 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."),
  8226. format: localize('schema.json.format', "Describes the format expected for the value."),
  8227. allOf: localize('schema.json.allOf', "An array of schemas, all of which must match."),
  8228. anyOf: localize('schema.json.anyOf', "An array of schemas, where at least one must match."),
  8229. oneOf: localize('schema.json.oneOf', "An array of schemas, exactly one of which must match."),
  8230. not: localize('schema.json.not', "A schema which must not match."),
  8231. $id: localize('schema.json.$id', "A unique identifier for the schema."),
  8232. $ref: localize('schema.json.$ref', "Reference a definition hosted on any location."),
  8233. $comment: localize('schema.json.$comment', "Comments from schema authors to readers or maintainers of the schema."),
  8234. readOnly: localize('schema.json.readOnly', "Indicates that the value of the instance is managed exclusively by the owning authority."),
  8235. examples: localize('schema.json.examples', "Sample JSON values associated with a particular schema, for the purpose of illustrating usage."),
  8236. 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."),
  8237. 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."),
  8238. const: localize('schema.json.const', "An instance validates successfully against this keyword if its value is equal to the value of the keyword."),
  8239. contentMediaType: localize('schema.json.contentMediaType', "Describes the media type of a string property."),
  8240. contentEncoding: localize('schema.json.contentEncoding', "Describes the content encoding of a string property."),
  8241. if: localize('schema.json.if', "The validation outcome of the \"if\" subschema controls which of the \"then\" or \"else\" keywords are evaluated."),
  8242. then: localize('schema.json.then', "The \"if\" subschema is used for validation when the \"if\" subschema succeeds."),
  8243. else: localize('schema.json.else', "The \"else\" subschema is used for validation when the \"if\" subschema fails.")
  8244. };
  8245. for (var schemaName in exports.schemaContributions.schemas) {
  8246. var schema = exports.schemaContributions.schemas[schemaName];
  8247. for (var property in schema.properties) {
  8248. var propertyObject = schema.properties[property];
  8249. if (typeof propertyObject === 'boolean') {
  8250. propertyObject = schema.properties[property] = {};
  8251. }
  8252. var description = descriptions[property];
  8253. if (description) {
  8254. propertyObject['description'] = description;
  8255. }
  8256. else {
  8257. console.log(property + ": localize('schema.json." + property + "', \"\")");
  8258. }
  8259. }
  8260. }
  8261. });
  8262. /*---------------------------------------------------------------------------------------------
  8263. * Copyright (c) Microsoft Corporation. All rights reserved.
  8264. * Licensed under the MIT License. See License.txt in the project root for license information.
  8265. *--------------------------------------------------------------------------------------------*/
  8266. (function (factory) {
  8267. if (typeof module === "object" && typeof module.exports === "object") {
  8268. var v = factory(require, exports);
  8269. if (v !== undefined) module.exports = v;
  8270. }
  8271. else if (typeof define === "function" && define.amd) {
  8272. define('vscode-json-languageservice/services/jsonFolding',["require", "exports", "jsonc-parser", "../jsonLanguageTypes"], factory);
  8273. }
  8274. })(function (require, exports) {
  8275. "use strict";
  8276. Object.defineProperty(exports, "__esModule", { value: true });
  8277. exports.getFoldingRanges = void 0;
  8278. var jsonc_parser_1 = require("jsonc-parser");
  8279. var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
  8280. function getFoldingRanges(document, context) {
  8281. var ranges = [];
  8282. var nestingLevels = [];
  8283. var stack = [];
  8284. var prevStart = -1;
  8285. var scanner = jsonc_parser_1.createScanner(document.getText(), false);
  8286. var token = scanner.scan();
  8287. function addRange(range) {
  8288. ranges.push(range);
  8289. nestingLevels.push(stack.length);
  8290. }
  8291. while (token !== 17 /* EOF */) {
  8292. switch (token) {
  8293. case 1 /* OpenBraceToken */:
  8294. case 3 /* OpenBracketToken */: {
  8295. var startLine = document.positionAt(scanner.getTokenOffset()).line;
  8296. var range = { startLine: startLine, endLine: startLine, kind: token === 1 /* OpenBraceToken */ ? 'object' : 'array' };
  8297. stack.push(range);
  8298. break;
  8299. }
  8300. case 2 /* CloseBraceToken */:
  8301. case 4 /* CloseBracketToken */: {
  8302. var kind = token === 2 /* CloseBraceToken */ ? 'object' : 'array';
  8303. if (stack.length > 0 && stack[stack.length - 1].kind === kind) {
  8304. var range = stack.pop();
  8305. var line = document.positionAt(scanner.getTokenOffset()).line;
  8306. if (range && line > range.startLine + 1 && prevStart !== range.startLine) {
  8307. range.endLine = line - 1;
  8308. addRange(range);
  8309. prevStart = range.startLine;
  8310. }
  8311. }
  8312. break;
  8313. }
  8314. case 13 /* BlockCommentTrivia */: {
  8315. var startLine = document.positionAt(scanner.getTokenOffset()).line;
  8316. var endLine = document.positionAt(scanner.getTokenOffset() + scanner.getTokenLength()).line;
  8317. if (scanner.getTokenError() === 1 /* UnexpectedEndOfComment */ && startLine + 1 < document.lineCount) {
  8318. scanner.setPosition(document.offsetAt(jsonLanguageTypes_1.Position.create(startLine + 1, 0)));
  8319. }
  8320. else {
  8321. if (startLine < endLine) {
  8322. addRange({ startLine: startLine, endLine: endLine, kind: jsonLanguageTypes_1.FoldingRangeKind.Comment });
  8323. prevStart = startLine;
  8324. }
  8325. }
  8326. break;
  8327. }
  8328. case 12 /* LineCommentTrivia */: {
  8329. var text = document.getText().substr(scanner.getTokenOffset(), scanner.getTokenLength());
  8330. var m = text.match(/^\/\/\s*#(region\b)|(endregion\b)/);
  8331. if (m) {
  8332. var line = document.positionAt(scanner.getTokenOffset()).line;
  8333. if (m[1]) { // start pattern match
  8334. var range = { startLine: line, endLine: line, kind: jsonLanguageTypes_1.FoldingRangeKind.Region };
  8335. stack.push(range);
  8336. }
  8337. else {
  8338. var i = stack.length - 1;
  8339. while (i >= 0 && stack[i].kind !== jsonLanguageTypes_1.FoldingRangeKind.Region) {
  8340. i--;
  8341. }
  8342. if (i >= 0) {
  8343. var range = stack[i];
  8344. stack.length = i;
  8345. if (line > range.startLine && prevStart !== range.startLine) {
  8346. range.endLine = line;
  8347. addRange(range);
  8348. prevStart = range.startLine;
  8349. }
  8350. }
  8351. }
  8352. }
  8353. break;
  8354. }
  8355. }
  8356. token = scanner.scan();
  8357. }
  8358. var rangeLimit = context && context.rangeLimit;
  8359. if (typeof rangeLimit !== 'number' || ranges.length <= rangeLimit) {
  8360. return ranges;
  8361. }
  8362. if (context && context.onRangeLimitExceeded) {
  8363. context.onRangeLimitExceeded(document.uri);
  8364. }
  8365. var counts = [];
  8366. for (var _i = 0, nestingLevels_1 = nestingLevels; _i < nestingLevels_1.length; _i++) {
  8367. var level = nestingLevels_1[_i];
  8368. if (level < 30) {
  8369. counts[level] = (counts[level] || 0) + 1;
  8370. }
  8371. }
  8372. var entries = 0;
  8373. var maxLevel = 0;
  8374. for (var i = 0; i < counts.length; i++) {
  8375. var n = counts[i];
  8376. if (n) {
  8377. if (n + entries > rangeLimit) {
  8378. maxLevel = i;
  8379. break;
  8380. }
  8381. entries += n;
  8382. }
  8383. }
  8384. var result = [];
  8385. for (var i = 0; i < ranges.length; i++) {
  8386. var level = nestingLevels[i];
  8387. if (typeof level === 'number') {
  8388. if (level < maxLevel || (level === maxLevel && entries++ < rangeLimit)) {
  8389. result.push(ranges[i]);
  8390. }
  8391. }
  8392. }
  8393. return result;
  8394. }
  8395. exports.getFoldingRanges = getFoldingRanges;
  8396. });
  8397. /*---------------------------------------------------------------------------------------------
  8398. * Copyright (c) Microsoft Corporation. All rights reserved.
  8399. * Licensed under the MIT License. See License.txt in the project root for license information.
  8400. *--------------------------------------------------------------------------------------------*/
  8401. (function (factory) {
  8402. if (typeof module === "object" && typeof module.exports === "object") {
  8403. var v = factory(require, exports);
  8404. if (v !== undefined) module.exports = v;
  8405. }
  8406. else if (typeof define === "function" && define.amd) {
  8407. define('vscode-json-languageservice/services/jsonSelectionRanges',["require", "exports", "../jsonLanguageTypes", "jsonc-parser"], factory);
  8408. }
  8409. })(function (require, exports) {
  8410. "use strict";
  8411. Object.defineProperty(exports, "__esModule", { value: true });
  8412. exports.getSelectionRanges = void 0;
  8413. var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
  8414. var jsonc_parser_1 = require("jsonc-parser");
  8415. function getSelectionRanges(document, positions, doc) {
  8416. function getSelectionRange(position) {
  8417. var offset = document.offsetAt(position);
  8418. var node = doc.getNodeFromOffset(offset, true);
  8419. var result = [];
  8420. while (node) {
  8421. switch (node.type) {
  8422. case 'string':
  8423. case 'object':
  8424. case 'array':
  8425. // range without ", [ or {
  8426. var cStart = node.offset + 1, cEnd = node.offset + node.length - 1;
  8427. if (cStart < cEnd && offset >= cStart && offset <= cEnd) {
  8428. result.push(newRange(cStart, cEnd));
  8429. }
  8430. result.push(newRange(node.offset, node.offset + node.length));
  8431. break;
  8432. case 'number':
  8433. case 'boolean':
  8434. case 'null':
  8435. case 'property':
  8436. result.push(newRange(node.offset, node.offset + node.length));
  8437. break;
  8438. }
  8439. if (node.type === 'property' || node.parent && node.parent.type === 'array') {
  8440. var afterCommaOffset = getOffsetAfterNextToken(node.offset + node.length, 5 /* CommaToken */);
  8441. if (afterCommaOffset !== -1) {
  8442. result.push(newRange(node.offset, afterCommaOffset));
  8443. }
  8444. }
  8445. node = node.parent;
  8446. }
  8447. var current = undefined;
  8448. for (var index = result.length - 1; index >= 0; index--) {
  8449. current = jsonLanguageTypes_1.SelectionRange.create(result[index], current);
  8450. }
  8451. if (!current) {
  8452. current = jsonLanguageTypes_1.SelectionRange.create(jsonLanguageTypes_1.Range.create(position, position));
  8453. }
  8454. return current;
  8455. }
  8456. function newRange(start, end) {
  8457. return jsonLanguageTypes_1.Range.create(document.positionAt(start), document.positionAt(end));
  8458. }
  8459. var scanner = jsonc_parser_1.createScanner(document.getText(), true);
  8460. function getOffsetAfterNextToken(offset, expectedToken) {
  8461. scanner.setPosition(offset);
  8462. var token = scanner.scan();
  8463. if (token === expectedToken) {
  8464. return scanner.getTokenOffset() + scanner.getTokenLength();
  8465. }
  8466. return -1;
  8467. }
  8468. return positions.map(getSelectionRange);
  8469. }
  8470. exports.getSelectionRanges = getSelectionRanges;
  8471. });
  8472. /*---------------------------------------------------------------------------------------------
  8473. * Copyright (c) Microsoft Corporation. All rights reserved.
  8474. * Licensed under the MIT License. See License.txt in the project root for license information.
  8475. *--------------------------------------------------------------------------------------------*/
  8476. (function (factory) {
  8477. if (typeof module === "object" && typeof module.exports === "object") {
  8478. var v = factory(require, exports);
  8479. if (v !== undefined) module.exports = v;
  8480. }
  8481. else if (typeof define === "function" && define.amd) {
  8482. define('vscode-json-languageservice/services/jsonLinks',["require", "exports", "../jsonLanguageTypes"], factory);
  8483. }
  8484. })(function (require, exports) {
  8485. "use strict";
  8486. Object.defineProperty(exports, "__esModule", { value: true });
  8487. exports.findLinks = void 0;
  8488. var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
  8489. function findLinks(document, doc) {
  8490. var links = [];
  8491. doc.visit(function (node) {
  8492. var _a;
  8493. if (node.type === "property" && node.keyNode.value === "$ref" && ((_a = node.valueNode) === null || _a === void 0 ? void 0 : _a.type) === 'string') {
  8494. var path = node.valueNode.value;
  8495. var targetNode = findTargetNode(doc, path);
  8496. if (targetNode) {
  8497. var targetPos = document.positionAt(targetNode.offset);
  8498. links.push({
  8499. target: document.uri + "#" + (targetPos.line + 1) + "," + (targetPos.character + 1),
  8500. range: createRange(document, node.valueNode)
  8501. });
  8502. }
  8503. }
  8504. return true;
  8505. });
  8506. return Promise.resolve(links);
  8507. }
  8508. exports.findLinks = findLinks;
  8509. function createRange(document, node) {
  8510. return jsonLanguageTypes_1.Range.create(document.positionAt(node.offset + 1), document.positionAt(node.offset + node.length - 1));
  8511. }
  8512. function findTargetNode(doc, path) {
  8513. var tokens = parseJSONPointer(path);
  8514. if (!tokens) {
  8515. return null;
  8516. }
  8517. return findNode(tokens, doc.root);
  8518. }
  8519. function findNode(pointer, node) {
  8520. if (!node) {
  8521. return null;
  8522. }
  8523. if (pointer.length === 0) {
  8524. return node;
  8525. }
  8526. var token = pointer.shift();
  8527. if (node && node.type === 'object') {
  8528. var propertyNode = node.properties.find(function (propertyNode) { return propertyNode.keyNode.value === token; });
  8529. if (!propertyNode) {
  8530. return null;
  8531. }
  8532. return findNode(pointer, propertyNode.valueNode);
  8533. }
  8534. else if (node && node.type === 'array') {
  8535. if (token.match(/^(0|[1-9][0-9]*)$/)) {
  8536. var index = Number.parseInt(token);
  8537. var arrayItem = node.items[index];
  8538. if (!arrayItem) {
  8539. return null;
  8540. }
  8541. return findNode(pointer, arrayItem);
  8542. }
  8543. }
  8544. return null;
  8545. }
  8546. function parseJSONPointer(path) {
  8547. if (path === "#") {
  8548. return [];
  8549. }
  8550. if (path[0] !== '#' || path[1] !== '/') {
  8551. return null;
  8552. }
  8553. return path.substring(2).split(/\//).map(unescape);
  8554. }
  8555. function unescape(str) {
  8556. return str.replace(/~1/g, '/').replace(/~0/g, '~');
  8557. }
  8558. });
  8559. /*---------------------------------------------------------------------------------------------
  8560. * Copyright (c) Microsoft Corporation. All rights reserved.
  8561. * Licensed under the MIT License. See License.txt in the project root for license information.
  8562. *--------------------------------------------------------------------------------------------*/
  8563. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  8564. if (k2 === undefined) k2 = k;
  8565. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  8566. }) : (function(o, m, k, k2) {
  8567. if (k2 === undefined) k2 = k;
  8568. o[k2] = m[k];
  8569. }));
  8570. var __exportStar = (this && this.__exportStar) || function(m, exports) {
  8571. for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
  8572. };
  8573. (function (factory) {
  8574. if (typeof module === "object" && typeof module.exports === "object") {
  8575. var v = factory(require, exports);
  8576. if (v !== undefined) module.exports = v;
  8577. }
  8578. else if (typeof define === "function" && define.amd) {
  8579. 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);
  8580. }
  8581. })(function (require, exports) {
  8582. "use strict";
  8583. Object.defineProperty(exports, "__esModule", { value: true });
  8584. exports.getLanguageService = void 0;
  8585. var jsonCompletion_1 = require("./services/jsonCompletion");
  8586. var jsonHover_1 = require("./services/jsonHover");
  8587. var jsonValidation_1 = require("./services/jsonValidation");
  8588. var jsonDocumentSymbols_1 = require("./services/jsonDocumentSymbols");
  8589. var jsonParser_1 = require("./parser/jsonParser");
  8590. var configuration_1 = require("./services/configuration");
  8591. var jsonSchemaService_1 = require("./services/jsonSchemaService");
  8592. var jsonFolding_1 = require("./services/jsonFolding");
  8593. var jsonSelectionRanges_1 = require("./services/jsonSelectionRanges");
  8594. var jsonc_parser_1 = require("jsonc-parser");
  8595. var jsonLanguageTypes_1 = require("./jsonLanguageTypes");
  8596. var jsonLinks_1 = require("./services/jsonLinks");
  8597. __exportStar(require("./jsonLanguageTypes"), exports);
  8598. function getLanguageService(params) {
  8599. var promise = params.promiseConstructor || Promise;
  8600. var jsonSchemaService = new jsonSchemaService_1.JSONSchemaService(params.schemaRequestService, params.workspaceContext, promise);
  8601. jsonSchemaService.setSchemaContributions(configuration_1.schemaContributions);
  8602. var jsonCompletion = new jsonCompletion_1.JSONCompletion(jsonSchemaService, params.contributions, promise, params.clientCapabilities);
  8603. var jsonHover = new jsonHover_1.JSONHover(jsonSchemaService, params.contributions, promise);
  8604. var jsonDocumentSymbols = new jsonDocumentSymbols_1.JSONDocumentSymbols(jsonSchemaService);
  8605. var jsonValidation = new jsonValidation_1.JSONValidation(jsonSchemaService, promise);
  8606. return {
  8607. configure: function (settings) {
  8608. jsonSchemaService.clearExternalSchemas();
  8609. if (settings.schemas) {
  8610. settings.schemas.forEach(function (settings) {
  8611. jsonSchemaService.registerExternalSchema(settings.uri, settings.fileMatch, settings.schema);
  8612. });
  8613. }
  8614. jsonValidation.configure(settings);
  8615. },
  8616. resetSchema: function (uri) { return jsonSchemaService.onResourceChange(uri); },
  8617. doValidation: jsonValidation.doValidation.bind(jsonValidation),
  8618. parseJSONDocument: function (document) { return jsonParser_1.parse(document, { collectComments: true }); },
  8619. newJSONDocument: function (root, diagnostics) { return jsonParser_1.newJSONDocument(root, diagnostics); },
  8620. getMatchingSchemas: jsonSchemaService.getMatchingSchemas.bind(jsonSchemaService),
  8621. doResolve: jsonCompletion.doResolve.bind(jsonCompletion),
  8622. doComplete: jsonCompletion.doComplete.bind(jsonCompletion),
  8623. findDocumentSymbols: jsonDocumentSymbols.findDocumentSymbols.bind(jsonDocumentSymbols),
  8624. findDocumentSymbols2: jsonDocumentSymbols.findDocumentSymbols2.bind(jsonDocumentSymbols),
  8625. findDocumentColors: jsonDocumentSymbols.findDocumentColors.bind(jsonDocumentSymbols),
  8626. getColorPresentations: jsonDocumentSymbols.getColorPresentations.bind(jsonDocumentSymbols),
  8627. doHover: jsonHover.doHover.bind(jsonHover),
  8628. getFoldingRanges: jsonFolding_1.getFoldingRanges,
  8629. getSelectionRanges: jsonSelectionRanges_1.getSelectionRanges,
  8630. findDefinition: function () { return Promise.resolve([]); },
  8631. findLinks: jsonLinks_1.findLinks,
  8632. format: function (d, r, o) {
  8633. var range = undefined;
  8634. if (r) {
  8635. var offset = d.offsetAt(r.start);
  8636. var length = d.offsetAt(r.end) - offset;
  8637. range = { offset: offset, length: length };
  8638. }
  8639. 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' };
  8640. return jsonc_parser_1.format(d.getText(), range, options).map(function (e) {
  8641. return jsonLanguageTypes_1.TextEdit.replace(jsonLanguageTypes_1.Range.create(d.positionAt(e.offset), d.positionAt(e.offset + e.length)), e.content);
  8642. });
  8643. }
  8644. };
  8645. }
  8646. exports.getLanguageService = getLanguageService;
  8647. });
  8648. define('vscode-json-languageservice', ['vscode-json-languageservice/jsonLanguageService'], function (main) { return main; });
  8649. /*---------------------------------------------------------------------------------------------
  8650. * Copyright (c) Microsoft Corporation. All rights reserved.
  8651. * Licensed under the MIT License. See License.txt in the project root for license information.
  8652. *--------------------------------------------------------------------------------------------*/
  8653. define('vs/language/json/languageFeatures',["require", "exports", "./fillers/monaco-editor-core", "vscode-json-languageservice"], function (require, exports, monaco_editor_core_1, jsonService) {
  8654. "use strict";
  8655. Object.defineProperty(exports, "__esModule", { value: true });
  8656. exports.SelectionRangeAdapter = exports.FoldingRangeAdapter = exports.DocumentColorAdapter = exports.DocumentRangeFormattingEditProvider = exports.DocumentFormattingEditProvider = exports.DocumentSymbolAdapter = exports.HoverAdapter = exports.CompletionAdapter = exports.DiagnosticsAdapter = void 0;
  8657. // --- diagnostics --- ---
  8658. var DiagnosticsAdapter = /** @class */ (function () {
  8659. function DiagnosticsAdapter(_languageId, _worker, defaults) {
  8660. var _this = this;
  8661. this._languageId = _languageId;
  8662. this._worker = _worker;
  8663. this._disposables = [];
  8664. this._listener = Object.create(null);
  8665. var onModelAdd = function (model) {
  8666. var modeId = model.getModeId();
  8667. if (modeId !== _this._languageId) {
  8668. return;
  8669. }
  8670. var handle;
  8671. _this._listener[model.uri.toString()] = model.onDidChangeContent(function () {
  8672. clearTimeout(handle);
  8673. handle = setTimeout(function () { return _this._doValidate(model.uri, modeId); }, 500);
  8674. });
  8675. _this._doValidate(model.uri, modeId);
  8676. };
  8677. var onModelRemoved = function (model) {
  8678. monaco_editor_core_1.editor.setModelMarkers(model, _this._languageId, []);
  8679. var uriStr = model.uri.toString();
  8680. var listener = _this._listener[uriStr];
  8681. if (listener) {
  8682. listener.dispose();
  8683. delete _this._listener[uriStr];
  8684. }
  8685. };
  8686. this._disposables.push(monaco_editor_core_1.editor.onDidCreateModel(onModelAdd));
  8687. this._disposables.push(monaco_editor_core_1.editor.onWillDisposeModel(function (model) {
  8688. onModelRemoved(model);
  8689. _this._resetSchema(model.uri);
  8690. }));
  8691. this._disposables.push(monaco_editor_core_1.editor.onDidChangeModelLanguage(function (event) {
  8692. onModelRemoved(event.model);
  8693. onModelAdd(event.model);
  8694. _this._resetSchema(event.model.uri);
  8695. }));
  8696. this._disposables.push(defaults.onDidChange(function (_) {
  8697. monaco_editor_core_1.editor.getModels().forEach(function (model) {
  8698. if (model.getModeId() === _this._languageId) {
  8699. onModelRemoved(model);
  8700. onModelAdd(model);
  8701. }
  8702. });
  8703. }));
  8704. this._disposables.push({
  8705. dispose: function () {
  8706. monaco_editor_core_1.editor.getModels().forEach(onModelRemoved);
  8707. for (var key in _this._listener) {
  8708. _this._listener[key].dispose();
  8709. }
  8710. }
  8711. });
  8712. monaco_editor_core_1.editor.getModels().forEach(onModelAdd);
  8713. }
  8714. DiagnosticsAdapter.prototype.dispose = function () {
  8715. this._disposables.forEach(function (d) { return d && d.dispose(); });
  8716. this._disposables = [];
  8717. };
  8718. DiagnosticsAdapter.prototype._resetSchema = function (resource) {
  8719. this._worker().then(function (worker) {
  8720. worker.resetSchema(resource.toString());
  8721. });
  8722. };
  8723. DiagnosticsAdapter.prototype._doValidate = function (resource, languageId) {
  8724. this._worker(resource)
  8725. .then(function (worker) {
  8726. return worker.doValidation(resource.toString()).then(function (diagnostics) {
  8727. var markers = diagnostics.map(function (d) { return toDiagnostics(resource, d); });
  8728. var model = monaco_editor_core_1.editor.getModel(resource);
  8729. if (model && model.getModeId() === languageId) {
  8730. monaco_editor_core_1.editor.setModelMarkers(model, languageId, markers);
  8731. }
  8732. });
  8733. })
  8734. .then(undefined, function (err) {
  8735. console.error(err);
  8736. });
  8737. };
  8738. return DiagnosticsAdapter;
  8739. }());
  8740. exports.DiagnosticsAdapter = DiagnosticsAdapter;
  8741. function toSeverity(lsSeverity) {
  8742. switch (lsSeverity) {
  8743. case jsonService.DiagnosticSeverity.Error:
  8744. return monaco_editor_core_1.MarkerSeverity.Error;
  8745. case jsonService.DiagnosticSeverity.Warning:
  8746. return monaco_editor_core_1.MarkerSeverity.Warning;
  8747. case jsonService.DiagnosticSeverity.Information:
  8748. return monaco_editor_core_1.MarkerSeverity.Info;
  8749. case jsonService.DiagnosticSeverity.Hint:
  8750. return monaco_editor_core_1.MarkerSeverity.Hint;
  8751. default:
  8752. return monaco_editor_core_1.MarkerSeverity.Info;
  8753. }
  8754. }
  8755. function toDiagnostics(resource, diag) {
  8756. var code = typeof diag.code === 'number' ? String(diag.code) : diag.code;
  8757. return {
  8758. severity: toSeverity(diag.severity),
  8759. startLineNumber: diag.range.start.line + 1,
  8760. startColumn: diag.range.start.character + 1,
  8761. endLineNumber: diag.range.end.line + 1,
  8762. endColumn: diag.range.end.character + 1,
  8763. message: diag.message,
  8764. code: code,
  8765. source: diag.source
  8766. };
  8767. }
  8768. // --- completion ------
  8769. function fromPosition(position) {
  8770. if (!position) {
  8771. return void 0;
  8772. }
  8773. return { character: position.column - 1, line: position.lineNumber - 1 };
  8774. }
  8775. function fromRange(range) {
  8776. if (!range) {
  8777. return void 0;
  8778. }
  8779. return {
  8780. start: {
  8781. line: range.startLineNumber - 1,
  8782. character: range.startColumn - 1
  8783. },
  8784. end: { line: range.endLineNumber - 1, character: range.endColumn - 1 }
  8785. };
  8786. }
  8787. function toRange(range) {
  8788. if (!range) {
  8789. return void 0;
  8790. }
  8791. return new monaco_editor_core_1.Range(range.start.line + 1, range.start.character + 1, range.end.line + 1, range.end.character + 1);
  8792. }
  8793. function isInsertReplaceEdit(edit) {
  8794. return (typeof edit.insert !== 'undefined' &&
  8795. typeof edit.replace !== 'undefined');
  8796. }
  8797. function toCompletionItemKind(kind) {
  8798. var mItemKind = monaco_editor_core_1.languages.CompletionItemKind;
  8799. switch (kind) {
  8800. case jsonService.CompletionItemKind.Text:
  8801. return mItemKind.Text;
  8802. case jsonService.CompletionItemKind.Method:
  8803. return mItemKind.Method;
  8804. case jsonService.CompletionItemKind.Function:
  8805. return mItemKind.Function;
  8806. case jsonService.CompletionItemKind.Constructor:
  8807. return mItemKind.Constructor;
  8808. case jsonService.CompletionItemKind.Field:
  8809. return mItemKind.Field;
  8810. case jsonService.CompletionItemKind.Variable:
  8811. return mItemKind.Variable;
  8812. case jsonService.CompletionItemKind.Class:
  8813. return mItemKind.Class;
  8814. case jsonService.CompletionItemKind.Interface:
  8815. return mItemKind.Interface;
  8816. case jsonService.CompletionItemKind.Module:
  8817. return mItemKind.Module;
  8818. case jsonService.CompletionItemKind.Property:
  8819. return mItemKind.Property;
  8820. case jsonService.CompletionItemKind.Unit:
  8821. return mItemKind.Unit;
  8822. case jsonService.CompletionItemKind.Value:
  8823. return mItemKind.Value;
  8824. case jsonService.CompletionItemKind.Enum:
  8825. return mItemKind.Enum;
  8826. case jsonService.CompletionItemKind.Keyword:
  8827. return mItemKind.Keyword;
  8828. case jsonService.CompletionItemKind.Snippet:
  8829. return mItemKind.Snippet;
  8830. case jsonService.CompletionItemKind.Color:
  8831. return mItemKind.Color;
  8832. case jsonService.CompletionItemKind.File:
  8833. return mItemKind.File;
  8834. case jsonService.CompletionItemKind.Reference:
  8835. return mItemKind.Reference;
  8836. }
  8837. return mItemKind.Property;
  8838. }
  8839. function fromCompletionItemKind(kind) {
  8840. var mItemKind = monaco_editor_core_1.languages.CompletionItemKind;
  8841. switch (kind) {
  8842. case mItemKind.Text:
  8843. return jsonService.CompletionItemKind.Text;
  8844. case mItemKind.Method:
  8845. return jsonService.CompletionItemKind.Method;
  8846. case mItemKind.Function:
  8847. return jsonService.CompletionItemKind.Function;
  8848. case mItemKind.Constructor:
  8849. return jsonService.CompletionItemKind.Constructor;
  8850. case mItemKind.Field:
  8851. return jsonService.CompletionItemKind.Field;
  8852. case mItemKind.Variable:
  8853. return jsonService.CompletionItemKind.Variable;
  8854. case mItemKind.Class:
  8855. return jsonService.CompletionItemKind.Class;
  8856. case mItemKind.Interface:
  8857. return jsonService.CompletionItemKind.Interface;
  8858. case mItemKind.Module:
  8859. return jsonService.CompletionItemKind.Module;
  8860. case mItemKind.Property:
  8861. return jsonService.CompletionItemKind.Property;
  8862. case mItemKind.Unit:
  8863. return jsonService.CompletionItemKind.Unit;
  8864. case mItemKind.Value:
  8865. return jsonService.CompletionItemKind.Value;
  8866. case mItemKind.Enum:
  8867. return jsonService.CompletionItemKind.Enum;
  8868. case mItemKind.Keyword:
  8869. return jsonService.CompletionItemKind.Keyword;
  8870. case mItemKind.Snippet:
  8871. return jsonService.CompletionItemKind.Snippet;
  8872. case mItemKind.Color:
  8873. return jsonService.CompletionItemKind.Color;
  8874. case mItemKind.File:
  8875. return jsonService.CompletionItemKind.File;
  8876. case mItemKind.Reference:
  8877. return jsonService.CompletionItemKind.Reference;
  8878. }
  8879. return jsonService.CompletionItemKind.Property;
  8880. }
  8881. function toTextEdit(textEdit) {
  8882. if (!textEdit) {
  8883. return void 0;
  8884. }
  8885. return {
  8886. range: toRange(textEdit.range),
  8887. text: textEdit.newText
  8888. };
  8889. }
  8890. function toCommand(c) {
  8891. return c && c.command === 'editor.action.triggerSuggest' ? { id: c.command, title: c.title, arguments: c.arguments } : undefined;
  8892. }
  8893. var CompletionAdapter = /** @class */ (function () {
  8894. function CompletionAdapter(_worker) {
  8895. this._worker = _worker;
  8896. }
  8897. Object.defineProperty(CompletionAdapter.prototype, "triggerCharacters", {
  8898. get: function () {
  8899. return [' ', ':', '"'];
  8900. },
  8901. enumerable: false,
  8902. configurable: true
  8903. });
  8904. CompletionAdapter.prototype.provideCompletionItems = function (model, position, context, token) {
  8905. var resource = model.uri;
  8906. return this._worker(resource)
  8907. .then(function (worker) {
  8908. return worker.doComplete(resource.toString(), fromPosition(position));
  8909. })
  8910. .then(function (info) {
  8911. if (!info) {
  8912. return;
  8913. }
  8914. var wordInfo = model.getWordUntilPosition(position);
  8915. var wordRange = new monaco_editor_core_1.Range(position.lineNumber, wordInfo.startColumn, position.lineNumber, wordInfo.endColumn);
  8916. var items = info.items.map(function (entry) {
  8917. var item = {
  8918. label: entry.label,
  8919. insertText: entry.insertText || entry.label,
  8920. sortText: entry.sortText,
  8921. filterText: entry.filterText,
  8922. documentation: entry.documentation,
  8923. detail: entry.detail,
  8924. command: toCommand(entry.command),
  8925. range: wordRange,
  8926. kind: toCompletionItemKind(entry.kind)
  8927. };
  8928. if (entry.textEdit) {
  8929. if (isInsertReplaceEdit(entry.textEdit)) {
  8930. item.range = {
  8931. insert: toRange(entry.textEdit.insert),
  8932. replace: toRange(entry.textEdit.replace)
  8933. };
  8934. }
  8935. else {
  8936. item.range = toRange(entry.textEdit.range);
  8937. }
  8938. item.insertText = entry.textEdit.newText;
  8939. }
  8940. if (entry.additionalTextEdits) {
  8941. item.additionalTextEdits = entry.additionalTextEdits.map(toTextEdit);
  8942. }
  8943. if (entry.insertTextFormat === jsonService.InsertTextFormat.Snippet) {
  8944. item.insertTextRules = monaco_editor_core_1.languages.CompletionItemInsertTextRule.InsertAsSnippet;
  8945. }
  8946. return item;
  8947. });
  8948. return {
  8949. isIncomplete: info.isIncomplete,
  8950. suggestions: items
  8951. };
  8952. });
  8953. };
  8954. return CompletionAdapter;
  8955. }());
  8956. exports.CompletionAdapter = CompletionAdapter;
  8957. function isMarkupContent(thing) {
  8958. return (thing &&
  8959. typeof thing === 'object' &&
  8960. typeof thing.kind === 'string');
  8961. }
  8962. function toMarkdownString(entry) {
  8963. if (typeof entry === 'string') {
  8964. return {
  8965. value: entry
  8966. };
  8967. }
  8968. if (isMarkupContent(entry)) {
  8969. if (entry.kind === 'plaintext') {
  8970. return {
  8971. value: entry.value.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&')
  8972. };
  8973. }
  8974. return {
  8975. value: entry.value
  8976. };
  8977. }
  8978. return { value: '```' + entry.language + '\n' + entry.value + '\n```\n' };
  8979. }
  8980. function toMarkedStringArray(contents) {
  8981. if (!contents) {
  8982. return void 0;
  8983. }
  8984. if (Array.isArray(contents)) {
  8985. return contents.map(toMarkdownString);
  8986. }
  8987. return [toMarkdownString(contents)];
  8988. }
  8989. // --- hover ------
  8990. var HoverAdapter = /** @class */ (function () {
  8991. function HoverAdapter(_worker) {
  8992. this._worker = _worker;
  8993. }
  8994. HoverAdapter.prototype.provideHover = function (model, position, token) {
  8995. var resource = model.uri;
  8996. return this._worker(resource)
  8997. .then(function (worker) {
  8998. return worker.doHover(resource.toString(), fromPosition(position));
  8999. })
  9000. .then(function (info) {
  9001. if (!info) {
  9002. return;
  9003. }
  9004. return {
  9005. range: toRange(info.range),
  9006. contents: toMarkedStringArray(info.contents)
  9007. };
  9008. });
  9009. };
  9010. return HoverAdapter;
  9011. }());
  9012. exports.HoverAdapter = HoverAdapter;
  9013. // --- definition ------
  9014. function toLocation(location) {
  9015. return {
  9016. uri: monaco_editor_core_1.Uri.parse(location.uri),
  9017. range: toRange(location.range)
  9018. };
  9019. }
  9020. // --- document symbols ------
  9021. function toSymbolKind(kind) {
  9022. var mKind = monaco_editor_core_1.languages.SymbolKind;
  9023. switch (kind) {
  9024. case jsonService.SymbolKind.File:
  9025. return mKind.Array;
  9026. case jsonService.SymbolKind.Module:
  9027. return mKind.Module;
  9028. case jsonService.SymbolKind.Namespace:
  9029. return mKind.Namespace;
  9030. case jsonService.SymbolKind.Package:
  9031. return mKind.Package;
  9032. case jsonService.SymbolKind.Class:
  9033. return mKind.Class;
  9034. case jsonService.SymbolKind.Method:
  9035. return mKind.Method;
  9036. case jsonService.SymbolKind.Property:
  9037. return mKind.Property;
  9038. case jsonService.SymbolKind.Field:
  9039. return mKind.Field;
  9040. case jsonService.SymbolKind.Constructor:
  9041. return mKind.Constructor;
  9042. case jsonService.SymbolKind.Enum:
  9043. return mKind.Enum;
  9044. case jsonService.SymbolKind.Interface:
  9045. return mKind.Interface;
  9046. case jsonService.SymbolKind.Function:
  9047. return mKind.Function;
  9048. case jsonService.SymbolKind.Variable:
  9049. return mKind.Variable;
  9050. case jsonService.SymbolKind.Constant:
  9051. return mKind.Constant;
  9052. case jsonService.SymbolKind.String:
  9053. return mKind.String;
  9054. case jsonService.SymbolKind.Number:
  9055. return mKind.Number;
  9056. case jsonService.SymbolKind.Boolean:
  9057. return mKind.Boolean;
  9058. case jsonService.SymbolKind.Array:
  9059. return mKind.Array;
  9060. }
  9061. return mKind.Function;
  9062. }
  9063. var DocumentSymbolAdapter = /** @class */ (function () {
  9064. function DocumentSymbolAdapter(_worker) {
  9065. this._worker = _worker;
  9066. }
  9067. DocumentSymbolAdapter.prototype.provideDocumentSymbols = function (model, token) {
  9068. var resource = model.uri;
  9069. return this._worker(resource)
  9070. .then(function (worker) { return worker.findDocumentSymbols(resource.toString()); })
  9071. .then(function (items) {
  9072. if (!items) {
  9073. return;
  9074. }
  9075. return items.map(function (item) { return ({
  9076. name: item.name,
  9077. detail: '',
  9078. containerName: item.containerName,
  9079. kind: toSymbolKind(item.kind),
  9080. range: toRange(item.location.range),
  9081. selectionRange: toRange(item.location.range),
  9082. tags: []
  9083. }); });
  9084. });
  9085. };
  9086. return DocumentSymbolAdapter;
  9087. }());
  9088. exports.DocumentSymbolAdapter = DocumentSymbolAdapter;
  9089. function fromFormattingOptions(options) {
  9090. return {
  9091. tabSize: options.tabSize,
  9092. insertSpaces: options.insertSpaces
  9093. };
  9094. }
  9095. var DocumentFormattingEditProvider = /** @class */ (function () {
  9096. function DocumentFormattingEditProvider(_worker) {
  9097. this._worker = _worker;
  9098. }
  9099. DocumentFormattingEditProvider.prototype.provideDocumentFormattingEdits = function (model, options, token) {
  9100. var resource = model.uri;
  9101. return this._worker(resource).then(function (worker) {
  9102. return worker
  9103. .format(resource.toString(), null, fromFormattingOptions(options))
  9104. .then(function (edits) {
  9105. if (!edits || edits.length === 0) {
  9106. return;
  9107. }
  9108. return edits.map(toTextEdit);
  9109. });
  9110. });
  9111. };
  9112. return DocumentFormattingEditProvider;
  9113. }());
  9114. exports.DocumentFormattingEditProvider = DocumentFormattingEditProvider;
  9115. var DocumentRangeFormattingEditProvider = /** @class */ (function () {
  9116. function DocumentRangeFormattingEditProvider(_worker) {
  9117. this._worker = _worker;
  9118. }
  9119. DocumentRangeFormattingEditProvider.prototype.provideDocumentRangeFormattingEdits = function (model, range, options, token) {
  9120. var resource = model.uri;
  9121. return this._worker(resource).then(function (worker) {
  9122. return worker
  9123. .format(resource.toString(), fromRange(range), fromFormattingOptions(options))
  9124. .then(function (edits) {
  9125. if (!edits || edits.length === 0) {
  9126. return;
  9127. }
  9128. return edits.map(toTextEdit);
  9129. });
  9130. });
  9131. };
  9132. return DocumentRangeFormattingEditProvider;
  9133. }());
  9134. exports.DocumentRangeFormattingEditProvider = DocumentRangeFormattingEditProvider;
  9135. var DocumentColorAdapter = /** @class */ (function () {
  9136. function DocumentColorAdapter(_worker) {
  9137. this._worker = _worker;
  9138. }
  9139. DocumentColorAdapter.prototype.provideDocumentColors = function (model, token) {
  9140. var resource = model.uri;
  9141. return this._worker(resource)
  9142. .then(function (worker) { return worker.findDocumentColors(resource.toString()); })
  9143. .then(function (infos) {
  9144. if (!infos) {
  9145. return;
  9146. }
  9147. return infos.map(function (item) { return ({
  9148. color: item.color,
  9149. range: toRange(item.range)
  9150. }); });
  9151. });
  9152. };
  9153. DocumentColorAdapter.prototype.provideColorPresentations = function (model, info, token) {
  9154. var resource = model.uri;
  9155. return this._worker(resource)
  9156. .then(function (worker) {
  9157. return worker.getColorPresentations(resource.toString(), info.color, fromRange(info.range));
  9158. })
  9159. .then(function (presentations) {
  9160. if (!presentations) {
  9161. return;
  9162. }
  9163. return presentations.map(function (presentation) {
  9164. var item = {
  9165. label: presentation.label
  9166. };
  9167. if (presentation.textEdit) {
  9168. item.textEdit = toTextEdit(presentation.textEdit);
  9169. }
  9170. if (presentation.additionalTextEdits) {
  9171. item.additionalTextEdits = presentation.additionalTextEdits.map(toTextEdit);
  9172. }
  9173. return item;
  9174. });
  9175. });
  9176. };
  9177. return DocumentColorAdapter;
  9178. }());
  9179. exports.DocumentColorAdapter = DocumentColorAdapter;
  9180. var FoldingRangeAdapter = /** @class */ (function () {
  9181. function FoldingRangeAdapter(_worker) {
  9182. this._worker = _worker;
  9183. }
  9184. FoldingRangeAdapter.prototype.provideFoldingRanges = function (model, context, token) {
  9185. var resource = model.uri;
  9186. return this._worker(resource)
  9187. .then(function (worker) { return worker.getFoldingRanges(resource.toString(), context); })
  9188. .then(function (ranges) {
  9189. if (!ranges) {
  9190. return;
  9191. }
  9192. return ranges.map(function (range) {
  9193. var result = {
  9194. start: range.startLine + 1,
  9195. end: range.endLine + 1
  9196. };
  9197. if (typeof range.kind !== 'undefined') {
  9198. result.kind = toFoldingRangeKind(range.kind);
  9199. }
  9200. return result;
  9201. });
  9202. });
  9203. };
  9204. return FoldingRangeAdapter;
  9205. }());
  9206. exports.FoldingRangeAdapter = FoldingRangeAdapter;
  9207. function toFoldingRangeKind(kind) {
  9208. switch (kind) {
  9209. case jsonService.FoldingRangeKind.Comment:
  9210. return monaco_editor_core_1.languages.FoldingRangeKind.Comment;
  9211. case jsonService.FoldingRangeKind.Imports:
  9212. return monaco_editor_core_1.languages.FoldingRangeKind.Imports;
  9213. case jsonService.FoldingRangeKind.Region:
  9214. return monaco_editor_core_1.languages.FoldingRangeKind.Region;
  9215. }
  9216. return void 0;
  9217. }
  9218. var SelectionRangeAdapter = /** @class */ (function () {
  9219. function SelectionRangeAdapter(_worker) {
  9220. this._worker = _worker;
  9221. }
  9222. SelectionRangeAdapter.prototype.provideSelectionRanges = function (model, positions, token) {
  9223. var resource = model.uri;
  9224. return this._worker(resource)
  9225. .then(function (worker) { return worker.getSelectionRanges(resource.toString(), positions.map(fromPosition)); })
  9226. .then(function (selectionRanges) {
  9227. if (!selectionRanges) {
  9228. return;
  9229. }
  9230. return selectionRanges.map(function (selectionRange) {
  9231. var result = [];
  9232. while (selectionRange) {
  9233. result.push({ range: toRange(selectionRange.range) });
  9234. selectionRange = selectionRange.parent;
  9235. }
  9236. return result;
  9237. });
  9238. });
  9239. };
  9240. return SelectionRangeAdapter;
  9241. }());
  9242. exports.SelectionRangeAdapter = SelectionRangeAdapter;
  9243. });
  9244. /*---------------------------------------------------------------------------------------------
  9245. * Copyright (c) Microsoft Corporation. All rights reserved.
  9246. * Licensed under the MIT License. See License.txt in the project root for license information.
  9247. *--------------------------------------------------------------------------------------------*/
  9248. define('vs/language/json/tokenization',["require", "exports", "jsonc-parser"], function (require, exports, json) {
  9249. "use strict";
  9250. Object.defineProperty(exports, "__esModule", { value: true });
  9251. exports.TOKEN_COMMENT_LINE = exports.TOKEN_COMMENT_BLOCK = exports.TOKEN_PROPERTY_NAME = exports.TOKEN_VALUE_NUMBER = exports.TOKEN_VALUE_STRING = exports.TOKEN_VALUE_NULL = exports.TOKEN_VALUE_BOOLEAN = exports.TOKEN_DELIM_COMMA = exports.TOKEN_DELIM_COLON = exports.TOKEN_DELIM_ARRAY = exports.TOKEN_DELIM_OBJECT = exports.createTokenizationSupport = void 0;
  9252. function createTokenizationSupport(supportComments) {
  9253. return {
  9254. getInitialState: function () { return new JSONState(null, null, false, null); },
  9255. tokenize: function (line, state, offsetDelta, stopAtOffset) {
  9256. return tokenize(supportComments, line, state, offsetDelta, stopAtOffset);
  9257. }
  9258. };
  9259. }
  9260. exports.createTokenizationSupport = createTokenizationSupport;
  9261. exports.TOKEN_DELIM_OBJECT = 'delimiter.bracket.json';
  9262. exports.TOKEN_DELIM_ARRAY = 'delimiter.array.json';
  9263. exports.TOKEN_DELIM_COLON = 'delimiter.colon.json';
  9264. exports.TOKEN_DELIM_COMMA = 'delimiter.comma.json';
  9265. exports.TOKEN_VALUE_BOOLEAN = 'keyword.json';
  9266. exports.TOKEN_VALUE_NULL = 'keyword.json';
  9267. exports.TOKEN_VALUE_STRING = 'string.value.json';
  9268. exports.TOKEN_VALUE_NUMBER = 'number.json';
  9269. exports.TOKEN_PROPERTY_NAME = 'string.key.json';
  9270. exports.TOKEN_COMMENT_BLOCK = 'comment.block.json';
  9271. exports.TOKEN_COMMENT_LINE = 'comment.line.json';
  9272. var ParentsStack = /** @class */ (function () {
  9273. function ParentsStack(parent, type) {
  9274. this.parent = parent;
  9275. this.type = type;
  9276. }
  9277. ParentsStack.pop = function (parents) {
  9278. if (parents) {
  9279. return parents.parent;
  9280. }
  9281. return null;
  9282. };
  9283. ParentsStack.push = function (parents, type) {
  9284. return new ParentsStack(parents, type);
  9285. };
  9286. ParentsStack.equals = function (a, b) {
  9287. if (!a && !b) {
  9288. return true;
  9289. }
  9290. if (!a || !b) {
  9291. return false;
  9292. }
  9293. while (a && b) {
  9294. if (a === b) {
  9295. return true;
  9296. }
  9297. if (a.type !== b.type) {
  9298. return false;
  9299. }
  9300. a = a.parent;
  9301. b = b.parent;
  9302. }
  9303. return true;
  9304. };
  9305. return ParentsStack;
  9306. }());
  9307. var JSONState = /** @class */ (function () {
  9308. function JSONState(state, scanError, lastWasColon, parents) {
  9309. this._state = state;
  9310. this.scanError = scanError;
  9311. this.lastWasColon = lastWasColon;
  9312. this.parents = parents;
  9313. }
  9314. JSONState.prototype.clone = function () {
  9315. return new JSONState(this._state, this.scanError, this.lastWasColon, this.parents);
  9316. };
  9317. JSONState.prototype.equals = function (other) {
  9318. if (other === this) {
  9319. return true;
  9320. }
  9321. if (!other || !(other instanceof JSONState)) {
  9322. return false;
  9323. }
  9324. return (this.scanError === other.scanError &&
  9325. this.lastWasColon === other.lastWasColon &&
  9326. ParentsStack.equals(this.parents, other.parents));
  9327. };
  9328. JSONState.prototype.getStateData = function () {
  9329. return this._state;
  9330. };
  9331. JSONState.prototype.setStateData = function (state) {
  9332. this._state = state;
  9333. };
  9334. return JSONState;
  9335. }());
  9336. function tokenize(comments, line, state, offsetDelta, stopAtOffset) {
  9337. if (offsetDelta === void 0) { offsetDelta = 0; }
  9338. // handle multiline strings and block comments
  9339. var numberOfInsertedCharacters = 0;
  9340. var adjustOffset = false;
  9341. switch (state.scanError) {
  9342. case 2 /* UnexpectedEndOfString */:
  9343. line = '"' + line;
  9344. numberOfInsertedCharacters = 1;
  9345. break;
  9346. case 1 /* UnexpectedEndOfComment */:
  9347. line = '/*' + line;
  9348. numberOfInsertedCharacters = 2;
  9349. break;
  9350. }
  9351. var scanner = json.createScanner(line);
  9352. var lastWasColon = state.lastWasColon;
  9353. var parents = state.parents;
  9354. var ret = {
  9355. tokens: [],
  9356. endState: state.clone()
  9357. };
  9358. while (true) {
  9359. var offset = offsetDelta + scanner.getPosition();
  9360. var type = '';
  9361. var kind = scanner.scan();
  9362. if (kind === 17 /* EOF */) {
  9363. break;
  9364. }
  9365. // Check that the scanner has advanced
  9366. if (offset === offsetDelta + scanner.getPosition()) {
  9367. throw new Error('Scanner did not advance, next 3 characters are: ' + line.substr(scanner.getPosition(), 3));
  9368. }
  9369. // In case we inserted /* or " character, we need to
  9370. // adjust the offset of all tokens (except the first)
  9371. if (adjustOffset) {
  9372. offset -= numberOfInsertedCharacters;
  9373. }
  9374. adjustOffset = numberOfInsertedCharacters > 0;
  9375. // brackets and type
  9376. switch (kind) {
  9377. case 1 /* OpenBraceToken */:
  9378. parents = ParentsStack.push(parents, 0 /* Object */);
  9379. type = exports.TOKEN_DELIM_OBJECT;
  9380. lastWasColon = false;
  9381. break;
  9382. case 2 /* CloseBraceToken */:
  9383. parents = ParentsStack.pop(parents);
  9384. type = exports.TOKEN_DELIM_OBJECT;
  9385. lastWasColon = false;
  9386. break;
  9387. case 3 /* OpenBracketToken */:
  9388. parents = ParentsStack.push(parents, 1 /* Array */);
  9389. type = exports.TOKEN_DELIM_ARRAY;
  9390. lastWasColon = false;
  9391. break;
  9392. case 4 /* CloseBracketToken */:
  9393. parents = ParentsStack.pop(parents);
  9394. type = exports.TOKEN_DELIM_ARRAY;
  9395. lastWasColon = false;
  9396. break;
  9397. case 6 /* ColonToken */:
  9398. type = exports.TOKEN_DELIM_COLON;
  9399. lastWasColon = true;
  9400. break;
  9401. case 5 /* CommaToken */:
  9402. type = exports.TOKEN_DELIM_COMMA;
  9403. lastWasColon = false;
  9404. break;
  9405. case 8 /* TrueKeyword */:
  9406. case 9 /* FalseKeyword */:
  9407. type = exports.TOKEN_VALUE_BOOLEAN;
  9408. lastWasColon = false;
  9409. break;
  9410. case 7 /* NullKeyword */:
  9411. type = exports.TOKEN_VALUE_NULL;
  9412. lastWasColon = false;
  9413. break;
  9414. case 10 /* StringLiteral */:
  9415. var currentParent = parents ? parents.type : 0 /* Object */;
  9416. var inArray = currentParent === 1 /* Array */;
  9417. type =
  9418. lastWasColon || inArray ? exports.TOKEN_VALUE_STRING : exports.TOKEN_PROPERTY_NAME;
  9419. lastWasColon = false;
  9420. break;
  9421. case 11 /* NumericLiteral */:
  9422. type = exports.TOKEN_VALUE_NUMBER;
  9423. lastWasColon = false;
  9424. break;
  9425. }
  9426. // comments, iff enabled
  9427. if (comments) {
  9428. switch (kind) {
  9429. case 12 /* LineCommentTrivia */:
  9430. type = exports.TOKEN_COMMENT_LINE;
  9431. break;
  9432. case 13 /* BlockCommentTrivia */:
  9433. type = exports.TOKEN_COMMENT_BLOCK;
  9434. break;
  9435. }
  9436. }
  9437. ret.endState = new JSONState(state.getStateData(), scanner.getTokenError(), lastWasColon, parents);
  9438. ret.tokens.push({
  9439. startIndex: offset,
  9440. scopes: type
  9441. });
  9442. }
  9443. return ret;
  9444. }
  9445. });
  9446. /*---------------------------------------------------------------------------------------------
  9447. * Copyright (c) Microsoft Corporation. All rights reserved.
  9448. * Licensed under the MIT License. See License.txt in the project root for license information.
  9449. *--------------------------------------------------------------------------------------------*/
  9450. define('vs/language/json/jsonMode',["require", "exports", "./workerManager", "./languageFeatures", "./tokenization", "./fillers/monaco-editor-core"], function (require, exports, workerManager_1, languageFeatures, tokenization_1, monaco_editor_core_1) {
  9451. "use strict";
  9452. Object.defineProperty(exports, "__esModule", { value: true });
  9453. exports.setupMode = void 0;
  9454. function setupMode(defaults) {
  9455. var disposables = [];
  9456. var providers = [];
  9457. var client = new workerManager_1.WorkerManager(defaults);
  9458. disposables.push(client);
  9459. var worker = function () {
  9460. var uris = [];
  9461. for (var _i = 0; _i < arguments.length; _i++) {
  9462. uris[_i] = arguments[_i];
  9463. }
  9464. return client.getLanguageServiceWorker.apply(client, uris);
  9465. };
  9466. function registerProviders() {
  9467. var languageId = defaults.languageId, modeConfiguration = defaults.modeConfiguration;
  9468. disposeAll(providers);
  9469. if (modeConfiguration.documentFormattingEdits) {
  9470. providers.push(monaco_editor_core_1.languages.registerDocumentFormattingEditProvider(languageId, new languageFeatures.DocumentFormattingEditProvider(worker)));
  9471. }
  9472. if (modeConfiguration.documentRangeFormattingEdits) {
  9473. providers.push(monaco_editor_core_1.languages.registerDocumentRangeFormattingEditProvider(languageId, new languageFeatures.DocumentRangeFormattingEditProvider(worker)));
  9474. }
  9475. if (modeConfiguration.completionItems) {
  9476. providers.push(monaco_editor_core_1.languages.registerCompletionItemProvider(languageId, new languageFeatures.CompletionAdapter(worker)));
  9477. }
  9478. if (modeConfiguration.hovers) {
  9479. providers.push(monaco_editor_core_1.languages.registerHoverProvider(languageId, new languageFeatures.HoverAdapter(worker)));
  9480. }
  9481. if (modeConfiguration.documentSymbols) {
  9482. providers.push(monaco_editor_core_1.languages.registerDocumentSymbolProvider(languageId, new languageFeatures.DocumentSymbolAdapter(worker)));
  9483. }
  9484. if (modeConfiguration.tokens) {
  9485. providers.push(monaco_editor_core_1.languages.setTokensProvider(languageId, tokenization_1.createTokenizationSupport(true)));
  9486. }
  9487. if (modeConfiguration.colors) {
  9488. providers.push(monaco_editor_core_1.languages.registerColorProvider(languageId, new languageFeatures.DocumentColorAdapter(worker)));
  9489. }
  9490. if (modeConfiguration.foldingRanges) {
  9491. providers.push(monaco_editor_core_1.languages.registerFoldingRangeProvider(languageId, new languageFeatures.FoldingRangeAdapter(worker)));
  9492. }
  9493. if (modeConfiguration.diagnostics) {
  9494. providers.push(new languageFeatures.DiagnosticsAdapter(languageId, worker, defaults));
  9495. }
  9496. if (modeConfiguration.selectionRanges) {
  9497. providers.push(monaco_editor_core_1.languages.registerSelectionRangeProvider(languageId, new languageFeatures.SelectionRangeAdapter(worker)));
  9498. }
  9499. }
  9500. registerProviders();
  9501. disposables.push(monaco_editor_core_1.languages.setLanguageConfiguration(defaults.languageId, richEditConfiguration));
  9502. var modeConfiguration = defaults.modeConfiguration;
  9503. defaults.onDidChange(function (newDefaults) {
  9504. if (newDefaults.modeConfiguration !== modeConfiguration) {
  9505. modeConfiguration = newDefaults.modeConfiguration;
  9506. registerProviders();
  9507. }
  9508. });
  9509. disposables.push(asDisposable(providers));
  9510. return asDisposable(disposables);
  9511. }
  9512. exports.setupMode = setupMode;
  9513. function asDisposable(disposables) {
  9514. return { dispose: function () { return disposeAll(disposables); } };
  9515. }
  9516. function disposeAll(disposables) {
  9517. while (disposables.length) {
  9518. disposables.pop().dispose();
  9519. }
  9520. }
  9521. var richEditConfiguration = {
  9522. wordPattern: /(-?\d*\.\d\w*)|([^\[\{\]\}\:\"\,\s]+)/g,
  9523. comments: {
  9524. lineComment: '//',
  9525. blockComment: ['/*', '*/']
  9526. },
  9527. brackets: [
  9528. ['{', '}'],
  9529. ['[', ']']
  9530. ],
  9531. autoClosingPairs: [
  9532. { open: '{', close: '}', notIn: ['string'] },
  9533. { open: '[', close: ']', notIn: ['string'] },
  9534. { open: '"', close: '"', notIn: ['string'] }
  9535. ]
  9536. };
  9537. });