jsonMode.js 412 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157
  1. define('vs/language/json/workerManager',["require", "exports"], function (require, exports) {
  2. /*---------------------------------------------------------------------------------------------
  3. * Copyright (c) Microsoft Corporation. All rights reserved.
  4. * Licensed under the MIT License. See License.txt in the project root for license information.
  5. *--------------------------------------------------------------------------------------------*/
  6. 'use strict';
  7. Object.defineProperty(exports, "__esModule", { value: true });
  8. var STOP_WHEN_IDLE_FOR = 2 * 60 * 1000; // 2min
  9. var WorkerManager = /** @class */ (function () {
  10. function WorkerManager(defaults) {
  11. var _this = this;
  12. this._defaults = defaults;
  13. this._worker = null;
  14. this._idleCheckInterval = setInterval(function () { return _this._checkIfIdle(); }, 30 * 1000);
  15. this._lastUsedTime = 0;
  16. this._configChangeListener = this._defaults.onDidChange(function () { return _this._stopWorker(); });
  17. }
  18. WorkerManager.prototype._stopWorker = function () {
  19. if (this._worker) {
  20. this._worker.dispose();
  21. this._worker = null;
  22. }
  23. this._client = null;
  24. };
  25. WorkerManager.prototype.dispose = function () {
  26. clearInterval(this._idleCheckInterval);
  27. this._configChangeListener.dispose();
  28. this._stopWorker();
  29. };
  30. WorkerManager.prototype._checkIfIdle = function () {
  31. if (!this._worker) {
  32. return;
  33. }
  34. var timePassedSinceLastUsed = Date.now() - this._lastUsedTime;
  35. if (timePassedSinceLastUsed > STOP_WHEN_IDLE_FOR) {
  36. this._stopWorker();
  37. }
  38. };
  39. WorkerManager.prototype._getClient = function () {
  40. this._lastUsedTime = Date.now();
  41. if (!this._client) {
  42. this._worker = monaco.editor.createWebWorker({
  43. // module that exports the create() method and returns a `JSONWorker` instance
  44. moduleId: 'vs/language/json/jsonWorker',
  45. label: this._defaults.languageId,
  46. // passed in to the create() method
  47. createData: {
  48. languageSettings: this._defaults.diagnosticsOptions,
  49. languageId: this._defaults.languageId,
  50. enableSchemaRequest: this._defaults.diagnosticsOptions.enableSchemaRequest
  51. }
  52. });
  53. this._client = this._worker.getProxy();
  54. }
  55. return this._client;
  56. };
  57. WorkerManager.prototype.getLanguageServiceWorker = function () {
  58. var _this = this;
  59. var resources = [];
  60. for (var _i = 0; _i < arguments.length; _i++) {
  61. resources[_i] = arguments[_i];
  62. }
  63. var _client;
  64. return this._getClient().then(function (client) {
  65. _client = client;
  66. }).then(function (_) {
  67. return _this._worker.withSyncedResources(resources);
  68. }).then(function (_) { return _client; });
  69. };
  70. return WorkerManager;
  71. }());
  72. exports.WorkerManager = WorkerManager;
  73. });
  74. (function (factory) {
  75. if (typeof module === "object" && typeof module.exports === "object") {
  76. var v = factory(require, exports);
  77. if (v !== undefined) module.exports = v;
  78. }
  79. else if (typeof define === "function" && define.amd) {
  80. define('jsonc-parser/impl/scanner',["require", "exports"], factory);
  81. }
  82. })(function (require, exports) {
  83. /*---------------------------------------------------------------------------------------------
  84. * Copyright (c) Microsoft Corporation. All rights reserved.
  85. * Licensed under the MIT License. See License.txt in the project root for license information.
  86. *--------------------------------------------------------------------------------------------*/
  87. 'use strict';
  88. Object.defineProperty(exports, "__esModule", { value: true });
  89. /**
  90. * Creates a JSON scanner on the given text.
  91. * If ignoreTrivia is set, whitespaces or comments are ignored.
  92. */
  93. function createScanner(text, ignoreTrivia) {
  94. if (ignoreTrivia === void 0) { ignoreTrivia = false; }
  95. var len = text.length;
  96. var pos = 0, value = '', tokenOffset = 0, token = 16 /* Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* None */;
  97. function scanHexDigits(count, exact) {
  98. var digits = 0;
  99. var value = 0;
  100. while (digits < count || !exact) {
  101. var ch = text.charCodeAt(pos);
  102. if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) {
  103. value = value * 16 + ch - 48 /* _0 */;
  104. }
  105. else if (ch >= 65 /* A */ && ch <= 70 /* F */) {
  106. value = value * 16 + ch - 65 /* A */ + 10;
  107. }
  108. else if (ch >= 97 /* a */ && ch <= 102 /* f */) {
  109. value = value * 16 + ch - 97 /* a */ + 10;
  110. }
  111. else {
  112. break;
  113. }
  114. pos++;
  115. digits++;
  116. }
  117. if (digits < count) {
  118. value = -1;
  119. }
  120. return value;
  121. }
  122. function setPosition(newPosition) {
  123. pos = newPosition;
  124. value = '';
  125. tokenOffset = 0;
  126. token = 16 /* Unknown */;
  127. scanError = 0 /* None */;
  128. }
  129. function scanNumber() {
  130. var start = pos;
  131. if (text.charCodeAt(pos) === 48 /* _0 */) {
  132. pos++;
  133. }
  134. else {
  135. pos++;
  136. while (pos < text.length && isDigit(text.charCodeAt(pos))) {
  137. pos++;
  138. }
  139. }
  140. if (pos < text.length && text.charCodeAt(pos) === 46 /* dot */) {
  141. pos++;
  142. if (pos < text.length && isDigit(text.charCodeAt(pos))) {
  143. pos++;
  144. while (pos < text.length && isDigit(text.charCodeAt(pos))) {
  145. pos++;
  146. }
  147. }
  148. else {
  149. scanError = 3 /* UnexpectedEndOfNumber */;
  150. return text.substring(start, pos);
  151. }
  152. }
  153. var end = pos;
  154. if (pos < text.length && (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */)) {
  155. pos++;
  156. if (pos < text.length && text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) {
  157. pos++;
  158. }
  159. if (pos < text.length && isDigit(text.charCodeAt(pos))) {
  160. pos++;
  161. while (pos < text.length && isDigit(text.charCodeAt(pos))) {
  162. pos++;
  163. }
  164. end = pos;
  165. }
  166. else {
  167. scanError = 3 /* UnexpectedEndOfNumber */;
  168. }
  169. }
  170. return text.substring(start, end);
  171. }
  172. function scanString() {
  173. var result = '', start = pos;
  174. while (true) {
  175. if (pos >= len) {
  176. result += text.substring(start, pos);
  177. scanError = 2 /* UnexpectedEndOfString */;
  178. break;
  179. }
  180. var ch = text.charCodeAt(pos);
  181. if (ch === 34 /* doubleQuote */) {
  182. result += text.substring(start, pos);
  183. pos++;
  184. break;
  185. }
  186. if (ch === 92 /* backslash */) {
  187. result += text.substring(start, pos);
  188. pos++;
  189. if (pos >= len) {
  190. scanError = 2 /* UnexpectedEndOfString */;
  191. break;
  192. }
  193. var ch2 = text.charCodeAt(pos++);
  194. switch (ch2) {
  195. case 34 /* doubleQuote */:
  196. result += '\"';
  197. break;
  198. case 92 /* backslash */:
  199. result += '\\';
  200. break;
  201. case 47 /* slash */:
  202. result += '/';
  203. break;
  204. case 98 /* b */:
  205. result += '\b';
  206. break;
  207. case 102 /* f */:
  208. result += '\f';
  209. break;
  210. case 110 /* n */:
  211. result += '\n';
  212. break;
  213. case 114 /* r */:
  214. result += '\r';
  215. break;
  216. case 116 /* t */:
  217. result += '\t';
  218. break;
  219. case 117 /* u */:
  220. var ch3 = scanHexDigits(4, true);
  221. if (ch3 >= 0) {
  222. result += String.fromCharCode(ch3);
  223. }
  224. else {
  225. scanError = 4 /* InvalidUnicode */;
  226. }
  227. break;
  228. default:
  229. scanError = 5 /* InvalidEscapeCharacter */;
  230. }
  231. start = pos;
  232. continue;
  233. }
  234. if (ch >= 0 && ch <= 0x1f) {
  235. if (isLineBreak(ch)) {
  236. result += text.substring(start, pos);
  237. scanError = 2 /* UnexpectedEndOfString */;
  238. break;
  239. }
  240. else {
  241. scanError = 6 /* InvalidCharacter */;
  242. // mark as error but continue with string
  243. }
  244. }
  245. pos++;
  246. }
  247. return result;
  248. }
  249. function scanNext() {
  250. value = '';
  251. scanError = 0 /* None */;
  252. tokenOffset = pos;
  253. lineStartOffset = lineNumber;
  254. prevTokenLineStartOffset = tokenLineStartOffset;
  255. if (pos >= len) {
  256. // at the end
  257. tokenOffset = len;
  258. return token = 17 /* EOF */;
  259. }
  260. var code = text.charCodeAt(pos);
  261. // trivia: whitespace
  262. if (isWhiteSpace(code)) {
  263. do {
  264. pos++;
  265. value += String.fromCharCode(code);
  266. code = text.charCodeAt(pos);
  267. } while (isWhiteSpace(code));
  268. return token = 15 /* Trivia */;
  269. }
  270. // trivia: newlines
  271. if (isLineBreak(code)) {
  272. pos++;
  273. value += String.fromCharCode(code);
  274. if (code === 13 /* carriageReturn */ && text.charCodeAt(pos) === 10 /* lineFeed */) {
  275. pos++;
  276. value += '\n';
  277. }
  278. lineNumber++;
  279. tokenLineStartOffset = pos;
  280. return token = 14 /* LineBreakTrivia */;
  281. }
  282. switch (code) {
  283. // tokens: []{}:,
  284. case 123 /* openBrace */:
  285. pos++;
  286. return token = 1 /* OpenBraceToken */;
  287. case 125 /* closeBrace */:
  288. pos++;
  289. return token = 2 /* CloseBraceToken */;
  290. case 91 /* openBracket */:
  291. pos++;
  292. return token = 3 /* OpenBracketToken */;
  293. case 93 /* closeBracket */:
  294. pos++;
  295. return token = 4 /* CloseBracketToken */;
  296. case 58 /* colon */:
  297. pos++;
  298. return token = 6 /* ColonToken */;
  299. case 44 /* comma */:
  300. pos++;
  301. return token = 5 /* CommaToken */;
  302. // strings
  303. case 34 /* doubleQuote */:
  304. pos++;
  305. value = scanString();
  306. return token = 10 /* StringLiteral */;
  307. // comments
  308. case 47 /* slash */:
  309. var start = pos - 1;
  310. // Single-line comment
  311. if (text.charCodeAt(pos + 1) === 47 /* slash */) {
  312. pos += 2;
  313. while (pos < len) {
  314. if (isLineBreak(text.charCodeAt(pos))) {
  315. break;
  316. }
  317. pos++;
  318. }
  319. value = text.substring(start, pos);
  320. return token = 12 /* LineCommentTrivia */;
  321. }
  322. // Multi-line comment
  323. if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
  324. pos += 2;
  325. var safeLength = len - 1; // For lookahead.
  326. var commentClosed = false;
  327. while (pos < safeLength) {
  328. var ch = text.charCodeAt(pos);
  329. if (ch === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
  330. pos += 2;
  331. commentClosed = true;
  332. break;
  333. }
  334. pos++;
  335. if (isLineBreak(ch)) {
  336. if (ch === 13 /* carriageReturn */ && text.charCodeAt(pos) === 10 /* lineFeed */) {
  337. pos++;
  338. }
  339. lineNumber++;
  340. tokenLineStartOffset = pos;
  341. }
  342. }
  343. if (!commentClosed) {
  344. pos++;
  345. scanError = 1 /* UnexpectedEndOfComment */;
  346. }
  347. value = text.substring(start, pos);
  348. return token = 13 /* BlockCommentTrivia */;
  349. }
  350. // just a single slash
  351. value += String.fromCharCode(code);
  352. pos++;
  353. return token = 16 /* Unknown */;
  354. // numbers
  355. case 45 /* minus */:
  356. value += String.fromCharCode(code);
  357. pos++;
  358. if (pos === len || !isDigit(text.charCodeAt(pos))) {
  359. return token = 16 /* Unknown */;
  360. }
  361. // found a minus, followed by a number so
  362. // we fall through to proceed with scanning
  363. // numbers
  364. case 48 /* _0 */:
  365. case 49 /* _1 */:
  366. case 50 /* _2 */:
  367. case 51 /* _3 */:
  368. case 52 /* _4 */:
  369. case 53 /* _5 */:
  370. case 54 /* _6 */:
  371. case 55 /* _7 */:
  372. case 56 /* _8 */:
  373. case 57 /* _9 */:
  374. value += scanNumber();
  375. return token = 11 /* NumericLiteral */;
  376. // literals and unknown symbols
  377. default:
  378. // is a literal? Read the full word.
  379. while (pos < len && isUnknownContentCharacter(code)) {
  380. pos++;
  381. code = text.charCodeAt(pos);
  382. }
  383. if (tokenOffset !== pos) {
  384. value = text.substring(tokenOffset, pos);
  385. // keywords: true, false, null
  386. switch (value) {
  387. case 'true': return token = 8 /* TrueKeyword */;
  388. case 'false': return token = 9 /* FalseKeyword */;
  389. case 'null': return token = 7 /* NullKeyword */;
  390. }
  391. return token = 16 /* Unknown */;
  392. }
  393. // some
  394. value += String.fromCharCode(code);
  395. pos++;
  396. return token = 16 /* Unknown */;
  397. }
  398. }
  399. function isUnknownContentCharacter(code) {
  400. if (isWhiteSpace(code) || isLineBreak(code)) {
  401. return false;
  402. }
  403. switch (code) {
  404. case 125 /* closeBrace */:
  405. case 93 /* closeBracket */:
  406. case 123 /* openBrace */:
  407. case 91 /* openBracket */:
  408. case 34 /* doubleQuote */:
  409. case 58 /* colon */:
  410. case 44 /* comma */:
  411. case 47 /* slash */:
  412. return false;
  413. }
  414. return true;
  415. }
  416. function scanNextNonTrivia() {
  417. var result;
  418. do {
  419. result = scanNext();
  420. } while (result >= 12 /* LineCommentTrivia */ && result <= 15 /* Trivia */);
  421. return result;
  422. }
  423. return {
  424. setPosition: setPosition,
  425. getPosition: function () { return pos; },
  426. scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
  427. getToken: function () { return token; },
  428. getTokenValue: function () { return value; },
  429. getTokenOffset: function () { return tokenOffset; },
  430. getTokenLength: function () { return pos - tokenOffset; },
  431. getTokenStartLine: function () { return lineStartOffset; },
  432. getTokenStartCharacter: function () { return tokenOffset - prevTokenLineStartOffset; },
  433. getTokenError: function () { return scanError; },
  434. };
  435. }
  436. exports.createScanner = createScanner;
  437. function isWhiteSpace(ch) {
  438. return ch === 32 /* space */ || ch === 9 /* tab */ || ch === 11 /* verticalTab */ || ch === 12 /* formFeed */ ||
  439. ch === 160 /* nonBreakingSpace */ || ch === 5760 /* ogham */ || ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
  440. ch === 8239 /* narrowNoBreakSpace */ || ch === 8287 /* mathematicalSpace */ || ch === 12288 /* ideographicSpace */ || ch === 65279 /* byteOrderMark */;
  441. }
  442. function isLineBreak(ch) {
  443. return ch === 10 /* lineFeed */ || ch === 13 /* carriageReturn */ || ch === 8232 /* lineSeparator */ || ch === 8233 /* paragraphSeparator */;
  444. }
  445. function isDigit(ch) {
  446. return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
  447. }
  448. });
  449. (function (factory) {
  450. if (typeof module === "object" && typeof module.exports === "object") {
  451. var v = factory(require, exports);
  452. if (v !== undefined) module.exports = v;
  453. }
  454. else if (typeof define === "function" && define.amd) {
  455. define('jsonc-parser/impl/format',["require", "exports", "./scanner"], factory);
  456. }
  457. })(function (require, exports) {
  458. /*---------------------------------------------------------------------------------------------
  459. * Copyright (c) Microsoft Corporation. All rights reserved.
  460. * Licensed under the MIT License. See License.txt in the project root for license information.
  461. *--------------------------------------------------------------------------------------------*/
  462. 'use strict';
  463. Object.defineProperty(exports, "__esModule", { value: true });
  464. var scanner_1 = require("./scanner");
  465. function format(documentText, range, options) {
  466. var initialIndentLevel;
  467. var formatText;
  468. var formatTextStart;
  469. var rangeStart;
  470. var rangeEnd;
  471. if (range) {
  472. rangeStart = range.offset;
  473. rangeEnd = rangeStart + range.length;
  474. formatTextStart = rangeStart;
  475. while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {
  476. formatTextStart--;
  477. }
  478. var endOffset = rangeEnd;
  479. while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {
  480. endOffset++;
  481. }
  482. formatText = documentText.substring(formatTextStart, endOffset);
  483. initialIndentLevel = computeIndentLevel(formatText, options);
  484. }
  485. else {
  486. formatText = documentText;
  487. initialIndentLevel = 0;
  488. formatTextStart = 0;
  489. rangeStart = 0;
  490. rangeEnd = documentText.length;
  491. }
  492. var eol = getEOL(options, documentText);
  493. var lineBreak = false;
  494. var indentLevel = 0;
  495. var indentValue;
  496. if (options.insertSpaces) {
  497. indentValue = repeat(' ', options.tabSize || 4);
  498. }
  499. else {
  500. indentValue = '\t';
  501. }
  502. var scanner = scanner_1.createScanner(formatText, false);
  503. var hasError = false;
  504. function newLineAndIndent() {
  505. return eol + repeat(indentValue, initialIndentLevel + indentLevel);
  506. }
  507. function scanNext() {
  508. var token = scanner.scan();
  509. lineBreak = false;
  510. while (token === 15 /* Trivia */ || token === 14 /* LineBreakTrivia */) {
  511. lineBreak = lineBreak || (token === 14 /* LineBreakTrivia */);
  512. token = scanner.scan();
  513. }
  514. hasError = token === 16 /* Unknown */ || scanner.getTokenError() !== 0 /* None */;
  515. return token;
  516. }
  517. var editOperations = [];
  518. function addEdit(text, startOffset, endOffset) {
  519. if (!hasError && startOffset < rangeEnd && endOffset > rangeStart && documentText.substring(startOffset, endOffset) !== text) {
  520. editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });
  521. }
  522. }
  523. var firstToken = scanNext();
  524. if (firstToken !== 17 /* EOF */) {
  525. var firstTokenStart = scanner.getTokenOffset() + formatTextStart;
  526. var initialIndent = repeat(indentValue, initialIndentLevel);
  527. addEdit(initialIndent, formatTextStart, firstTokenStart);
  528. }
  529. while (firstToken !== 17 /* EOF */) {
  530. var firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
  531. var secondToken = scanNext();
  532. var replaceContent = '';
  533. while (!lineBreak && (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */)) {
  534. // comments on the same line: keep them on the same line, but ignore them otherwise
  535. var commentTokenStart = scanner.getTokenOffset() + formatTextStart;
  536. addEdit(' ', firstTokenEnd, commentTokenStart);
  537. firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
  538. replaceContent = secondToken === 12 /* LineCommentTrivia */ ? newLineAndIndent() : '';
  539. secondToken = scanNext();
  540. }
  541. if (secondToken === 2 /* CloseBraceToken */) {
  542. if (firstToken !== 1 /* OpenBraceToken */) {
  543. indentLevel--;
  544. replaceContent = newLineAndIndent();
  545. }
  546. }
  547. else if (secondToken === 4 /* CloseBracketToken */) {
  548. if (firstToken !== 3 /* OpenBracketToken */) {
  549. indentLevel--;
  550. replaceContent = newLineAndIndent();
  551. }
  552. }
  553. else {
  554. switch (firstToken) {
  555. case 3 /* OpenBracketToken */:
  556. case 1 /* OpenBraceToken */:
  557. indentLevel++;
  558. replaceContent = newLineAndIndent();
  559. break;
  560. case 5 /* CommaToken */:
  561. case 12 /* LineCommentTrivia */:
  562. replaceContent = newLineAndIndent();
  563. break;
  564. case 13 /* BlockCommentTrivia */:
  565. if (lineBreak) {
  566. replaceContent = newLineAndIndent();
  567. }
  568. else {
  569. // symbol following comment on the same line: keep on same line, separate with ' '
  570. replaceContent = ' ';
  571. }
  572. break;
  573. case 6 /* ColonToken */:
  574. replaceContent = ' ';
  575. break;
  576. case 10 /* StringLiteral */:
  577. if (secondToken === 6 /* ColonToken */) {
  578. replaceContent = '';
  579. break;
  580. }
  581. // fall through
  582. case 7 /* NullKeyword */:
  583. case 8 /* TrueKeyword */:
  584. case 9 /* FalseKeyword */:
  585. case 11 /* NumericLiteral */:
  586. case 2 /* CloseBraceToken */:
  587. case 4 /* CloseBracketToken */:
  588. if (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */) {
  589. replaceContent = ' ';
  590. }
  591. else if (secondToken !== 5 /* CommaToken */ && secondToken !== 17 /* EOF */) {
  592. hasError = true;
  593. }
  594. break;
  595. case 16 /* Unknown */:
  596. hasError = true;
  597. break;
  598. }
  599. if (lineBreak && (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */)) {
  600. replaceContent = newLineAndIndent();
  601. }
  602. }
  603. var secondTokenStart = scanner.getTokenOffset() + formatTextStart;
  604. addEdit(replaceContent, firstTokenEnd, secondTokenStart);
  605. firstToken = secondToken;
  606. }
  607. return editOperations;
  608. }
  609. exports.format = format;
  610. function repeat(s, count) {
  611. var result = '';
  612. for (var i = 0; i < count; i++) {
  613. result += s;
  614. }
  615. return result;
  616. }
  617. function computeIndentLevel(content, options) {
  618. var i = 0;
  619. var nChars = 0;
  620. var tabSize = options.tabSize || 4;
  621. while (i < content.length) {
  622. var ch = content.charAt(i);
  623. if (ch === ' ') {
  624. nChars++;
  625. }
  626. else if (ch === '\t') {
  627. nChars += tabSize;
  628. }
  629. else {
  630. break;
  631. }
  632. i++;
  633. }
  634. return Math.floor(nChars / tabSize);
  635. }
  636. function getEOL(options, text) {
  637. for (var i = 0; i < text.length; i++) {
  638. var ch = text.charAt(i);
  639. if (ch === '\r') {
  640. if (i + 1 < text.length && text.charAt(i + 1) === '\n') {
  641. return '\r\n';
  642. }
  643. return '\r';
  644. }
  645. else if (ch === '\n') {
  646. return '\n';
  647. }
  648. }
  649. return (options && options.eol) || '\n';
  650. }
  651. function isEOL(text, offset) {
  652. return '\r\n'.indexOf(text.charAt(offset)) !== -1;
  653. }
  654. exports.isEOL = isEOL;
  655. });
  656. (function (factory) {
  657. if (typeof module === "object" && typeof module.exports === "object") {
  658. var v = factory(require, exports);
  659. if (v !== undefined) module.exports = v;
  660. }
  661. else if (typeof define === "function" && define.amd) {
  662. define('jsonc-parser/impl/parser',["require", "exports", "./scanner"], factory);
  663. }
  664. })(function (require, exports) {
  665. /*---------------------------------------------------------------------------------------------
  666. * Copyright (c) Microsoft Corporation. All rights reserved.
  667. * Licensed under the MIT License. See License.txt in the project root for license information.
  668. *--------------------------------------------------------------------------------------------*/
  669. 'use strict';
  670. Object.defineProperty(exports, "__esModule", { value: true });
  671. var scanner_1 = require("./scanner");
  672. var ParseOptions;
  673. (function (ParseOptions) {
  674. ParseOptions.DEFAULT = {
  675. allowTrailingComma: false
  676. };
  677. })(ParseOptions || (ParseOptions = {}));
  678. /**
  679. * 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.
  680. */
  681. function getLocation(text, position) {
  682. var segments = []; // strings or numbers
  683. var earlyReturnException = new Object();
  684. var previousNode = undefined;
  685. var previousNodeInst = {
  686. value: {},
  687. offset: 0,
  688. length: 0,
  689. type: 'object',
  690. parent: undefined
  691. };
  692. var isAtPropertyKey = false;
  693. function setPreviousNode(value, offset, length, type) {
  694. previousNodeInst.value = value;
  695. previousNodeInst.offset = offset;
  696. previousNodeInst.length = length;
  697. previousNodeInst.type = type;
  698. previousNodeInst.colonOffset = undefined;
  699. previousNode = previousNodeInst;
  700. }
  701. try {
  702. visit(text, {
  703. onObjectBegin: function (offset, length) {
  704. if (position <= offset) {
  705. throw earlyReturnException;
  706. }
  707. previousNode = undefined;
  708. isAtPropertyKey = position > offset;
  709. segments.push(''); // push a placeholder (will be replaced)
  710. },
  711. onObjectProperty: function (name, offset, length) {
  712. if (position < offset) {
  713. throw earlyReturnException;
  714. }
  715. setPreviousNode(name, offset, length, 'property');
  716. segments[segments.length - 1] = name;
  717. if (position <= offset + length) {
  718. throw earlyReturnException;
  719. }
  720. },
  721. onObjectEnd: function (offset, length) {
  722. if (position <= offset) {
  723. throw earlyReturnException;
  724. }
  725. previousNode = undefined;
  726. segments.pop();
  727. },
  728. onArrayBegin: function (offset, length) {
  729. if (position <= offset) {
  730. throw earlyReturnException;
  731. }
  732. previousNode = undefined;
  733. segments.push(0);
  734. },
  735. onArrayEnd: function (offset, length) {
  736. if (position <= offset) {
  737. throw earlyReturnException;
  738. }
  739. previousNode = undefined;
  740. segments.pop();
  741. },
  742. onLiteralValue: function (value, offset, length) {
  743. if (position < offset) {
  744. throw earlyReturnException;
  745. }
  746. setPreviousNode(value, offset, length, getNodeType(value));
  747. if (position <= offset + length) {
  748. throw earlyReturnException;
  749. }
  750. },
  751. onSeparator: function (sep, offset, length) {
  752. if (position <= offset) {
  753. throw earlyReturnException;
  754. }
  755. if (sep === ':' && previousNode && previousNode.type === 'property') {
  756. previousNode.colonOffset = offset;
  757. isAtPropertyKey = false;
  758. previousNode = undefined;
  759. }
  760. else if (sep === ',') {
  761. var last = segments[segments.length - 1];
  762. if (typeof last === 'number') {
  763. segments[segments.length - 1] = last + 1;
  764. }
  765. else {
  766. isAtPropertyKey = true;
  767. segments[segments.length - 1] = '';
  768. }
  769. previousNode = undefined;
  770. }
  771. }
  772. });
  773. }
  774. catch (e) {
  775. if (e !== earlyReturnException) {
  776. throw e;
  777. }
  778. }
  779. return {
  780. path: segments,
  781. previousNode: previousNode,
  782. isAtPropertyKey: isAtPropertyKey,
  783. matches: function (pattern) {
  784. var k = 0;
  785. for (var i = 0; k < pattern.length && i < segments.length; i++) {
  786. if (pattern[k] === segments[i] || pattern[k] === '*') {
  787. k++;
  788. }
  789. else if (pattern[k] !== '**') {
  790. return false;
  791. }
  792. }
  793. return k === pattern.length;
  794. }
  795. };
  796. }
  797. exports.getLocation = getLocation;
  798. /**
  799. * 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.
  800. * Therefore always check the errors list to find out if the input was valid.
  801. */
  802. function parse(text, errors, options) {
  803. if (errors === void 0) { errors = []; }
  804. if (options === void 0) { options = ParseOptions.DEFAULT; }
  805. var currentProperty = null;
  806. var currentParent = [];
  807. var previousParents = [];
  808. function onValue(value) {
  809. if (Array.isArray(currentParent)) {
  810. currentParent.push(value);
  811. }
  812. else if (currentProperty !== null) {
  813. currentParent[currentProperty] = value;
  814. }
  815. }
  816. var visitor = {
  817. onObjectBegin: function () {
  818. var object = {};
  819. onValue(object);
  820. previousParents.push(currentParent);
  821. currentParent = object;
  822. currentProperty = null;
  823. },
  824. onObjectProperty: function (name) {
  825. currentProperty = name;
  826. },
  827. onObjectEnd: function () {
  828. currentParent = previousParents.pop();
  829. },
  830. onArrayBegin: function () {
  831. var array = [];
  832. onValue(array);
  833. previousParents.push(currentParent);
  834. currentParent = array;
  835. currentProperty = null;
  836. },
  837. onArrayEnd: function () {
  838. currentParent = previousParents.pop();
  839. },
  840. onLiteralValue: onValue,
  841. onError: function (error, offset, length) {
  842. errors.push({ error: error, offset: offset, length: length });
  843. }
  844. };
  845. visit(text, visitor, options);
  846. return currentParent[0];
  847. }
  848. exports.parse = parse;
  849. /**
  850. * 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.
  851. */
  852. function parseTree(text, errors, options) {
  853. if (errors === void 0) { errors = []; }
  854. if (options === void 0) { options = ParseOptions.DEFAULT; }
  855. var currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root
  856. function ensurePropertyComplete(endOffset) {
  857. if (currentParent.type === 'property') {
  858. currentParent.length = endOffset - currentParent.offset;
  859. currentParent = currentParent.parent;
  860. }
  861. }
  862. function onValue(valueNode) {
  863. currentParent.children.push(valueNode);
  864. return valueNode;
  865. }
  866. var visitor = {
  867. onObjectBegin: function (offset) {
  868. currentParent = onValue({ type: 'object', offset: offset, length: -1, parent: currentParent, children: [] });
  869. },
  870. onObjectProperty: function (name, offset, length) {
  871. currentParent = onValue({ type: 'property', offset: offset, length: -1, parent: currentParent, children: [] });
  872. currentParent.children.push({ type: 'string', value: name, offset: offset, length: length, parent: currentParent });
  873. },
  874. onObjectEnd: function (offset, length) {
  875. currentParent.length = offset + length - currentParent.offset;
  876. currentParent = currentParent.parent;
  877. ensurePropertyComplete(offset + length);
  878. },
  879. onArrayBegin: function (offset, length) {
  880. currentParent = onValue({ type: 'array', offset: offset, length: -1, parent: currentParent, children: [] });
  881. },
  882. onArrayEnd: function (offset, length) {
  883. currentParent.length = offset + length - currentParent.offset;
  884. currentParent = currentParent.parent;
  885. ensurePropertyComplete(offset + length);
  886. },
  887. onLiteralValue: function (value, offset, length) {
  888. onValue({ type: getNodeType(value), offset: offset, length: length, parent: currentParent, value: value });
  889. ensurePropertyComplete(offset + length);
  890. },
  891. onSeparator: function (sep, offset, length) {
  892. if (currentParent.type === 'property') {
  893. if (sep === ':') {
  894. currentParent.colonOffset = offset;
  895. }
  896. else if (sep === ',') {
  897. ensurePropertyComplete(offset);
  898. }
  899. }
  900. },
  901. onError: function (error, offset, length) {
  902. errors.push({ error: error, offset: offset, length: length });
  903. }
  904. };
  905. visit(text, visitor, options);
  906. var result = currentParent.children[0];
  907. if (result) {
  908. delete result.parent;
  909. }
  910. return result;
  911. }
  912. exports.parseTree = parseTree;
  913. /**
  914. * Finds the node at the given path in a JSON DOM.
  915. */
  916. function findNodeAtLocation(root, path) {
  917. if (!root) {
  918. return undefined;
  919. }
  920. var node = root;
  921. for (var _i = 0, path_1 = path; _i < path_1.length; _i++) {
  922. var segment = path_1[_i];
  923. if (typeof segment === 'string') {
  924. if (node.type !== 'object' || !Array.isArray(node.children)) {
  925. return undefined;
  926. }
  927. var found = false;
  928. for (var _a = 0, _b = node.children; _a < _b.length; _a++) {
  929. var propertyNode = _b[_a];
  930. if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment) {
  931. node = propertyNode.children[1];
  932. found = true;
  933. break;
  934. }
  935. }
  936. if (!found) {
  937. return undefined;
  938. }
  939. }
  940. else {
  941. var index = segment;
  942. if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {
  943. return undefined;
  944. }
  945. node = node.children[index];
  946. }
  947. }
  948. return node;
  949. }
  950. exports.findNodeAtLocation = findNodeAtLocation;
  951. /**
  952. * Gets the JSON path of the given JSON DOM node
  953. */
  954. function getNodePath(node) {
  955. if (!node.parent || !node.parent.children) {
  956. return [];
  957. }
  958. var path = getNodePath(node.parent);
  959. if (node.parent.type === 'property') {
  960. var key = node.parent.children[0].value;
  961. path.push(key);
  962. }
  963. else if (node.parent.type === 'array') {
  964. var index = node.parent.children.indexOf(node);
  965. if (index !== -1) {
  966. path.push(index);
  967. }
  968. }
  969. return path;
  970. }
  971. exports.getNodePath = getNodePath;
  972. /**
  973. * Evaluates the JavaScript object of the given JSON DOM node
  974. */
  975. function getNodeValue(node) {
  976. switch (node.type) {
  977. case 'array':
  978. return node.children.map(getNodeValue);
  979. case 'object':
  980. var obj = Object.create(null);
  981. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  982. var prop = _a[_i];
  983. var valueNode = prop.children[1];
  984. if (valueNode) {
  985. obj[prop.children[0].value] = getNodeValue(valueNode);
  986. }
  987. }
  988. return obj;
  989. case 'null':
  990. case 'string':
  991. case 'number':
  992. case 'boolean':
  993. return node.value;
  994. default:
  995. return undefined;
  996. }
  997. }
  998. exports.getNodeValue = getNodeValue;
  999. function contains(node, offset, includeRightBound) {
  1000. if (includeRightBound === void 0) { includeRightBound = false; }
  1001. return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length));
  1002. }
  1003. exports.contains = contains;
  1004. /**
  1005. * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.
  1006. */
  1007. function findNodeAtOffset(node, offset, includeRightBound) {
  1008. if (includeRightBound === void 0) { includeRightBound = false; }
  1009. if (contains(node, offset, includeRightBound)) {
  1010. var children = node.children;
  1011. if (Array.isArray(children)) {
  1012. for (var i = 0; i < children.length && children[i].offset <= offset; i++) {
  1013. var item = findNodeAtOffset(children[i], offset, includeRightBound);
  1014. if (item) {
  1015. return item;
  1016. }
  1017. }
  1018. }
  1019. return node;
  1020. }
  1021. return undefined;
  1022. }
  1023. exports.findNodeAtOffset = findNodeAtOffset;
  1024. /**
  1025. * Parses the given text and invokes the visitor functions for each object, array and literal reached.
  1026. */
  1027. function visit(text, visitor, options) {
  1028. if (options === void 0) { options = ParseOptions.DEFAULT; }
  1029. var _scanner = scanner_1.createScanner(text, false);
  1030. function toNoArgVisit(visitFunction) {
  1031. return visitFunction ? function () { return visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); } : function () { return true; };
  1032. }
  1033. function toOneArgVisit(visitFunction) {
  1034. return visitFunction ? function (arg) { return visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); } : function () { return true; };
  1035. }
  1036. 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);
  1037. var disallowComments = options && options.disallowComments;
  1038. var allowTrailingComma = options && options.allowTrailingComma;
  1039. function scanNext() {
  1040. while (true) {
  1041. var token = _scanner.scan();
  1042. switch (_scanner.getTokenError()) {
  1043. case 4 /* InvalidUnicode */:
  1044. handleError(14 /* InvalidUnicode */);
  1045. break;
  1046. case 5 /* InvalidEscapeCharacter */:
  1047. handleError(15 /* InvalidEscapeCharacter */);
  1048. break;
  1049. case 3 /* UnexpectedEndOfNumber */:
  1050. handleError(13 /* UnexpectedEndOfNumber */);
  1051. break;
  1052. case 1 /* UnexpectedEndOfComment */:
  1053. if (!disallowComments) {
  1054. handleError(11 /* UnexpectedEndOfComment */);
  1055. }
  1056. break;
  1057. case 2 /* UnexpectedEndOfString */:
  1058. handleError(12 /* UnexpectedEndOfString */);
  1059. break;
  1060. case 6 /* InvalidCharacter */:
  1061. handleError(16 /* InvalidCharacter */);
  1062. break;
  1063. }
  1064. switch (token) {
  1065. case 12 /* LineCommentTrivia */:
  1066. case 13 /* BlockCommentTrivia */:
  1067. if (disallowComments) {
  1068. handleError(10 /* InvalidCommentToken */);
  1069. }
  1070. else {
  1071. onComment();
  1072. }
  1073. break;
  1074. case 16 /* Unknown */:
  1075. handleError(1 /* InvalidSymbol */);
  1076. break;
  1077. case 15 /* Trivia */:
  1078. case 14 /* LineBreakTrivia */:
  1079. break;
  1080. default:
  1081. return token;
  1082. }
  1083. }
  1084. }
  1085. function handleError(error, skipUntilAfter, skipUntil) {
  1086. if (skipUntilAfter === void 0) { skipUntilAfter = []; }
  1087. if (skipUntil === void 0) { skipUntil = []; }
  1088. onError(error);
  1089. if (skipUntilAfter.length + skipUntil.length > 0) {
  1090. var token = _scanner.getToken();
  1091. while (token !== 17 /* EOF */) {
  1092. if (skipUntilAfter.indexOf(token) !== -1) {
  1093. scanNext();
  1094. break;
  1095. }
  1096. else if (skipUntil.indexOf(token) !== -1) {
  1097. break;
  1098. }
  1099. token = scanNext();
  1100. }
  1101. }
  1102. }
  1103. function parseString(isValue) {
  1104. var value = _scanner.getTokenValue();
  1105. if (isValue) {
  1106. onLiteralValue(value);
  1107. }
  1108. else {
  1109. onObjectProperty(value);
  1110. }
  1111. scanNext();
  1112. return true;
  1113. }
  1114. function parseLiteral() {
  1115. switch (_scanner.getToken()) {
  1116. case 11 /* NumericLiteral */:
  1117. var value = 0;
  1118. try {
  1119. value = JSON.parse(_scanner.getTokenValue());
  1120. if (typeof value !== 'number') {
  1121. handleError(2 /* InvalidNumberFormat */);
  1122. value = 0;
  1123. }
  1124. }
  1125. catch (e) {
  1126. handleError(2 /* InvalidNumberFormat */);
  1127. }
  1128. onLiteralValue(value);
  1129. break;
  1130. case 7 /* NullKeyword */:
  1131. onLiteralValue(null);
  1132. break;
  1133. case 8 /* TrueKeyword */:
  1134. onLiteralValue(true);
  1135. break;
  1136. case 9 /* FalseKeyword */:
  1137. onLiteralValue(false);
  1138. break;
  1139. default:
  1140. return false;
  1141. }
  1142. scanNext();
  1143. return true;
  1144. }
  1145. function parseProperty() {
  1146. if (_scanner.getToken() !== 10 /* StringLiteral */) {
  1147. handleError(3 /* PropertyNameExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  1148. return false;
  1149. }
  1150. parseString(false);
  1151. if (_scanner.getToken() === 6 /* ColonToken */) {
  1152. onSeparator(':');
  1153. scanNext(); // consume colon
  1154. if (!parseValue()) {
  1155. handleError(4 /* ValueExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  1156. }
  1157. }
  1158. else {
  1159. handleError(5 /* ColonExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  1160. }
  1161. return true;
  1162. }
  1163. function parseObject() {
  1164. onObjectBegin();
  1165. scanNext(); // consume open brace
  1166. var needsComma = false;
  1167. while (_scanner.getToken() !== 2 /* CloseBraceToken */ && _scanner.getToken() !== 17 /* EOF */) {
  1168. if (_scanner.getToken() === 5 /* CommaToken */) {
  1169. if (!needsComma) {
  1170. handleError(4 /* ValueExpected */, [], []);
  1171. }
  1172. onSeparator(',');
  1173. scanNext(); // consume comma
  1174. if (_scanner.getToken() === 2 /* CloseBraceToken */ && allowTrailingComma) {
  1175. break;
  1176. }
  1177. }
  1178. else if (needsComma) {
  1179. handleError(6 /* CommaExpected */, [], []);
  1180. }
  1181. if (!parseProperty()) {
  1182. handleError(4 /* ValueExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  1183. }
  1184. needsComma = true;
  1185. }
  1186. onObjectEnd();
  1187. if (_scanner.getToken() !== 2 /* CloseBraceToken */) {
  1188. handleError(7 /* CloseBraceExpected */, [2 /* CloseBraceToken */], []);
  1189. }
  1190. else {
  1191. scanNext(); // consume close brace
  1192. }
  1193. return true;
  1194. }
  1195. function parseArray() {
  1196. onArrayBegin();
  1197. scanNext(); // consume open bracket
  1198. var needsComma = false;
  1199. while (_scanner.getToken() !== 4 /* CloseBracketToken */ && _scanner.getToken() !== 17 /* EOF */) {
  1200. if (_scanner.getToken() === 5 /* CommaToken */) {
  1201. if (!needsComma) {
  1202. handleError(4 /* ValueExpected */, [], []);
  1203. }
  1204. onSeparator(',');
  1205. scanNext(); // consume comma
  1206. if (_scanner.getToken() === 4 /* CloseBracketToken */ && allowTrailingComma) {
  1207. break;
  1208. }
  1209. }
  1210. else if (needsComma) {
  1211. handleError(6 /* CommaExpected */, [], []);
  1212. }
  1213. if (!parseValue()) {
  1214. handleError(4 /* ValueExpected */, [], [4 /* CloseBracketToken */, 5 /* CommaToken */]);
  1215. }
  1216. needsComma = true;
  1217. }
  1218. onArrayEnd();
  1219. if (_scanner.getToken() !== 4 /* CloseBracketToken */) {
  1220. handleError(8 /* CloseBracketExpected */, [4 /* CloseBracketToken */], []);
  1221. }
  1222. else {
  1223. scanNext(); // consume close bracket
  1224. }
  1225. return true;
  1226. }
  1227. function parseValue() {
  1228. switch (_scanner.getToken()) {
  1229. case 3 /* OpenBracketToken */:
  1230. return parseArray();
  1231. case 1 /* OpenBraceToken */:
  1232. return parseObject();
  1233. case 10 /* StringLiteral */:
  1234. return parseString(true);
  1235. default:
  1236. return parseLiteral();
  1237. }
  1238. }
  1239. scanNext();
  1240. if (_scanner.getToken() === 17 /* EOF */) {
  1241. if (options.allowEmptyContent) {
  1242. return true;
  1243. }
  1244. handleError(4 /* ValueExpected */, [], []);
  1245. return false;
  1246. }
  1247. if (!parseValue()) {
  1248. handleError(4 /* ValueExpected */, [], []);
  1249. return false;
  1250. }
  1251. if (_scanner.getToken() !== 17 /* EOF */) {
  1252. handleError(9 /* EndOfFileExpected */, [], []);
  1253. }
  1254. return true;
  1255. }
  1256. exports.visit = visit;
  1257. /**
  1258. * Takes JSON with JavaScript-style comments and remove
  1259. * them. Optionally replaces every none-newline character
  1260. * of comments with a replaceCharacter
  1261. */
  1262. function stripComments(text, replaceCh) {
  1263. var _scanner = scanner_1.createScanner(text), parts = [], kind, offset = 0, pos;
  1264. do {
  1265. pos = _scanner.getPosition();
  1266. kind = _scanner.scan();
  1267. switch (kind) {
  1268. case 12 /* LineCommentTrivia */:
  1269. case 13 /* BlockCommentTrivia */:
  1270. case 17 /* EOF */:
  1271. if (offset !== pos) {
  1272. parts.push(text.substring(offset, pos));
  1273. }
  1274. if (replaceCh !== undefined) {
  1275. parts.push(_scanner.getTokenValue().replace(/[^\r\n]/g, replaceCh));
  1276. }
  1277. offset = _scanner.getPosition();
  1278. break;
  1279. }
  1280. } while (kind !== 17 /* EOF */);
  1281. return parts.join('');
  1282. }
  1283. exports.stripComments = stripComments;
  1284. function getNodeType(value) {
  1285. switch (typeof value) {
  1286. case 'boolean': return 'boolean';
  1287. case 'number': return 'number';
  1288. case 'string': return 'string';
  1289. case 'object': {
  1290. if (!value) {
  1291. return 'null';
  1292. }
  1293. else if (Array.isArray(value)) {
  1294. return 'array';
  1295. }
  1296. return 'object';
  1297. }
  1298. default: return 'null';
  1299. }
  1300. }
  1301. exports.getNodeType = getNodeType;
  1302. });
  1303. (function (factory) {
  1304. if (typeof module === "object" && typeof module.exports === "object") {
  1305. var v = factory(require, exports);
  1306. if (v !== undefined) module.exports = v;
  1307. }
  1308. else if (typeof define === "function" && define.amd) {
  1309. define('jsonc-parser/impl/edit',["require", "exports", "./format", "./parser"], factory);
  1310. }
  1311. })(function (require, exports) {
  1312. /*---------------------------------------------------------------------------------------------
  1313. * Copyright (c) Microsoft Corporation. All rights reserved.
  1314. * Licensed under the MIT License. See License.txt in the project root for license information.
  1315. *--------------------------------------------------------------------------------------------*/
  1316. 'use strict';
  1317. Object.defineProperty(exports, "__esModule", { value: true });
  1318. var format_1 = require("./format");
  1319. var parser_1 = require("./parser");
  1320. function removeProperty(text, path, formattingOptions) {
  1321. return setProperty(text, path, void 0, formattingOptions);
  1322. }
  1323. exports.removeProperty = removeProperty;
  1324. function setProperty(text, originalPath, value, formattingOptions, getInsertionIndex) {
  1325. var _a;
  1326. var path = originalPath.slice();
  1327. var errors = [];
  1328. var root = parser_1.parseTree(text, errors);
  1329. var parent = void 0;
  1330. var lastSegment = void 0;
  1331. while (path.length > 0) {
  1332. lastSegment = path.pop();
  1333. parent = parser_1.findNodeAtLocation(root, path);
  1334. if (parent === void 0 && value !== void 0) {
  1335. if (typeof lastSegment === 'string') {
  1336. value = (_a = {}, _a[lastSegment] = value, _a);
  1337. }
  1338. else {
  1339. value = [value];
  1340. }
  1341. }
  1342. else {
  1343. break;
  1344. }
  1345. }
  1346. if (!parent) {
  1347. // empty document
  1348. if (value === void 0) { // delete
  1349. throw new Error('Can not delete in empty document');
  1350. }
  1351. return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, formattingOptions);
  1352. }
  1353. else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) {
  1354. var existing = parser_1.findNodeAtLocation(parent, [lastSegment]);
  1355. if (existing !== void 0) {
  1356. if (value === void 0) { // delete
  1357. if (!existing.parent) {
  1358. throw new Error('Malformed AST');
  1359. }
  1360. var propertyIndex = parent.children.indexOf(existing.parent);
  1361. var removeBegin = void 0;
  1362. var removeEnd = existing.parent.offset + existing.parent.length;
  1363. if (propertyIndex > 0) {
  1364. // remove the comma of the previous node
  1365. var previous = parent.children[propertyIndex - 1];
  1366. removeBegin = previous.offset + previous.length;
  1367. }
  1368. else {
  1369. removeBegin = parent.offset + 1;
  1370. if (parent.children.length > 1) {
  1371. // remove the comma of the next node
  1372. var next = parent.children[1];
  1373. removeEnd = next.offset;
  1374. }
  1375. }
  1376. return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, formattingOptions);
  1377. }
  1378. else {
  1379. // set value of existing property
  1380. return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, formattingOptions);
  1381. }
  1382. }
  1383. else {
  1384. if (value === void 0) { // delete
  1385. return []; // property does not exist, nothing to do
  1386. }
  1387. var newProperty = JSON.stringify(lastSegment) + ": " + JSON.stringify(value);
  1388. var index = getInsertionIndex ? getInsertionIndex(parent.children.map(function (p) { return p.children[0].value; })) : parent.children.length;
  1389. var edit = void 0;
  1390. if (index > 0) {
  1391. var previous = parent.children[index - 1];
  1392. edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
  1393. }
  1394. else if (parent.children.length === 0) {
  1395. edit = { offset: parent.offset + 1, length: 0, content: newProperty };
  1396. }
  1397. else {
  1398. edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' };
  1399. }
  1400. return withFormatting(text, edit, formattingOptions);
  1401. }
  1402. }
  1403. else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) {
  1404. var insertIndex = lastSegment;
  1405. if (insertIndex === -1) {
  1406. // Insert
  1407. var newProperty = "" + JSON.stringify(value);
  1408. var edit = void 0;
  1409. if (parent.children.length === 0) {
  1410. edit = { offset: parent.offset + 1, length: 0, content: newProperty };
  1411. }
  1412. else {
  1413. var previous = parent.children[parent.children.length - 1];
  1414. edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
  1415. }
  1416. return withFormatting(text, edit, formattingOptions);
  1417. }
  1418. else {
  1419. if (value === void 0 && parent.children.length >= 0) {
  1420. //Removal
  1421. var removalIndex = lastSegment;
  1422. var toRemove = parent.children[removalIndex];
  1423. var edit = void 0;
  1424. if (parent.children.length === 1) {
  1425. // only item
  1426. edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' };
  1427. }
  1428. else if (parent.children.length - 1 === removalIndex) {
  1429. // last item
  1430. var previous = parent.children[removalIndex - 1];
  1431. var offset = previous.offset + previous.length;
  1432. var parentEndOffset = parent.offset + parent.length;
  1433. edit = { offset: offset, length: parentEndOffset - 2 - offset, content: '' };
  1434. }
  1435. else {
  1436. edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' };
  1437. }
  1438. return withFormatting(text, edit, formattingOptions);
  1439. }
  1440. else {
  1441. throw new Error('Array modification not supported yet');
  1442. }
  1443. }
  1444. }
  1445. else {
  1446. throw new Error("Can not add " + (typeof lastSegment !== 'number' ? 'index' : 'property') + " to parent of type " + parent.type);
  1447. }
  1448. }
  1449. exports.setProperty = setProperty;
  1450. function withFormatting(text, edit, formattingOptions) {
  1451. // apply the edit
  1452. var newText = applyEdit(text, edit);
  1453. // format the new text
  1454. var begin = edit.offset;
  1455. var end = edit.offset + edit.content.length;
  1456. if (edit.length === 0 || edit.content.length === 0) { // insert or remove
  1457. while (begin > 0 && !format_1.isEOL(newText, begin - 1)) {
  1458. begin--;
  1459. }
  1460. while (end < newText.length && !format_1.isEOL(newText, end)) {
  1461. end++;
  1462. }
  1463. }
  1464. var edits = format_1.format(newText, { offset: begin, length: end - begin }, formattingOptions);
  1465. // apply the formatting edits and track the begin and end offsets of the changes
  1466. for (var i = edits.length - 1; i >= 0; i--) {
  1467. var edit_1 = edits[i];
  1468. newText = applyEdit(newText, edit_1);
  1469. begin = Math.min(begin, edit_1.offset);
  1470. end = Math.max(end, edit_1.offset + edit_1.length);
  1471. end += edit_1.content.length - edit_1.length;
  1472. }
  1473. // create a single edit with all changes
  1474. var editLength = text.length - (newText.length - end) - begin;
  1475. return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];
  1476. }
  1477. function applyEdit(text, edit) {
  1478. return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
  1479. }
  1480. exports.applyEdit = applyEdit;
  1481. function isWS(text, offset) {
  1482. return '\r\n \t'.indexOf(text.charAt(offset)) !== -1;
  1483. }
  1484. exports.isWS = isWS;
  1485. });
  1486. (function (factory) {
  1487. if (typeof module === "object" && typeof module.exports === "object") {
  1488. var v = factory(require, exports);
  1489. if (v !== undefined) module.exports = v;
  1490. }
  1491. else if (typeof define === "function" && define.amd) {
  1492. define('jsonc-parser/main',["require", "exports", "./impl/format", "./impl/edit", "./impl/scanner", "./impl/parser"], factory);
  1493. }
  1494. })(function (require, exports) {
  1495. /*---------------------------------------------------------------------------------------------
  1496. * Copyright (c) Microsoft Corporation. All rights reserved.
  1497. * Licensed under the MIT License. See License.txt in the project root for license information.
  1498. *--------------------------------------------------------------------------------------------*/
  1499. 'use strict';
  1500. Object.defineProperty(exports, "__esModule", { value: true });
  1501. var formatter = require("./impl/format");
  1502. var edit = require("./impl/edit");
  1503. var scanner = require("./impl/scanner");
  1504. var parser = require("./impl/parser");
  1505. /**
  1506. * Creates a JSON scanner on the given text.
  1507. * If ignoreTrivia is set, whitespaces or comments are ignored.
  1508. */
  1509. exports.createScanner = scanner.createScanner;
  1510. /**
  1511. * 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.
  1512. */
  1513. exports.getLocation = parser.getLocation;
  1514. /**
  1515. * 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.
  1516. * Therefore, always check the errors list to find out if the input was valid.
  1517. */
  1518. exports.parse = parser.parse;
  1519. /**
  1520. * 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.
  1521. */
  1522. exports.parseTree = parser.parseTree;
  1523. /**
  1524. * Finds the node at the given path in a JSON DOM.
  1525. */
  1526. exports.findNodeAtLocation = parser.findNodeAtLocation;
  1527. /**
  1528. * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.
  1529. */
  1530. exports.findNodeAtOffset = parser.findNodeAtOffset;
  1531. /**
  1532. * Gets the JSON path of the given JSON DOM node
  1533. */
  1534. exports.getNodePath = parser.getNodePath;
  1535. /**
  1536. * Evaluates the JavaScript object of the given JSON DOM node
  1537. */
  1538. exports.getNodeValue = parser.getNodeValue;
  1539. /**
  1540. * Parses the given text and invokes the visitor functions for each object, array and literal reached.
  1541. */
  1542. exports.visit = parser.visit;
  1543. /**
  1544. * Takes JSON with JavaScript-style comments and remove
  1545. * them. Optionally replaces every none-newline character
  1546. * of comments with a replaceCharacter
  1547. */
  1548. exports.stripComments = parser.stripComments;
  1549. function printParseErrorCode(code) {
  1550. switch (code) {
  1551. case 1 /* InvalidSymbol */: return 'InvalidSymbol';
  1552. case 2 /* InvalidNumberFormat */: return 'InvalidNumberFormat';
  1553. case 3 /* PropertyNameExpected */: return 'PropertyNameExpected';
  1554. case 4 /* ValueExpected */: return 'ValueExpected';
  1555. case 5 /* ColonExpected */: return 'ColonExpected';
  1556. case 6 /* CommaExpected */: return 'CommaExpected';
  1557. case 7 /* CloseBraceExpected */: return 'CloseBraceExpected';
  1558. case 8 /* CloseBracketExpected */: return 'CloseBracketExpected';
  1559. case 9 /* EndOfFileExpected */: return 'EndOfFileExpected';
  1560. case 10 /* InvalidCommentToken */: return 'InvalidCommentToken';
  1561. case 11 /* UnexpectedEndOfComment */: return 'UnexpectedEndOfComment';
  1562. case 12 /* UnexpectedEndOfString */: return 'UnexpectedEndOfString';
  1563. case 13 /* UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber';
  1564. case 14 /* InvalidUnicode */: return 'InvalidUnicode';
  1565. case 15 /* InvalidEscapeCharacter */: return 'InvalidEscapeCharacter';
  1566. case 16 /* InvalidCharacter */: return 'InvalidCharacter';
  1567. }
  1568. return '<unknown ParseErrorCode>';
  1569. }
  1570. exports.printParseErrorCode = printParseErrorCode;
  1571. /**
  1572. * Computes the edits needed to format a JSON document.
  1573. *
  1574. * @param documentText The input text
  1575. * @param range The range to format or `undefined` to format the full content
  1576. * @param options The formatting options
  1577. * @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
  1578. * 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
  1579. * text in the original document. However, multiple edits can have
  1580. * 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.
  1581. * To apply edits to an input, you can use `applyEdits`.
  1582. */
  1583. function format(documentText, range, options) {
  1584. return formatter.format(documentText, range, options);
  1585. }
  1586. exports.format = format;
  1587. /**
  1588. * Computes the edits needed to modify a value in the JSON document.
  1589. *
  1590. * @param documentText The input text
  1591. * @param path The path of the value to change. The path represents either to the document root, a property or an array item.
  1592. * If the path points to an non-existing property or item, it will be created.
  1593. * @param value The new value for the specified property or item. If the value is undefined,
  1594. * the property or item will be removed.
  1595. * @param options Options
  1596. * @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
  1597. * 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
  1598. * text in the original document. However, multiple edits can have
  1599. * 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.
  1600. * To apply edits to an input, you can use `applyEdits`.
  1601. */
  1602. function modify(text, path, value, options) {
  1603. return edit.setProperty(text, path, value, options.formattingOptions, options.getInsertionIndex);
  1604. }
  1605. exports.modify = modify;
  1606. /**
  1607. * Applies edits to a input string.
  1608. */
  1609. function applyEdits(text, edits) {
  1610. for (var i = edits.length - 1; i >= 0; i--) {
  1611. text = edit.applyEdit(text, edits[i]);
  1612. }
  1613. return text;
  1614. }
  1615. exports.applyEdits = applyEdits;
  1616. });
  1617. define('jsonc-parser', ['jsonc-parser/main'], function (main) { return main; });
  1618. /*---------------------------------------------------------------------------------------------
  1619. * Copyright (c) Microsoft Corporation. All rights reserved.
  1620. * Licensed under the MIT License. See License.txt in the project root for license information.
  1621. *--------------------------------------------------------------------------------------------*/
  1622. (function (factory) {
  1623. if (typeof module === "object" && typeof module.exports === "object") {
  1624. var v = factory(require, exports);
  1625. if (v !== undefined) module.exports = v;
  1626. }
  1627. else if (typeof define === "function" && define.amd) {
  1628. define('vscode-json-languageservice/utils/objects',["require", "exports"], factory);
  1629. }
  1630. })(function (require, exports) {
  1631. "use strict";
  1632. Object.defineProperty(exports, "__esModule", { value: true });
  1633. function equals(one, other) {
  1634. if (one === other) {
  1635. return true;
  1636. }
  1637. if (one === null || one === undefined || other === null || other === undefined) {
  1638. return false;
  1639. }
  1640. if (typeof one !== typeof other) {
  1641. return false;
  1642. }
  1643. if (typeof one !== 'object') {
  1644. return false;
  1645. }
  1646. if ((Array.isArray(one)) !== (Array.isArray(other))) {
  1647. return false;
  1648. }
  1649. var i, key;
  1650. if (Array.isArray(one)) {
  1651. if (one.length !== other.length) {
  1652. return false;
  1653. }
  1654. for (i = 0; i < one.length; i++) {
  1655. if (!equals(one[i], other[i])) {
  1656. return false;
  1657. }
  1658. }
  1659. }
  1660. else {
  1661. var oneKeys = [];
  1662. for (key in one) {
  1663. oneKeys.push(key);
  1664. }
  1665. oneKeys.sort();
  1666. var otherKeys = [];
  1667. for (key in other) {
  1668. otherKeys.push(key);
  1669. }
  1670. otherKeys.sort();
  1671. if (!equals(oneKeys, otherKeys)) {
  1672. return false;
  1673. }
  1674. for (i = 0; i < oneKeys.length; i++) {
  1675. if (!equals(one[oneKeys[i]], other[oneKeys[i]])) {
  1676. return false;
  1677. }
  1678. }
  1679. }
  1680. return true;
  1681. }
  1682. exports.equals = equals;
  1683. function isNumber(val) {
  1684. return typeof val === 'number';
  1685. }
  1686. exports.isNumber = isNumber;
  1687. function isDefined(val) {
  1688. return typeof val !== 'undefined';
  1689. }
  1690. exports.isDefined = isDefined;
  1691. function isBoolean(val) {
  1692. return typeof val === 'boolean';
  1693. }
  1694. exports.isBoolean = isBoolean;
  1695. function isString(val) {
  1696. return typeof val === 'string';
  1697. }
  1698. exports.isString = isString;
  1699. });
  1700. (function (factory) {
  1701. if (typeof module === "object" && typeof module.exports === "object") {
  1702. var v = factory(require, exports);
  1703. if (v !== undefined) module.exports = v;
  1704. }
  1705. else if (typeof define === "function" && define.amd) {
  1706. define('vscode-languageserver-types/main',["require", "exports"], factory);
  1707. }
  1708. })(function (require, exports) {
  1709. /* --------------------------------------------------------------------------------------------
  1710. * Copyright (c) Microsoft Corporation. All rights reserved.
  1711. * Licensed under the MIT License. See License.txt in the project root for license information.
  1712. * ------------------------------------------------------------------------------------------ */
  1713. 'use strict';
  1714. Object.defineProperty(exports, "__esModule", { value: true });
  1715. /**
  1716. * The Position namespace provides helper functions to work with
  1717. * [Position](#Position) literals.
  1718. */
  1719. var Position;
  1720. (function (Position) {
  1721. /**
  1722. * Creates a new Position literal from the given line and character.
  1723. * @param line The position's line.
  1724. * @param character The position's character.
  1725. */
  1726. function create(line, character) {
  1727. return { line: line, character: character };
  1728. }
  1729. Position.create = create;
  1730. /**
  1731. * Checks whether the given liternal conforms to the [Position](#Position) interface.
  1732. */
  1733. function is(value) {
  1734. var candidate = value;
  1735. return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character);
  1736. }
  1737. Position.is = is;
  1738. })(Position = exports.Position || (exports.Position = {}));
  1739. /**
  1740. * The Range namespace provides helper functions to work with
  1741. * [Range](#Range) literals.
  1742. */
  1743. var Range;
  1744. (function (Range) {
  1745. function create(one, two, three, four) {
  1746. if (Is.number(one) && Is.number(two) && Is.number(three) && Is.number(four)) {
  1747. return { start: Position.create(one, two), end: Position.create(three, four) };
  1748. }
  1749. else if (Position.is(one) && Position.is(two)) {
  1750. return { start: one, end: two };
  1751. }
  1752. else {
  1753. throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
  1754. }
  1755. }
  1756. Range.create = create;
  1757. /**
  1758. * Checks whether the given literal conforms to the [Range](#Range) interface.
  1759. */
  1760. function is(value) {
  1761. var candidate = value;
  1762. return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
  1763. }
  1764. Range.is = is;
  1765. })(Range = exports.Range || (exports.Range = {}));
  1766. /**
  1767. * The Location namespace provides helper functions to work with
  1768. * [Location](#Location) literals.
  1769. */
  1770. var Location;
  1771. (function (Location) {
  1772. /**
  1773. * Creates a Location literal.
  1774. * @param uri The location's uri.
  1775. * @param range The location's range.
  1776. */
  1777. function create(uri, range) {
  1778. return { uri: uri, range: range };
  1779. }
  1780. Location.create = create;
  1781. /**
  1782. * Checks whether the given literal conforms to the [Location](#Location) interface.
  1783. */
  1784. function is(value) {
  1785. var candidate = value;
  1786. return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
  1787. }
  1788. Location.is = is;
  1789. })(Location = exports.Location || (exports.Location = {}));
  1790. /**
  1791. * The LocationLink namespace provides helper functions to work with
  1792. * [LocationLink](#LocationLink) literals.
  1793. */
  1794. var LocationLink;
  1795. (function (LocationLink) {
  1796. /**
  1797. * Creates a LocationLink literal.
  1798. * @param targetUri The definition's uri.
  1799. * @param targetRange The full range of the definition.
  1800. * @param targetSelectionRange The span of the symbol definition at the target.
  1801. * @param originSelectionRange The span of the symbol being defined in the originating source file.
  1802. */
  1803. function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
  1804. return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };
  1805. }
  1806. LocationLink.create = create;
  1807. /**
  1808. * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface.
  1809. */
  1810. function is(value) {
  1811. var candidate = value;
  1812. return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)
  1813. && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange))
  1814. && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
  1815. }
  1816. LocationLink.is = is;
  1817. })(LocationLink = exports.LocationLink || (exports.LocationLink = {}));
  1818. /**
  1819. * The Color namespace provides helper functions to work with
  1820. * [Color](#Color) literals.
  1821. */
  1822. var Color;
  1823. (function (Color) {
  1824. /**
  1825. * Creates a new Color literal.
  1826. */
  1827. function create(red, green, blue, alpha) {
  1828. return {
  1829. red: red,
  1830. green: green,
  1831. blue: blue,
  1832. alpha: alpha,
  1833. };
  1834. }
  1835. Color.create = create;
  1836. /**
  1837. * Checks whether the given literal conforms to the [Color](#Color) interface.
  1838. */
  1839. function is(value) {
  1840. var candidate = value;
  1841. return Is.number(candidate.red)
  1842. && Is.number(candidate.green)
  1843. && Is.number(candidate.blue)
  1844. && Is.number(candidate.alpha);
  1845. }
  1846. Color.is = is;
  1847. })(Color = exports.Color || (exports.Color = {}));
  1848. /**
  1849. * The ColorInformation namespace provides helper functions to work with
  1850. * [ColorInformation](#ColorInformation) literals.
  1851. */
  1852. var ColorInformation;
  1853. (function (ColorInformation) {
  1854. /**
  1855. * Creates a new ColorInformation literal.
  1856. */
  1857. function create(range, color) {
  1858. return {
  1859. range: range,
  1860. color: color,
  1861. };
  1862. }
  1863. ColorInformation.create = create;
  1864. /**
  1865. * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
  1866. */
  1867. function is(value) {
  1868. var candidate = value;
  1869. return Range.is(candidate.range) && Color.is(candidate.color);
  1870. }
  1871. ColorInformation.is = is;
  1872. })(ColorInformation = exports.ColorInformation || (exports.ColorInformation = {}));
  1873. /**
  1874. * The Color namespace provides helper functions to work with
  1875. * [ColorPresentation](#ColorPresentation) literals.
  1876. */
  1877. var ColorPresentation;
  1878. (function (ColorPresentation) {
  1879. /**
  1880. * Creates a new ColorInformation literal.
  1881. */
  1882. function create(label, textEdit, additionalTextEdits) {
  1883. return {
  1884. label: label,
  1885. textEdit: textEdit,
  1886. additionalTextEdits: additionalTextEdits,
  1887. };
  1888. }
  1889. ColorPresentation.create = create;
  1890. /**
  1891. * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
  1892. */
  1893. function is(value) {
  1894. var candidate = value;
  1895. return Is.string(candidate.label)
  1896. && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))
  1897. && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
  1898. }
  1899. ColorPresentation.is = is;
  1900. })(ColorPresentation = exports.ColorPresentation || (exports.ColorPresentation = {}));
  1901. /**
  1902. * Enum of known range kinds
  1903. */
  1904. var FoldingRangeKind;
  1905. (function (FoldingRangeKind) {
  1906. /**
  1907. * Folding range for a comment
  1908. */
  1909. FoldingRangeKind["Comment"] = "comment";
  1910. /**
  1911. * Folding range for a imports or includes
  1912. */
  1913. FoldingRangeKind["Imports"] = "imports";
  1914. /**
  1915. * Folding range for a region (e.g. `#region`)
  1916. */
  1917. FoldingRangeKind["Region"] = "region";
  1918. })(FoldingRangeKind = exports.FoldingRangeKind || (exports.FoldingRangeKind = {}));
  1919. /**
  1920. * The folding range namespace provides helper functions to work with
  1921. * [FoldingRange](#FoldingRange) literals.
  1922. */
  1923. var FoldingRange;
  1924. (function (FoldingRange) {
  1925. /**
  1926. * Creates a new FoldingRange literal.
  1927. */
  1928. function create(startLine, endLine, startCharacter, endCharacter, kind) {
  1929. var result = {
  1930. startLine: startLine,
  1931. endLine: endLine
  1932. };
  1933. if (Is.defined(startCharacter)) {
  1934. result.startCharacter = startCharacter;
  1935. }
  1936. if (Is.defined(endCharacter)) {
  1937. result.endCharacter = endCharacter;
  1938. }
  1939. if (Is.defined(kind)) {
  1940. result.kind = kind;
  1941. }
  1942. return result;
  1943. }
  1944. FoldingRange.create = create;
  1945. /**
  1946. * Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface.
  1947. */
  1948. function is(value) {
  1949. var candidate = value;
  1950. return Is.number(candidate.startLine) && Is.number(candidate.startLine)
  1951. && (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter))
  1952. && (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter))
  1953. && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
  1954. }
  1955. FoldingRange.is = is;
  1956. })(FoldingRange = exports.FoldingRange || (exports.FoldingRange = {}));
  1957. /**
  1958. * The DiagnosticRelatedInformation namespace provides helper functions to work with
  1959. * [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals.
  1960. */
  1961. var DiagnosticRelatedInformation;
  1962. (function (DiagnosticRelatedInformation) {
  1963. /**
  1964. * Creates a new DiagnosticRelatedInformation literal.
  1965. */
  1966. function create(location, message) {
  1967. return {
  1968. location: location,
  1969. message: message
  1970. };
  1971. }
  1972. DiagnosticRelatedInformation.create = create;
  1973. /**
  1974. * Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface.
  1975. */
  1976. function is(value) {
  1977. var candidate = value;
  1978. return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
  1979. }
  1980. DiagnosticRelatedInformation.is = is;
  1981. })(DiagnosticRelatedInformation = exports.DiagnosticRelatedInformation || (exports.DiagnosticRelatedInformation = {}));
  1982. /**
  1983. * The diagnostic's severity.
  1984. */
  1985. var DiagnosticSeverity;
  1986. (function (DiagnosticSeverity) {
  1987. /**
  1988. * Reports an error.
  1989. */
  1990. DiagnosticSeverity.Error = 1;
  1991. /**
  1992. * Reports a warning.
  1993. */
  1994. DiagnosticSeverity.Warning = 2;
  1995. /**
  1996. * Reports an information.
  1997. */
  1998. DiagnosticSeverity.Information = 3;
  1999. /**
  2000. * Reports a hint.
  2001. */
  2002. DiagnosticSeverity.Hint = 4;
  2003. })(DiagnosticSeverity = exports.DiagnosticSeverity || (exports.DiagnosticSeverity = {}));
  2004. /**
  2005. * The diagnostic tags.
  2006. *
  2007. * @since 3.15.0
  2008. */
  2009. var DiagnosticTag;
  2010. (function (DiagnosticTag) {
  2011. /**
  2012. * Unused or unnecessary code.
  2013. *
  2014. * Clients are allowed to render diagnostics with this tag faded out instead of having
  2015. * an error squiggle.
  2016. */
  2017. DiagnosticTag.Unnecessary = 1;
  2018. /**
  2019. * Deprecated or obsolete code.
  2020. *
  2021. * Clients are allowed to rendered diagnostics with this tag strike through.
  2022. */
  2023. DiagnosticTag.Deprecated = 2;
  2024. })(DiagnosticTag = exports.DiagnosticTag || (exports.DiagnosticTag = {}));
  2025. /**
  2026. * The Diagnostic namespace provides helper functions to work with
  2027. * [Diagnostic](#Diagnostic) literals.
  2028. */
  2029. var Diagnostic;
  2030. (function (Diagnostic) {
  2031. /**
  2032. * Creates a new Diagnostic literal.
  2033. */
  2034. function create(range, message, severity, code, source, relatedInformation) {
  2035. var result = { range: range, message: message };
  2036. if (Is.defined(severity)) {
  2037. result.severity = severity;
  2038. }
  2039. if (Is.defined(code)) {
  2040. result.code = code;
  2041. }
  2042. if (Is.defined(source)) {
  2043. result.source = source;
  2044. }
  2045. if (Is.defined(relatedInformation)) {
  2046. result.relatedInformation = relatedInformation;
  2047. }
  2048. return result;
  2049. }
  2050. Diagnostic.create = create;
  2051. /**
  2052. * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface.
  2053. */
  2054. function is(value) {
  2055. var candidate = value;
  2056. return Is.defined(candidate)
  2057. && Range.is(candidate.range)
  2058. && Is.string(candidate.message)
  2059. && (Is.number(candidate.severity) || Is.undefined(candidate.severity))
  2060. && (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))
  2061. && (Is.string(candidate.source) || Is.undefined(candidate.source))
  2062. && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
  2063. }
  2064. Diagnostic.is = is;
  2065. })(Diagnostic = exports.Diagnostic || (exports.Diagnostic = {}));
  2066. /**
  2067. * The Command namespace provides helper functions to work with
  2068. * [Command](#Command) literals.
  2069. */
  2070. var Command;
  2071. (function (Command) {
  2072. /**
  2073. * Creates a new Command literal.
  2074. */
  2075. function create(title, command) {
  2076. var args = [];
  2077. for (var _i = 2; _i < arguments.length; _i++) {
  2078. args[_i - 2] = arguments[_i];
  2079. }
  2080. var result = { title: title, command: command };
  2081. if (Is.defined(args) && args.length > 0) {
  2082. result.arguments = args;
  2083. }
  2084. return result;
  2085. }
  2086. Command.create = create;
  2087. /**
  2088. * Checks whether the given literal conforms to the [Command](#Command) interface.
  2089. */
  2090. function is(value) {
  2091. var candidate = value;
  2092. return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
  2093. }
  2094. Command.is = is;
  2095. })(Command = exports.Command || (exports.Command = {}));
  2096. /**
  2097. * The TextEdit namespace provides helper function to create replace,
  2098. * insert and delete edits more easily.
  2099. */
  2100. var TextEdit;
  2101. (function (TextEdit) {
  2102. /**
  2103. * Creates a replace text edit.
  2104. * @param range The range of text to be replaced.
  2105. * @param newText The new text.
  2106. */
  2107. function replace(range, newText) {
  2108. return { range: range, newText: newText };
  2109. }
  2110. TextEdit.replace = replace;
  2111. /**
  2112. * Creates a insert text edit.
  2113. * @param position The position to insert the text at.
  2114. * @param newText The text to be inserted.
  2115. */
  2116. function insert(position, newText) {
  2117. return { range: { start: position, end: position }, newText: newText };
  2118. }
  2119. TextEdit.insert = insert;
  2120. /**
  2121. * Creates a delete text edit.
  2122. * @param range The range of text to be deleted.
  2123. */
  2124. function del(range) {
  2125. return { range: range, newText: '' };
  2126. }
  2127. TextEdit.del = del;
  2128. function is(value) {
  2129. var candidate = value;
  2130. return Is.objectLiteral(candidate)
  2131. && Is.string(candidate.newText)
  2132. && Range.is(candidate.range);
  2133. }
  2134. TextEdit.is = is;
  2135. })(TextEdit = exports.TextEdit || (exports.TextEdit = {}));
  2136. /**
  2137. * The TextDocumentEdit namespace provides helper function to create
  2138. * an edit that manipulates a text document.
  2139. */
  2140. var TextDocumentEdit;
  2141. (function (TextDocumentEdit) {
  2142. /**
  2143. * Creates a new `TextDocumentEdit`
  2144. */
  2145. function create(textDocument, edits) {
  2146. return { textDocument: textDocument, edits: edits };
  2147. }
  2148. TextDocumentEdit.create = create;
  2149. function is(value) {
  2150. var candidate = value;
  2151. return Is.defined(candidate)
  2152. && VersionedTextDocumentIdentifier.is(candidate.textDocument)
  2153. && Array.isArray(candidate.edits);
  2154. }
  2155. TextDocumentEdit.is = is;
  2156. })(TextDocumentEdit = exports.TextDocumentEdit || (exports.TextDocumentEdit = {}));
  2157. var CreateFile;
  2158. (function (CreateFile) {
  2159. function create(uri, options) {
  2160. var result = {
  2161. kind: 'create',
  2162. uri: uri
  2163. };
  2164. if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
  2165. result.options = options;
  2166. }
  2167. return result;
  2168. }
  2169. CreateFile.create = create;
  2170. function is(value) {
  2171. var candidate = value;
  2172. return candidate && candidate.kind === 'create' && Is.string(candidate.uri) &&
  2173. (candidate.options === void 0 ||
  2174. ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
  2175. }
  2176. CreateFile.is = is;
  2177. })(CreateFile = exports.CreateFile || (exports.CreateFile = {}));
  2178. var RenameFile;
  2179. (function (RenameFile) {
  2180. function create(oldUri, newUri, options) {
  2181. var result = {
  2182. kind: 'rename',
  2183. oldUri: oldUri,
  2184. newUri: newUri
  2185. };
  2186. if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
  2187. result.options = options;
  2188. }
  2189. return result;
  2190. }
  2191. RenameFile.create = create;
  2192. function is(value) {
  2193. var candidate = value;
  2194. return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) &&
  2195. (candidate.options === void 0 ||
  2196. ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
  2197. }
  2198. RenameFile.is = is;
  2199. })(RenameFile = exports.RenameFile || (exports.RenameFile = {}));
  2200. var DeleteFile;
  2201. (function (DeleteFile) {
  2202. function create(uri, options) {
  2203. var result = {
  2204. kind: 'delete',
  2205. uri: uri
  2206. };
  2207. if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
  2208. result.options = options;
  2209. }
  2210. return result;
  2211. }
  2212. DeleteFile.create = create;
  2213. function is(value) {
  2214. var candidate = value;
  2215. return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) &&
  2216. (candidate.options === void 0 ||
  2217. ((candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))));
  2218. }
  2219. DeleteFile.is = is;
  2220. })(DeleteFile = exports.DeleteFile || (exports.DeleteFile = {}));
  2221. var WorkspaceEdit;
  2222. (function (WorkspaceEdit) {
  2223. function is(value) {
  2224. var candidate = value;
  2225. return candidate &&
  2226. (candidate.changes !== void 0 || candidate.documentChanges !== void 0) &&
  2227. (candidate.documentChanges === void 0 || candidate.documentChanges.every(function (change) {
  2228. if (Is.string(change.kind)) {
  2229. return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
  2230. }
  2231. else {
  2232. return TextDocumentEdit.is(change);
  2233. }
  2234. }));
  2235. }
  2236. WorkspaceEdit.is = is;
  2237. })(WorkspaceEdit = exports.WorkspaceEdit || (exports.WorkspaceEdit = {}));
  2238. var TextEditChangeImpl = /** @class */ (function () {
  2239. function TextEditChangeImpl(edits) {
  2240. this.edits = edits;
  2241. }
  2242. TextEditChangeImpl.prototype.insert = function (position, newText) {
  2243. this.edits.push(TextEdit.insert(position, newText));
  2244. };
  2245. TextEditChangeImpl.prototype.replace = function (range, newText) {
  2246. this.edits.push(TextEdit.replace(range, newText));
  2247. };
  2248. TextEditChangeImpl.prototype.delete = function (range) {
  2249. this.edits.push(TextEdit.del(range));
  2250. };
  2251. TextEditChangeImpl.prototype.add = function (edit) {
  2252. this.edits.push(edit);
  2253. };
  2254. TextEditChangeImpl.prototype.all = function () {
  2255. return this.edits;
  2256. };
  2257. TextEditChangeImpl.prototype.clear = function () {
  2258. this.edits.splice(0, this.edits.length);
  2259. };
  2260. return TextEditChangeImpl;
  2261. }());
  2262. /**
  2263. * A workspace change helps constructing changes to a workspace.
  2264. */
  2265. var WorkspaceChange = /** @class */ (function () {
  2266. function WorkspaceChange(workspaceEdit) {
  2267. var _this = this;
  2268. this._textEditChanges = Object.create(null);
  2269. if (workspaceEdit) {
  2270. this._workspaceEdit = workspaceEdit;
  2271. if (workspaceEdit.documentChanges) {
  2272. workspaceEdit.documentChanges.forEach(function (change) {
  2273. if (TextDocumentEdit.is(change)) {
  2274. var textEditChange = new TextEditChangeImpl(change.edits);
  2275. _this._textEditChanges[change.textDocument.uri] = textEditChange;
  2276. }
  2277. });
  2278. }
  2279. else if (workspaceEdit.changes) {
  2280. Object.keys(workspaceEdit.changes).forEach(function (key) {
  2281. var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
  2282. _this._textEditChanges[key] = textEditChange;
  2283. });
  2284. }
  2285. }
  2286. }
  2287. Object.defineProperty(WorkspaceChange.prototype, "edit", {
  2288. /**
  2289. * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal
  2290. * use to be returned from a workspace edit operation like rename.
  2291. */
  2292. get: function () {
  2293. return this._workspaceEdit;
  2294. },
  2295. enumerable: true,
  2296. configurable: true
  2297. });
  2298. WorkspaceChange.prototype.getTextEditChange = function (key) {
  2299. if (VersionedTextDocumentIdentifier.is(key)) {
  2300. if (!this._workspaceEdit) {
  2301. this._workspaceEdit = {
  2302. documentChanges: []
  2303. };
  2304. }
  2305. if (!this._workspaceEdit.documentChanges) {
  2306. throw new Error('Workspace edit is not configured for document changes.');
  2307. }
  2308. var textDocument = key;
  2309. var result = this._textEditChanges[textDocument.uri];
  2310. if (!result) {
  2311. var edits = [];
  2312. var textDocumentEdit = {
  2313. textDocument: textDocument,
  2314. edits: edits
  2315. };
  2316. this._workspaceEdit.documentChanges.push(textDocumentEdit);
  2317. result = new TextEditChangeImpl(edits);
  2318. this._textEditChanges[textDocument.uri] = result;
  2319. }
  2320. return result;
  2321. }
  2322. else {
  2323. if (!this._workspaceEdit) {
  2324. this._workspaceEdit = {
  2325. changes: Object.create(null)
  2326. };
  2327. }
  2328. if (!this._workspaceEdit.changes) {
  2329. throw new Error('Workspace edit is not configured for normal text edit changes.');
  2330. }
  2331. var result = this._textEditChanges[key];
  2332. if (!result) {
  2333. var edits = [];
  2334. this._workspaceEdit.changes[key] = edits;
  2335. result = new TextEditChangeImpl(edits);
  2336. this._textEditChanges[key] = result;
  2337. }
  2338. return result;
  2339. }
  2340. };
  2341. WorkspaceChange.prototype.createFile = function (uri, options) {
  2342. this.checkDocumentChanges();
  2343. this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));
  2344. };
  2345. WorkspaceChange.prototype.renameFile = function (oldUri, newUri, options) {
  2346. this.checkDocumentChanges();
  2347. this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));
  2348. };
  2349. WorkspaceChange.prototype.deleteFile = function (uri, options) {
  2350. this.checkDocumentChanges();
  2351. this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));
  2352. };
  2353. WorkspaceChange.prototype.checkDocumentChanges = function () {
  2354. if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {
  2355. throw new Error('Workspace edit is not configured for document changes.');
  2356. }
  2357. };
  2358. return WorkspaceChange;
  2359. }());
  2360. exports.WorkspaceChange = WorkspaceChange;
  2361. /**
  2362. * The TextDocumentIdentifier namespace provides helper functions to work with
  2363. * [TextDocumentIdentifier](#TextDocumentIdentifier) literals.
  2364. */
  2365. var TextDocumentIdentifier;
  2366. (function (TextDocumentIdentifier) {
  2367. /**
  2368. * Creates a new TextDocumentIdentifier literal.
  2369. * @param uri The document's uri.
  2370. */
  2371. function create(uri) {
  2372. return { uri: uri };
  2373. }
  2374. TextDocumentIdentifier.create = create;
  2375. /**
  2376. * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface.
  2377. */
  2378. function is(value) {
  2379. var candidate = value;
  2380. return Is.defined(candidate) && Is.string(candidate.uri);
  2381. }
  2382. TextDocumentIdentifier.is = is;
  2383. })(TextDocumentIdentifier = exports.TextDocumentIdentifier || (exports.TextDocumentIdentifier = {}));
  2384. /**
  2385. * The VersionedTextDocumentIdentifier namespace provides helper functions to work with
  2386. * [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals.
  2387. */
  2388. var VersionedTextDocumentIdentifier;
  2389. (function (VersionedTextDocumentIdentifier) {
  2390. /**
  2391. * Creates a new VersionedTextDocumentIdentifier literal.
  2392. * @param uri The document's uri.
  2393. * @param uri The document's text.
  2394. */
  2395. function create(uri, version) {
  2396. return { uri: uri, version: version };
  2397. }
  2398. VersionedTextDocumentIdentifier.create = create;
  2399. /**
  2400. * Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface.
  2401. */
  2402. function is(value) {
  2403. var candidate = value;
  2404. return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.number(candidate.version));
  2405. }
  2406. VersionedTextDocumentIdentifier.is = is;
  2407. })(VersionedTextDocumentIdentifier = exports.VersionedTextDocumentIdentifier || (exports.VersionedTextDocumentIdentifier = {}));
  2408. /**
  2409. * The TextDocumentItem namespace provides helper functions to work with
  2410. * [TextDocumentItem](#TextDocumentItem) literals.
  2411. */
  2412. var TextDocumentItem;
  2413. (function (TextDocumentItem) {
  2414. /**
  2415. * Creates a new TextDocumentItem literal.
  2416. * @param uri The document's uri.
  2417. * @param languageId The document's language identifier.
  2418. * @param version The document's version number.
  2419. * @param text The document's text.
  2420. */
  2421. function create(uri, languageId, version, text) {
  2422. return { uri: uri, languageId: languageId, version: version, text: text };
  2423. }
  2424. TextDocumentItem.create = create;
  2425. /**
  2426. * Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface.
  2427. */
  2428. function is(value) {
  2429. var candidate = value;
  2430. return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.number(candidate.version) && Is.string(candidate.text);
  2431. }
  2432. TextDocumentItem.is = is;
  2433. })(TextDocumentItem = exports.TextDocumentItem || (exports.TextDocumentItem = {}));
  2434. /**
  2435. * Describes the content type that a client supports in various
  2436. * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
  2437. *
  2438. * Please note that `MarkupKinds` must not start with a `$`. This kinds
  2439. * are reserved for internal usage.
  2440. */
  2441. var MarkupKind;
  2442. (function (MarkupKind) {
  2443. /**
  2444. * Plain text is supported as a content format
  2445. */
  2446. MarkupKind.PlainText = 'plaintext';
  2447. /**
  2448. * Markdown is supported as a content format
  2449. */
  2450. MarkupKind.Markdown = 'markdown';
  2451. })(MarkupKind = exports.MarkupKind || (exports.MarkupKind = {}));
  2452. (function (MarkupKind) {
  2453. /**
  2454. * Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type.
  2455. */
  2456. function is(value) {
  2457. var candidate = value;
  2458. return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;
  2459. }
  2460. MarkupKind.is = is;
  2461. })(MarkupKind = exports.MarkupKind || (exports.MarkupKind = {}));
  2462. var MarkupContent;
  2463. (function (MarkupContent) {
  2464. /**
  2465. * Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface.
  2466. */
  2467. function is(value) {
  2468. var candidate = value;
  2469. return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
  2470. }
  2471. MarkupContent.is = is;
  2472. })(MarkupContent = exports.MarkupContent || (exports.MarkupContent = {}));
  2473. /**
  2474. * The kind of a completion entry.
  2475. */
  2476. var CompletionItemKind;
  2477. (function (CompletionItemKind) {
  2478. CompletionItemKind.Text = 1;
  2479. CompletionItemKind.Method = 2;
  2480. CompletionItemKind.Function = 3;
  2481. CompletionItemKind.Constructor = 4;
  2482. CompletionItemKind.Field = 5;
  2483. CompletionItemKind.Variable = 6;
  2484. CompletionItemKind.Class = 7;
  2485. CompletionItemKind.Interface = 8;
  2486. CompletionItemKind.Module = 9;
  2487. CompletionItemKind.Property = 10;
  2488. CompletionItemKind.Unit = 11;
  2489. CompletionItemKind.Value = 12;
  2490. CompletionItemKind.Enum = 13;
  2491. CompletionItemKind.Keyword = 14;
  2492. CompletionItemKind.Snippet = 15;
  2493. CompletionItemKind.Color = 16;
  2494. CompletionItemKind.File = 17;
  2495. CompletionItemKind.Reference = 18;
  2496. CompletionItemKind.Folder = 19;
  2497. CompletionItemKind.EnumMember = 20;
  2498. CompletionItemKind.Constant = 21;
  2499. CompletionItemKind.Struct = 22;
  2500. CompletionItemKind.Event = 23;
  2501. CompletionItemKind.Operator = 24;
  2502. CompletionItemKind.TypeParameter = 25;
  2503. })(CompletionItemKind = exports.CompletionItemKind || (exports.CompletionItemKind = {}));
  2504. /**
  2505. * Defines whether the insert text in a completion item should be interpreted as
  2506. * plain text or a snippet.
  2507. */
  2508. var InsertTextFormat;
  2509. (function (InsertTextFormat) {
  2510. /**
  2511. * The primary text to be inserted is treated as a plain string.
  2512. */
  2513. InsertTextFormat.PlainText = 1;
  2514. /**
  2515. * The primary text to be inserted is treated as a snippet.
  2516. *
  2517. * A snippet can define tab stops and placeholders with `$1`, `$2`
  2518. * and `${3:foo}`. `$0` defines the final tab stop, it defaults to
  2519. * the end of the snippet. Placeholders with equal identifiers are linked,
  2520. * that is typing in one will update others too.
  2521. *
  2522. * See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md
  2523. */
  2524. InsertTextFormat.Snippet = 2;
  2525. })(InsertTextFormat = exports.InsertTextFormat || (exports.InsertTextFormat = {}));
  2526. /**
  2527. * Completion item tags are extra annotations that tweak the rendering of a completion
  2528. * item.
  2529. *
  2530. * @since 3.15.0
  2531. */
  2532. var CompletionItemTag;
  2533. (function (CompletionItemTag) {
  2534. /**
  2535. * Render a completion as obsolete, usually using a strike-out.
  2536. */
  2537. CompletionItemTag.Deprecated = 1;
  2538. })(CompletionItemTag = exports.CompletionItemTag || (exports.CompletionItemTag = {}));
  2539. /**
  2540. * The CompletionItem namespace provides functions to deal with
  2541. * completion items.
  2542. */
  2543. var CompletionItem;
  2544. (function (CompletionItem) {
  2545. /**
  2546. * Create a completion item and seed it with a label.
  2547. * @param label The completion item's label
  2548. */
  2549. function create(label) {
  2550. return { label: label };
  2551. }
  2552. CompletionItem.create = create;
  2553. })(CompletionItem = exports.CompletionItem || (exports.CompletionItem = {}));
  2554. /**
  2555. * The CompletionList namespace provides functions to deal with
  2556. * completion lists.
  2557. */
  2558. var CompletionList;
  2559. (function (CompletionList) {
  2560. /**
  2561. * Creates a new completion list.
  2562. *
  2563. * @param items The completion items.
  2564. * @param isIncomplete The list is not complete.
  2565. */
  2566. function create(items, isIncomplete) {
  2567. return { items: items ? items : [], isIncomplete: !!isIncomplete };
  2568. }
  2569. CompletionList.create = create;
  2570. })(CompletionList = exports.CompletionList || (exports.CompletionList = {}));
  2571. var MarkedString;
  2572. (function (MarkedString) {
  2573. /**
  2574. * Creates a marked string from plain text.
  2575. *
  2576. * @param plainText The plain text.
  2577. */
  2578. function fromPlainText(plainText) {
  2579. return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
  2580. }
  2581. MarkedString.fromPlainText = fromPlainText;
  2582. /**
  2583. * Checks whether the given value conforms to the [MarkedString](#MarkedString) type.
  2584. */
  2585. function is(value) {
  2586. var candidate = value;
  2587. return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));
  2588. }
  2589. MarkedString.is = is;
  2590. })(MarkedString = exports.MarkedString || (exports.MarkedString = {}));
  2591. var Hover;
  2592. (function (Hover) {
  2593. /**
  2594. * Checks whether the given value conforms to the [Hover](#Hover) interface.
  2595. */
  2596. function is(value) {
  2597. var candidate = value;
  2598. return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||
  2599. MarkedString.is(candidate.contents) ||
  2600. Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));
  2601. }
  2602. Hover.is = is;
  2603. })(Hover = exports.Hover || (exports.Hover = {}));
  2604. /**
  2605. * The ParameterInformation namespace provides helper functions to work with
  2606. * [ParameterInformation](#ParameterInformation) literals.
  2607. */
  2608. var ParameterInformation;
  2609. (function (ParameterInformation) {
  2610. /**
  2611. * Creates a new parameter information literal.
  2612. *
  2613. * @param label A label string.
  2614. * @param documentation A doc string.
  2615. */
  2616. function create(label, documentation) {
  2617. return documentation ? { label: label, documentation: documentation } : { label: label };
  2618. }
  2619. ParameterInformation.create = create;
  2620. })(ParameterInformation = exports.ParameterInformation || (exports.ParameterInformation = {}));
  2621. /**
  2622. * The SignatureInformation namespace provides helper functions to work with
  2623. * [SignatureInformation](#SignatureInformation) literals.
  2624. */
  2625. var SignatureInformation;
  2626. (function (SignatureInformation) {
  2627. function create(label, documentation) {
  2628. var parameters = [];
  2629. for (var _i = 2; _i < arguments.length; _i++) {
  2630. parameters[_i - 2] = arguments[_i];
  2631. }
  2632. var result = { label: label };
  2633. if (Is.defined(documentation)) {
  2634. result.documentation = documentation;
  2635. }
  2636. if (Is.defined(parameters)) {
  2637. result.parameters = parameters;
  2638. }
  2639. else {
  2640. result.parameters = [];
  2641. }
  2642. return result;
  2643. }
  2644. SignatureInformation.create = create;
  2645. })(SignatureInformation = exports.SignatureInformation || (exports.SignatureInformation = {}));
  2646. /**
  2647. * A document highlight kind.
  2648. */
  2649. var DocumentHighlightKind;
  2650. (function (DocumentHighlightKind) {
  2651. /**
  2652. * A textual occurrence.
  2653. */
  2654. DocumentHighlightKind.Text = 1;
  2655. /**
  2656. * Read-access of a symbol, like reading a variable.
  2657. */
  2658. DocumentHighlightKind.Read = 2;
  2659. /**
  2660. * Write-access of a symbol, like writing to a variable.
  2661. */
  2662. DocumentHighlightKind.Write = 3;
  2663. })(DocumentHighlightKind = exports.DocumentHighlightKind || (exports.DocumentHighlightKind = {}));
  2664. /**
  2665. * DocumentHighlight namespace to provide helper functions to work with
  2666. * [DocumentHighlight](#DocumentHighlight) literals.
  2667. */
  2668. var DocumentHighlight;
  2669. (function (DocumentHighlight) {
  2670. /**
  2671. * Create a DocumentHighlight object.
  2672. * @param range The range the highlight applies to.
  2673. */
  2674. function create(range, kind) {
  2675. var result = { range: range };
  2676. if (Is.number(kind)) {
  2677. result.kind = kind;
  2678. }
  2679. return result;
  2680. }
  2681. DocumentHighlight.create = create;
  2682. })(DocumentHighlight = exports.DocumentHighlight || (exports.DocumentHighlight = {}));
  2683. /**
  2684. * A symbol kind.
  2685. */
  2686. var SymbolKind;
  2687. (function (SymbolKind) {
  2688. SymbolKind.File = 1;
  2689. SymbolKind.Module = 2;
  2690. SymbolKind.Namespace = 3;
  2691. SymbolKind.Package = 4;
  2692. SymbolKind.Class = 5;
  2693. SymbolKind.Method = 6;
  2694. SymbolKind.Property = 7;
  2695. SymbolKind.Field = 8;
  2696. SymbolKind.Constructor = 9;
  2697. SymbolKind.Enum = 10;
  2698. SymbolKind.Interface = 11;
  2699. SymbolKind.Function = 12;
  2700. SymbolKind.Variable = 13;
  2701. SymbolKind.Constant = 14;
  2702. SymbolKind.String = 15;
  2703. SymbolKind.Number = 16;
  2704. SymbolKind.Boolean = 17;
  2705. SymbolKind.Array = 18;
  2706. SymbolKind.Object = 19;
  2707. SymbolKind.Key = 20;
  2708. SymbolKind.Null = 21;
  2709. SymbolKind.EnumMember = 22;
  2710. SymbolKind.Struct = 23;
  2711. SymbolKind.Event = 24;
  2712. SymbolKind.Operator = 25;
  2713. SymbolKind.TypeParameter = 26;
  2714. })(SymbolKind = exports.SymbolKind || (exports.SymbolKind = {}));
  2715. /**
  2716. * Symbol tags are extra annotations that tweak the rendering of a symbol.
  2717. * @since 3.15
  2718. */
  2719. var SymbolTag;
  2720. (function (SymbolTag) {
  2721. /**
  2722. * Render a symbol as obsolete, usually using a strike-out.
  2723. */
  2724. SymbolTag.Deprecated = 1;
  2725. })(SymbolTag = exports.SymbolTag || (exports.SymbolTag = {}));
  2726. var SymbolInformation;
  2727. (function (SymbolInformation) {
  2728. /**
  2729. * Creates a new symbol information literal.
  2730. *
  2731. * @param name The name of the symbol.
  2732. * @param kind The kind of the symbol.
  2733. * @param range The range of the location of the symbol.
  2734. * @param uri The resource of the location of symbol, defaults to the current document.
  2735. * @param containerName The name of the symbol containing the symbol.
  2736. */
  2737. function create(name, kind, range, uri, containerName) {
  2738. var result = {
  2739. name: name,
  2740. kind: kind,
  2741. location: { uri: uri, range: range }
  2742. };
  2743. if (containerName) {
  2744. result.containerName = containerName;
  2745. }
  2746. return result;
  2747. }
  2748. SymbolInformation.create = create;
  2749. })(SymbolInformation = exports.SymbolInformation || (exports.SymbolInformation = {}));
  2750. var DocumentSymbol;
  2751. (function (DocumentSymbol) {
  2752. /**
  2753. * Creates a new symbol information literal.
  2754. *
  2755. * @param name The name of the symbol.
  2756. * @param detail The detail of the symbol.
  2757. * @param kind The kind of the symbol.
  2758. * @param range The range of the symbol.
  2759. * @param selectionRange The selectionRange of the symbol.
  2760. * @param children Children of the symbol.
  2761. */
  2762. function create(name, detail, kind, range, selectionRange, children) {
  2763. var result = {
  2764. name: name,
  2765. detail: detail,
  2766. kind: kind,
  2767. range: range,
  2768. selectionRange: selectionRange
  2769. };
  2770. if (children !== void 0) {
  2771. result.children = children;
  2772. }
  2773. return result;
  2774. }
  2775. DocumentSymbol.create = create;
  2776. /**
  2777. * Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface.
  2778. */
  2779. function is(value) {
  2780. var candidate = value;
  2781. return candidate &&
  2782. Is.string(candidate.name) && Is.number(candidate.kind) &&
  2783. Range.is(candidate.range) && Range.is(candidate.selectionRange) &&
  2784. (candidate.detail === void 0 || Is.string(candidate.detail)) &&
  2785. (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) &&
  2786. (candidate.children === void 0 || Array.isArray(candidate.children));
  2787. }
  2788. DocumentSymbol.is = is;
  2789. })(DocumentSymbol = exports.DocumentSymbol || (exports.DocumentSymbol = {}));
  2790. /**
  2791. * A set of predefined code action kinds
  2792. */
  2793. var CodeActionKind;
  2794. (function (CodeActionKind) {
  2795. /**
  2796. * Empty kind.
  2797. */
  2798. CodeActionKind.Empty = '';
  2799. /**
  2800. * Base kind for quickfix actions: 'quickfix'
  2801. */
  2802. CodeActionKind.QuickFix = 'quickfix';
  2803. /**
  2804. * Base kind for refactoring actions: 'refactor'
  2805. */
  2806. CodeActionKind.Refactor = 'refactor';
  2807. /**
  2808. * Base kind for refactoring extraction actions: 'refactor.extract'
  2809. *
  2810. * Example extract actions:
  2811. *
  2812. * - Extract method
  2813. * - Extract function
  2814. * - Extract variable
  2815. * - Extract interface from class
  2816. * - ...
  2817. */
  2818. CodeActionKind.RefactorExtract = 'refactor.extract';
  2819. /**
  2820. * Base kind for refactoring inline actions: 'refactor.inline'
  2821. *
  2822. * Example inline actions:
  2823. *
  2824. * - Inline function
  2825. * - Inline variable
  2826. * - Inline constant
  2827. * - ...
  2828. */
  2829. CodeActionKind.RefactorInline = 'refactor.inline';
  2830. /**
  2831. * Base kind for refactoring rewrite actions: 'refactor.rewrite'
  2832. *
  2833. * Example rewrite actions:
  2834. *
  2835. * - Convert JavaScript function to class
  2836. * - Add or remove parameter
  2837. * - Encapsulate field
  2838. * - Make method static
  2839. * - Move method to base class
  2840. * - ...
  2841. */
  2842. CodeActionKind.RefactorRewrite = 'refactor.rewrite';
  2843. /**
  2844. * Base kind for source actions: `source`
  2845. *
  2846. * Source code actions apply to the entire file.
  2847. */
  2848. CodeActionKind.Source = 'source';
  2849. /**
  2850. * Base kind for an organize imports source action: `source.organizeImports`
  2851. */
  2852. CodeActionKind.SourceOrganizeImports = 'source.organizeImports';
  2853. /**
  2854. * Base kind for auto-fix source actions: `source.fixAll`.
  2855. *
  2856. * Fix all actions automatically fix errors that have a clear fix that do not require user input.
  2857. * They should not suppress errors or perform unsafe fixes such as generating new types or classes.
  2858. *
  2859. * @since 3.15.0
  2860. */
  2861. CodeActionKind.SourceFixAll = 'source.fixAll';
  2862. })(CodeActionKind = exports.CodeActionKind || (exports.CodeActionKind = {}));
  2863. /**
  2864. * The CodeActionContext namespace provides helper functions to work with
  2865. * [CodeActionContext](#CodeActionContext) literals.
  2866. */
  2867. var CodeActionContext;
  2868. (function (CodeActionContext) {
  2869. /**
  2870. * Creates a new CodeActionContext literal.
  2871. */
  2872. function create(diagnostics, only) {
  2873. var result = { diagnostics: diagnostics };
  2874. if (only !== void 0 && only !== null) {
  2875. result.only = only;
  2876. }
  2877. return result;
  2878. }
  2879. CodeActionContext.create = create;
  2880. /**
  2881. * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface.
  2882. */
  2883. function is(value) {
  2884. var candidate = value;
  2885. return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string));
  2886. }
  2887. CodeActionContext.is = is;
  2888. })(CodeActionContext = exports.CodeActionContext || (exports.CodeActionContext = {}));
  2889. var CodeAction;
  2890. (function (CodeAction) {
  2891. function create(title, commandOrEdit, kind) {
  2892. var result = { title: title };
  2893. if (Command.is(commandOrEdit)) {
  2894. result.command = commandOrEdit;
  2895. }
  2896. else {
  2897. result.edit = commandOrEdit;
  2898. }
  2899. if (kind !== void 0) {
  2900. result.kind = kind;
  2901. }
  2902. return result;
  2903. }
  2904. CodeAction.create = create;
  2905. function is(value) {
  2906. var candidate = value;
  2907. return candidate && Is.string(candidate.title) &&
  2908. (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&
  2909. (candidate.kind === void 0 || Is.string(candidate.kind)) &&
  2910. (candidate.edit !== void 0 || candidate.command !== void 0) &&
  2911. (candidate.command === void 0 || Command.is(candidate.command)) &&
  2912. (candidate.isPreferred === void 0 || Is.boolean(candidate.isPreferred)) &&
  2913. (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));
  2914. }
  2915. CodeAction.is = is;
  2916. })(CodeAction = exports.CodeAction || (exports.CodeAction = {}));
  2917. /**
  2918. * The CodeLens namespace provides helper functions to work with
  2919. * [CodeLens](#CodeLens) literals.
  2920. */
  2921. var CodeLens;
  2922. (function (CodeLens) {
  2923. /**
  2924. * Creates a new CodeLens literal.
  2925. */
  2926. function create(range, data) {
  2927. var result = { range: range };
  2928. if (Is.defined(data)) {
  2929. result.data = data;
  2930. }
  2931. return result;
  2932. }
  2933. CodeLens.create = create;
  2934. /**
  2935. * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface.
  2936. */
  2937. function is(value) {
  2938. var candidate = value;
  2939. return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
  2940. }
  2941. CodeLens.is = is;
  2942. })(CodeLens = exports.CodeLens || (exports.CodeLens = {}));
  2943. /**
  2944. * The FormattingOptions namespace provides helper functions to work with
  2945. * [FormattingOptions](#FormattingOptions) literals.
  2946. */
  2947. var FormattingOptions;
  2948. (function (FormattingOptions) {
  2949. /**
  2950. * Creates a new FormattingOptions literal.
  2951. */
  2952. function create(tabSize, insertSpaces) {
  2953. return { tabSize: tabSize, insertSpaces: insertSpaces };
  2954. }
  2955. FormattingOptions.create = create;
  2956. /**
  2957. * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface.
  2958. */
  2959. function is(value) {
  2960. var candidate = value;
  2961. return Is.defined(candidate) && Is.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
  2962. }
  2963. FormattingOptions.is = is;
  2964. })(FormattingOptions = exports.FormattingOptions || (exports.FormattingOptions = {}));
  2965. /**
  2966. * The DocumentLink namespace provides helper functions to work with
  2967. * [DocumentLink](#DocumentLink) literals.
  2968. */
  2969. var DocumentLink;
  2970. (function (DocumentLink) {
  2971. /**
  2972. * Creates a new DocumentLink literal.
  2973. */
  2974. function create(range, target, data) {
  2975. return { range: range, target: target, data: data };
  2976. }
  2977. DocumentLink.create = create;
  2978. /**
  2979. * Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface.
  2980. */
  2981. function is(value) {
  2982. var candidate = value;
  2983. return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
  2984. }
  2985. DocumentLink.is = is;
  2986. })(DocumentLink = exports.DocumentLink || (exports.DocumentLink = {}));
  2987. /**
  2988. * The SelectionRange namespace provides helper function to work with
  2989. * SelectionRange literals.
  2990. */
  2991. var SelectionRange;
  2992. (function (SelectionRange) {
  2993. /**
  2994. * Creates a new SelectionRange
  2995. * @param range the range.
  2996. * @param parent an optional parent.
  2997. */
  2998. function create(range, parent) {
  2999. return { range: range, parent: parent };
  3000. }
  3001. SelectionRange.create = create;
  3002. function is(value) {
  3003. var candidate = value;
  3004. return candidate !== undefined && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));
  3005. }
  3006. SelectionRange.is = is;
  3007. })(SelectionRange = exports.SelectionRange || (exports.SelectionRange = {}));
  3008. exports.EOL = ['\n', '\r\n', '\r'];
  3009. /**
  3010. * @deprecated Use the text document from the new vscode-languageserver-textdocument package.
  3011. */
  3012. var TextDocument;
  3013. (function (TextDocument) {
  3014. /**
  3015. * Creates a new ITextDocument literal from the given uri and content.
  3016. * @param uri The document's uri.
  3017. * @param languageId The document's language Id.
  3018. * @param content The document's content.
  3019. */
  3020. function create(uri, languageId, version, content) {
  3021. return new FullTextDocument(uri, languageId, version, content);
  3022. }
  3023. TextDocument.create = create;
  3024. /**
  3025. * Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface.
  3026. */
  3027. function is(value) {
  3028. var candidate = value;
  3029. return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.number(candidate.lineCount)
  3030. && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
  3031. }
  3032. TextDocument.is = is;
  3033. function applyEdits(document, edits) {
  3034. var text = document.getText();
  3035. var sortedEdits = mergeSort(edits, function (a, b) {
  3036. var diff = a.range.start.line - b.range.start.line;
  3037. if (diff === 0) {
  3038. return a.range.start.character - b.range.start.character;
  3039. }
  3040. return diff;
  3041. });
  3042. var lastModifiedOffset = text.length;
  3043. for (var i = sortedEdits.length - 1; i >= 0; i--) {
  3044. var e = sortedEdits[i];
  3045. var startOffset = document.offsetAt(e.range.start);
  3046. var endOffset = document.offsetAt(e.range.end);
  3047. if (endOffset <= lastModifiedOffset) {
  3048. text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
  3049. }
  3050. else {
  3051. throw new Error('Overlapping edit');
  3052. }
  3053. lastModifiedOffset = startOffset;
  3054. }
  3055. return text;
  3056. }
  3057. TextDocument.applyEdits = applyEdits;
  3058. function mergeSort(data, compare) {
  3059. if (data.length <= 1) {
  3060. // sorted
  3061. return data;
  3062. }
  3063. var p = (data.length / 2) | 0;
  3064. var left = data.slice(0, p);
  3065. var right = data.slice(p);
  3066. mergeSort(left, compare);
  3067. mergeSort(right, compare);
  3068. var leftIdx = 0;
  3069. var rightIdx = 0;
  3070. var i = 0;
  3071. while (leftIdx < left.length && rightIdx < right.length) {
  3072. var ret = compare(left[leftIdx], right[rightIdx]);
  3073. if (ret <= 0) {
  3074. // smaller_equal -> take left to preserve order
  3075. data[i++] = left[leftIdx++];
  3076. }
  3077. else {
  3078. // greater -> take right
  3079. data[i++] = right[rightIdx++];
  3080. }
  3081. }
  3082. while (leftIdx < left.length) {
  3083. data[i++] = left[leftIdx++];
  3084. }
  3085. while (rightIdx < right.length) {
  3086. data[i++] = right[rightIdx++];
  3087. }
  3088. return data;
  3089. }
  3090. })(TextDocument = exports.TextDocument || (exports.TextDocument = {}));
  3091. var FullTextDocument = /** @class */ (function () {
  3092. function FullTextDocument(uri, languageId, version, content) {
  3093. this._uri = uri;
  3094. this._languageId = languageId;
  3095. this._version = version;
  3096. this._content = content;
  3097. this._lineOffsets = undefined;
  3098. }
  3099. Object.defineProperty(FullTextDocument.prototype, "uri", {
  3100. get: function () {
  3101. return this._uri;
  3102. },
  3103. enumerable: true,
  3104. configurable: true
  3105. });
  3106. Object.defineProperty(FullTextDocument.prototype, "languageId", {
  3107. get: function () {
  3108. return this._languageId;
  3109. },
  3110. enumerable: true,
  3111. configurable: true
  3112. });
  3113. Object.defineProperty(FullTextDocument.prototype, "version", {
  3114. get: function () {
  3115. return this._version;
  3116. },
  3117. enumerable: true,
  3118. configurable: true
  3119. });
  3120. FullTextDocument.prototype.getText = function (range) {
  3121. if (range) {
  3122. var start = this.offsetAt(range.start);
  3123. var end = this.offsetAt(range.end);
  3124. return this._content.substring(start, end);
  3125. }
  3126. return this._content;
  3127. };
  3128. FullTextDocument.prototype.update = function (event, version) {
  3129. this._content = event.text;
  3130. this._version = version;
  3131. this._lineOffsets = undefined;
  3132. };
  3133. FullTextDocument.prototype.getLineOffsets = function () {
  3134. if (this._lineOffsets === undefined) {
  3135. var lineOffsets = [];
  3136. var text = this._content;
  3137. var isLineStart = true;
  3138. for (var i = 0; i < text.length; i++) {
  3139. if (isLineStart) {
  3140. lineOffsets.push(i);
  3141. isLineStart = false;
  3142. }
  3143. var ch = text.charAt(i);
  3144. isLineStart = (ch === '\r' || ch === '\n');
  3145. if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {
  3146. i++;
  3147. }
  3148. }
  3149. if (isLineStart && text.length > 0) {
  3150. lineOffsets.push(text.length);
  3151. }
  3152. this._lineOffsets = lineOffsets;
  3153. }
  3154. return this._lineOffsets;
  3155. };
  3156. FullTextDocument.prototype.positionAt = function (offset) {
  3157. offset = Math.max(Math.min(offset, this._content.length), 0);
  3158. var lineOffsets = this.getLineOffsets();
  3159. var low = 0, high = lineOffsets.length;
  3160. if (high === 0) {
  3161. return Position.create(0, offset);
  3162. }
  3163. while (low < high) {
  3164. var mid = Math.floor((low + high) / 2);
  3165. if (lineOffsets[mid] > offset) {
  3166. high = mid;
  3167. }
  3168. else {
  3169. low = mid + 1;
  3170. }
  3171. }
  3172. // low is the least x for which the line offset is larger than the current offset
  3173. // or array.length if no line offset is larger than the current offset
  3174. var line = low - 1;
  3175. return Position.create(line, offset - lineOffsets[line]);
  3176. };
  3177. FullTextDocument.prototype.offsetAt = function (position) {
  3178. var lineOffsets = this.getLineOffsets();
  3179. if (position.line >= lineOffsets.length) {
  3180. return this._content.length;
  3181. }
  3182. else if (position.line < 0) {
  3183. return 0;
  3184. }
  3185. var lineOffset = lineOffsets[position.line];
  3186. var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
  3187. return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
  3188. };
  3189. Object.defineProperty(FullTextDocument.prototype, "lineCount", {
  3190. get: function () {
  3191. return this.getLineOffsets().length;
  3192. },
  3193. enumerable: true,
  3194. configurable: true
  3195. });
  3196. return FullTextDocument;
  3197. }());
  3198. var Is;
  3199. (function (Is) {
  3200. var toString = Object.prototype.toString;
  3201. function defined(value) {
  3202. return typeof value !== 'undefined';
  3203. }
  3204. Is.defined = defined;
  3205. function undefined(value) {
  3206. return typeof value === 'undefined';
  3207. }
  3208. Is.undefined = undefined;
  3209. function boolean(value) {
  3210. return value === true || value === false;
  3211. }
  3212. Is.boolean = boolean;
  3213. function string(value) {
  3214. return toString.call(value) === '[object String]';
  3215. }
  3216. Is.string = string;
  3217. function number(value) {
  3218. return toString.call(value) === '[object Number]';
  3219. }
  3220. Is.number = number;
  3221. function func(value) {
  3222. return toString.call(value) === '[object Function]';
  3223. }
  3224. Is.func = func;
  3225. function objectLiteral(value) {
  3226. // Strictly speaking class instances pass this check as well. Since the LSP
  3227. // doesn't use classes we ignore this for now. If we do we need to add something
  3228. // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
  3229. return value !== null && typeof value === 'object';
  3230. }
  3231. Is.objectLiteral = objectLiteral;
  3232. function typedArray(value, check) {
  3233. return Array.isArray(value) && value.every(check);
  3234. }
  3235. Is.typedArray = typedArray;
  3236. })(Is || (Is = {}));
  3237. });
  3238. define('vscode-languageserver-types', ['vscode-languageserver-types/main'], function (main) { return main; });
  3239. (function (factory) {
  3240. if (typeof module === "object" && typeof module.exports === "object") {
  3241. var v = factory(require, exports);
  3242. if (v !== undefined) module.exports = v;
  3243. }
  3244. else if (typeof define === "function" && define.amd) {
  3245. define('vscode-languageserver-textdocument/main',["require", "exports"], factory);
  3246. }
  3247. })(function (require, exports) {
  3248. /* --------------------------------------------------------------------------------------------
  3249. * Copyright (c) Microsoft Corporation. All rights reserved.
  3250. * Licensed under the MIT License. See License.txt in the project root for license information.
  3251. * ------------------------------------------------------------------------------------------ */
  3252. 'use strict';
  3253. Object.defineProperty(exports, "__esModule", { value: true });
  3254. var FullTextDocument = /** @class */ (function () {
  3255. function FullTextDocument(uri, languageId, version, content) {
  3256. this._uri = uri;
  3257. this._languageId = languageId;
  3258. this._version = version;
  3259. this._content = content;
  3260. this._lineOffsets = undefined;
  3261. }
  3262. Object.defineProperty(FullTextDocument.prototype, "uri", {
  3263. get: function () {
  3264. return this._uri;
  3265. },
  3266. enumerable: true,
  3267. configurable: true
  3268. });
  3269. Object.defineProperty(FullTextDocument.prototype, "languageId", {
  3270. get: function () {
  3271. return this._languageId;
  3272. },
  3273. enumerable: true,
  3274. configurable: true
  3275. });
  3276. Object.defineProperty(FullTextDocument.prototype, "version", {
  3277. get: function () {
  3278. return this._version;
  3279. },
  3280. enumerable: true,
  3281. configurable: true
  3282. });
  3283. FullTextDocument.prototype.getText = function (range) {
  3284. if (range) {
  3285. var start = this.offsetAt(range.start);
  3286. var end = this.offsetAt(range.end);
  3287. return this._content.substring(start, end);
  3288. }
  3289. return this._content;
  3290. };
  3291. FullTextDocument.prototype.update = function (changes, version) {
  3292. for (var _i = 0, changes_1 = changes; _i < changes_1.length; _i++) {
  3293. var change = changes_1[_i];
  3294. if (FullTextDocument.isIncremental(change)) {
  3295. // makes sure start is before end
  3296. var range = getWellformedRange(change.range);
  3297. // update content
  3298. var startOffset = this.offsetAt(range.start);
  3299. var endOffset = this.offsetAt(range.end);
  3300. this._content = this._content.substring(0, startOffset) + change.text + this._content.substring(endOffset, this._content.length);
  3301. // update the offsets
  3302. var startLine = Math.max(range.start.line, 0);
  3303. var endLine = Math.max(range.end.line, 0);
  3304. var lineOffsets = this._lineOffsets;
  3305. var addedLineOffsets = computeLineOffsets(change.text, false, startOffset);
  3306. if (endLine - startLine === addedLineOffsets.length) {
  3307. for (var i = 0, len = addedLineOffsets.length; i < len; i++) {
  3308. lineOffsets[i + startLine + 1] = addedLineOffsets[i];
  3309. }
  3310. }
  3311. else {
  3312. if (addedLineOffsets.length < 10000) {
  3313. lineOffsets.splice.apply(lineOffsets, [startLine + 1, endLine - startLine].concat(addedLineOffsets));
  3314. }
  3315. else { // avoid too many arguments for splice
  3316. this._lineOffsets = lineOffsets = lineOffsets.slice(0, startLine + 1).concat(addedLineOffsets, lineOffsets.slice(endLine + 1));
  3317. }
  3318. }
  3319. var diff = change.text.length - (endOffset - startOffset);
  3320. if (diff !== 0) {
  3321. for (var i = startLine + 1 + addedLineOffsets.length, len = lineOffsets.length; i < len; i++) {
  3322. lineOffsets[i] = lineOffsets[i] + diff;
  3323. }
  3324. }
  3325. }
  3326. else if (FullTextDocument.isFull(change)) {
  3327. this._content = change.text;
  3328. this._lineOffsets = undefined;
  3329. }
  3330. else {
  3331. throw new Error('Unknown change event received');
  3332. }
  3333. }
  3334. this._version = version;
  3335. };
  3336. FullTextDocument.prototype.getLineOffsets = function () {
  3337. if (this._lineOffsets === undefined) {
  3338. this._lineOffsets = computeLineOffsets(this._content, true);
  3339. }
  3340. return this._lineOffsets;
  3341. };
  3342. FullTextDocument.prototype.positionAt = function (offset) {
  3343. offset = Math.max(Math.min(offset, this._content.length), 0);
  3344. var lineOffsets = this.getLineOffsets();
  3345. var low = 0, high = lineOffsets.length;
  3346. if (high === 0) {
  3347. return { line: 0, character: offset };
  3348. }
  3349. while (low < high) {
  3350. var mid = Math.floor((low + high) / 2);
  3351. if (lineOffsets[mid] > offset) {
  3352. high = mid;
  3353. }
  3354. else {
  3355. low = mid + 1;
  3356. }
  3357. }
  3358. // low is the least x for which the line offset is larger than the current offset
  3359. // or array.length if no line offset is larger than the current offset
  3360. var line = low - 1;
  3361. return { line: line, character: offset - lineOffsets[line] };
  3362. };
  3363. FullTextDocument.prototype.offsetAt = function (position) {
  3364. var lineOffsets = this.getLineOffsets();
  3365. if (position.line >= lineOffsets.length) {
  3366. return this._content.length;
  3367. }
  3368. else if (position.line < 0) {
  3369. return 0;
  3370. }
  3371. var lineOffset = lineOffsets[position.line];
  3372. var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
  3373. return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
  3374. };
  3375. Object.defineProperty(FullTextDocument.prototype, "lineCount", {
  3376. get: function () {
  3377. return this.getLineOffsets().length;
  3378. },
  3379. enumerable: true,
  3380. configurable: true
  3381. });
  3382. FullTextDocument.isIncremental = function (event) {
  3383. var candidate = event;
  3384. return candidate !== undefined && candidate !== null &&
  3385. typeof candidate.text === 'string' && candidate.range !== undefined &&
  3386. (candidate.rangeLength === undefined || typeof candidate.rangeLength === 'number');
  3387. };
  3388. FullTextDocument.isFull = function (event) {
  3389. var candidate = event;
  3390. return candidate !== undefined && candidate !== null &&
  3391. typeof candidate.text === 'string' && candidate.range === undefined && candidate.rangeLength === undefined;
  3392. };
  3393. return FullTextDocument;
  3394. }());
  3395. var TextDocument;
  3396. (function (TextDocument) {
  3397. /**
  3398. * Creates a new text document.
  3399. *
  3400. * @param uri The document's uri.
  3401. * @param languageId The document's language Id.
  3402. * @param version The document's initial version number.
  3403. * @param content The document's content.
  3404. */
  3405. function create(uri, languageId, version, content) {
  3406. return new FullTextDocument(uri, languageId, version, content);
  3407. }
  3408. TextDocument.create = create;
  3409. /**
  3410. * Updates a TextDocument by modifing its content.
  3411. *
  3412. * @param document the document to update. Only documents created by TextDocument.create are valid inputs.
  3413. * @param changes the changes to apply to the document.
  3414. * @returns The updated TextDocument. Note: That's the same document instance passed in as first parameter.
  3415. *
  3416. */
  3417. function update(document, changes, version) {
  3418. if (document instanceof FullTextDocument) {
  3419. document.update(changes, version);
  3420. return document;
  3421. }
  3422. else {
  3423. throw new Error('TextDocument.update: document must be created by TextDocument.create');
  3424. }
  3425. }
  3426. TextDocument.update = update;
  3427. function applyEdits(document, edits) {
  3428. var text = document.getText();
  3429. var sortedEdits = mergeSort(edits.map(getWellformedEdit), function (a, b) {
  3430. var diff = a.range.start.line - b.range.start.line;
  3431. if (diff === 0) {
  3432. return a.range.start.character - b.range.start.character;
  3433. }
  3434. return diff;
  3435. });
  3436. var lastModifiedOffset = text.length;
  3437. for (var i = sortedEdits.length - 1; i >= 0; i--) {
  3438. var e = sortedEdits[i];
  3439. var startOffset = document.offsetAt(e.range.start);
  3440. var endOffset = document.offsetAt(e.range.end);
  3441. if (endOffset <= lastModifiedOffset) {
  3442. text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
  3443. }
  3444. else {
  3445. throw new Error('Overlapping edit');
  3446. }
  3447. lastModifiedOffset = startOffset;
  3448. }
  3449. return text;
  3450. }
  3451. TextDocument.applyEdits = applyEdits;
  3452. })(TextDocument = exports.TextDocument || (exports.TextDocument = {}));
  3453. function mergeSort(data, compare) {
  3454. if (data.length <= 1) {
  3455. // sorted
  3456. return data;
  3457. }
  3458. var p = (data.length / 2) | 0;
  3459. var left = data.slice(0, p);
  3460. var right = data.slice(p);
  3461. mergeSort(left, compare);
  3462. mergeSort(right, compare);
  3463. var leftIdx = 0;
  3464. var rightIdx = 0;
  3465. var i = 0;
  3466. while (leftIdx < left.length && rightIdx < right.length) {
  3467. var ret = compare(left[leftIdx], right[rightIdx]);
  3468. if (ret <= 0) {
  3469. // smaller_equal -> take left to preserve order
  3470. data[i++] = left[leftIdx++];
  3471. }
  3472. else {
  3473. // greater -> take right
  3474. data[i++] = right[rightIdx++];
  3475. }
  3476. }
  3477. while (leftIdx < left.length) {
  3478. data[i++] = left[leftIdx++];
  3479. }
  3480. while (rightIdx < right.length) {
  3481. data[i++] = right[rightIdx++];
  3482. }
  3483. return data;
  3484. }
  3485. function computeLineOffsets(text, isAtLineStart, textOffset) {
  3486. if (textOffset === void 0) { textOffset = 0; }
  3487. var result = isAtLineStart ? [textOffset] : [];
  3488. for (var i = 0; i < text.length; i++) {
  3489. var ch = text.charCodeAt(i);
  3490. if (ch === 13 /* CarriageReturn */ || ch === 10 /* LineFeed */) {
  3491. if (ch === 13 /* CarriageReturn */ && i + 1 < text.length && text.charCodeAt(i + 1) === 10 /* LineFeed */) {
  3492. i++;
  3493. }
  3494. result.push(textOffset + i + 1);
  3495. }
  3496. }
  3497. return result;
  3498. }
  3499. function getWellformedRange(range) {
  3500. var start = range.start;
  3501. var end = range.end;
  3502. if (start.line > end.line || (start.line === end.line && start.character > end.character)) {
  3503. return { start: end, end: start };
  3504. }
  3505. return range;
  3506. }
  3507. function getWellformedEdit(textEdit) {
  3508. var range = getWellformedRange(textEdit.range);
  3509. if (range !== textEdit.range) {
  3510. return { newText: textEdit.newText, range: range };
  3511. }
  3512. return textEdit;
  3513. }
  3514. });
  3515. define('vscode-languageserver-textdocument', ['vscode-languageserver-textdocument/main'], function (main) { return main; });
  3516. (function (factory) {
  3517. if (typeof module === "object" && typeof module.exports === "object") {
  3518. var v = factory(require, exports);
  3519. if (v !== undefined) module.exports = v;
  3520. }
  3521. else if (typeof define === "function" && define.amd) {
  3522. define('vscode-json-languageservice/jsonLanguageTypes',["require", "exports", "vscode-languageserver-types", "vscode-languageserver-textdocument", "vscode-languageserver-types"], factory);
  3523. }
  3524. })(function (require, exports) {
  3525. "use strict";
  3526. function __export(m) {
  3527. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  3528. }
  3529. Object.defineProperty(exports, "__esModule", { value: true });
  3530. var vscode_languageserver_types_1 = require("vscode-languageserver-types");
  3531. var vscode_languageserver_textdocument_1 = require("vscode-languageserver-textdocument");
  3532. exports.TextDocument = vscode_languageserver_textdocument_1.TextDocument;
  3533. __export(require("vscode-languageserver-types"));
  3534. /**
  3535. * Error codes used by diagnostics
  3536. */
  3537. var ErrorCode;
  3538. (function (ErrorCode) {
  3539. ErrorCode[ErrorCode["Undefined"] = 0] = "Undefined";
  3540. ErrorCode[ErrorCode["EnumValueMismatch"] = 1] = "EnumValueMismatch";
  3541. ErrorCode[ErrorCode["UnexpectedEndOfComment"] = 257] = "UnexpectedEndOfComment";
  3542. ErrorCode[ErrorCode["UnexpectedEndOfString"] = 258] = "UnexpectedEndOfString";
  3543. ErrorCode[ErrorCode["UnexpectedEndOfNumber"] = 259] = "UnexpectedEndOfNumber";
  3544. ErrorCode[ErrorCode["InvalidUnicode"] = 260] = "InvalidUnicode";
  3545. ErrorCode[ErrorCode["InvalidEscapeCharacter"] = 261] = "InvalidEscapeCharacter";
  3546. ErrorCode[ErrorCode["InvalidCharacter"] = 262] = "InvalidCharacter";
  3547. ErrorCode[ErrorCode["PropertyExpected"] = 513] = "PropertyExpected";
  3548. ErrorCode[ErrorCode["CommaExpected"] = 514] = "CommaExpected";
  3549. ErrorCode[ErrorCode["ColonExpected"] = 515] = "ColonExpected";
  3550. ErrorCode[ErrorCode["ValueExpected"] = 516] = "ValueExpected";
  3551. ErrorCode[ErrorCode["CommaOrCloseBacketExpected"] = 517] = "CommaOrCloseBacketExpected";
  3552. ErrorCode[ErrorCode["CommaOrCloseBraceExpected"] = 518] = "CommaOrCloseBraceExpected";
  3553. ErrorCode[ErrorCode["TrailingComma"] = 519] = "TrailingComma";
  3554. ErrorCode[ErrorCode["DuplicateKey"] = 520] = "DuplicateKey";
  3555. ErrorCode[ErrorCode["CommentNotPermitted"] = 521] = "CommentNotPermitted";
  3556. ErrorCode[ErrorCode["SchemaResolveError"] = 768] = "SchemaResolveError";
  3557. })(ErrorCode = exports.ErrorCode || (exports.ErrorCode = {}));
  3558. var ClientCapabilities;
  3559. (function (ClientCapabilities) {
  3560. ClientCapabilities.LATEST = {
  3561. textDocument: {
  3562. completion: {
  3563. completionItem: {
  3564. documentationFormat: [vscode_languageserver_types_1.MarkupKind.Markdown, vscode_languageserver_types_1.MarkupKind.PlainText],
  3565. commitCharactersSupport: true
  3566. }
  3567. }
  3568. }
  3569. };
  3570. })(ClientCapabilities = exports.ClientCapabilities || (exports.ClientCapabilities = {}));
  3571. });
  3572. /*---------------------------------------------------------------------------------------------
  3573. * Copyright (c) Microsoft Corporation. All rights reserved.
  3574. * Licensed under the MIT License. See License.txt in the project root for license information.
  3575. *--------------------------------------------------------------------------------------------*/
  3576. define('vscode-nls/vscode-nls',["require", "exports"], function (require, exports) {
  3577. "use strict";
  3578. Object.defineProperty(exports, "__esModule", { value: true });
  3579. function format(message, args) {
  3580. var result;
  3581. if (args.length === 0) {
  3582. result = message;
  3583. }
  3584. else {
  3585. result = message.replace(/\{(\d+)\}/g, function (match, rest) {
  3586. var index = rest[0];
  3587. return typeof args[index] !== 'undefined' ? args[index] : match;
  3588. });
  3589. }
  3590. return result;
  3591. }
  3592. function localize(key, message) {
  3593. var args = [];
  3594. for (var _i = 2; _i < arguments.length; _i++) {
  3595. args[_i - 2] = arguments[_i];
  3596. }
  3597. return format(message, args);
  3598. }
  3599. function loadMessageBundle(file) {
  3600. return localize;
  3601. }
  3602. exports.loadMessageBundle = loadMessageBundle;
  3603. function config(opt) {
  3604. return loadMessageBundle;
  3605. }
  3606. exports.config = config;
  3607. });
  3608. define('vscode-nls', ['vscode-nls/vscode-nls'], function (main) { return main; });
  3609. /*---------------------------------------------------------------------------------------------
  3610. * Copyright (c) Microsoft Corporation. All rights reserved.
  3611. * Licensed under the MIT License. See License.txt in the project root for license information.
  3612. *--------------------------------------------------------------------------------------------*/
  3613. var __extends = (this && this.__extends) || (function () {
  3614. var extendStatics = function (d, b) {
  3615. extendStatics = Object.setPrototypeOf ||
  3616. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  3617. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  3618. return extendStatics(d, b);
  3619. };
  3620. return function (d, b) {
  3621. extendStatics(d, b);
  3622. function __() { this.constructor = d; }
  3623. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3624. };
  3625. })();
  3626. (function (factory) {
  3627. if (typeof module === "object" && typeof module.exports === "object") {
  3628. var v = factory(require, exports);
  3629. if (v !== undefined) module.exports = v;
  3630. }
  3631. else if (typeof define === "function" && define.amd) {
  3632. define('vscode-json-languageservice/parser/jsonParser',["require", "exports", "jsonc-parser", "../utils/objects", "../jsonLanguageTypes", "vscode-nls"], factory);
  3633. }
  3634. })(function (require, exports) {
  3635. "use strict";
  3636. Object.defineProperty(exports, "__esModule", { value: true });
  3637. var Json = require("jsonc-parser");
  3638. var objects_1 = require("../utils/objects");
  3639. var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
  3640. var nls = require("vscode-nls");
  3641. var localize = nls.loadMessageBundle();
  3642. var formats = {
  3643. '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})$/ },
  3644. '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 },
  3645. '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 },
  3646. '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 },
  3647. '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,}))$/ }
  3648. };
  3649. var ASTNodeImpl = /** @class */ (function () {
  3650. function ASTNodeImpl(parent, offset, length) {
  3651. this.offset = offset;
  3652. this.length = length;
  3653. this.parent = parent;
  3654. }
  3655. Object.defineProperty(ASTNodeImpl.prototype, "children", {
  3656. get: function () {
  3657. return [];
  3658. },
  3659. enumerable: true,
  3660. configurable: true
  3661. });
  3662. ASTNodeImpl.prototype.toString = function () {
  3663. return 'type: ' + this.type + ' (' + this.offset + '/' + this.length + ')' + (this.parent ? ' parent: {' + this.parent.toString() + '}' : '');
  3664. };
  3665. return ASTNodeImpl;
  3666. }());
  3667. exports.ASTNodeImpl = ASTNodeImpl;
  3668. var NullASTNodeImpl = /** @class */ (function (_super) {
  3669. __extends(NullASTNodeImpl, _super);
  3670. function NullASTNodeImpl(parent, offset) {
  3671. var _this = _super.call(this, parent, offset) || this;
  3672. _this.type = 'null';
  3673. _this.value = null;
  3674. return _this;
  3675. }
  3676. return NullASTNodeImpl;
  3677. }(ASTNodeImpl));
  3678. exports.NullASTNodeImpl = NullASTNodeImpl;
  3679. var BooleanASTNodeImpl = /** @class */ (function (_super) {
  3680. __extends(BooleanASTNodeImpl, _super);
  3681. function BooleanASTNodeImpl(parent, boolValue, offset) {
  3682. var _this = _super.call(this, parent, offset) || this;
  3683. _this.type = 'boolean';
  3684. _this.value = boolValue;
  3685. return _this;
  3686. }
  3687. return BooleanASTNodeImpl;
  3688. }(ASTNodeImpl));
  3689. exports.BooleanASTNodeImpl = BooleanASTNodeImpl;
  3690. var ArrayASTNodeImpl = /** @class */ (function (_super) {
  3691. __extends(ArrayASTNodeImpl, _super);
  3692. function ArrayASTNodeImpl(parent, offset) {
  3693. var _this = _super.call(this, parent, offset) || this;
  3694. _this.type = 'array';
  3695. _this.items = [];
  3696. return _this;
  3697. }
  3698. Object.defineProperty(ArrayASTNodeImpl.prototype, "children", {
  3699. get: function () {
  3700. return this.items;
  3701. },
  3702. enumerable: true,
  3703. configurable: true
  3704. });
  3705. return ArrayASTNodeImpl;
  3706. }(ASTNodeImpl));
  3707. exports.ArrayASTNodeImpl = ArrayASTNodeImpl;
  3708. var NumberASTNodeImpl = /** @class */ (function (_super) {
  3709. __extends(NumberASTNodeImpl, _super);
  3710. function NumberASTNodeImpl(parent, offset) {
  3711. var _this = _super.call(this, parent, offset) || this;
  3712. _this.type = 'number';
  3713. _this.isInteger = true;
  3714. _this.value = Number.NaN;
  3715. return _this;
  3716. }
  3717. return NumberASTNodeImpl;
  3718. }(ASTNodeImpl));
  3719. exports.NumberASTNodeImpl = NumberASTNodeImpl;
  3720. var StringASTNodeImpl = /** @class */ (function (_super) {
  3721. __extends(StringASTNodeImpl, _super);
  3722. function StringASTNodeImpl(parent, offset, length) {
  3723. var _this = _super.call(this, parent, offset, length) || this;
  3724. _this.type = 'string';
  3725. _this.value = '';
  3726. return _this;
  3727. }
  3728. return StringASTNodeImpl;
  3729. }(ASTNodeImpl));
  3730. exports.StringASTNodeImpl = StringASTNodeImpl;
  3731. var PropertyASTNodeImpl = /** @class */ (function (_super) {
  3732. __extends(PropertyASTNodeImpl, _super);
  3733. function PropertyASTNodeImpl(parent, offset) {
  3734. var _this = _super.call(this, parent, offset) || this;
  3735. _this.type = 'property';
  3736. _this.colonOffset = -1;
  3737. return _this;
  3738. }
  3739. Object.defineProperty(PropertyASTNodeImpl.prototype, "children", {
  3740. get: function () {
  3741. return this.valueNode ? [this.keyNode, this.valueNode] : [this.keyNode];
  3742. },
  3743. enumerable: true,
  3744. configurable: true
  3745. });
  3746. return PropertyASTNodeImpl;
  3747. }(ASTNodeImpl));
  3748. exports.PropertyASTNodeImpl = PropertyASTNodeImpl;
  3749. var ObjectASTNodeImpl = /** @class */ (function (_super) {
  3750. __extends(ObjectASTNodeImpl, _super);
  3751. function ObjectASTNodeImpl(parent, offset) {
  3752. var _this = _super.call(this, parent, offset) || this;
  3753. _this.type = 'object';
  3754. _this.properties = [];
  3755. return _this;
  3756. }
  3757. Object.defineProperty(ObjectASTNodeImpl.prototype, "children", {
  3758. get: function () {
  3759. return this.properties;
  3760. },
  3761. enumerable: true,
  3762. configurable: true
  3763. });
  3764. return ObjectASTNodeImpl;
  3765. }(ASTNodeImpl));
  3766. exports.ObjectASTNodeImpl = ObjectASTNodeImpl;
  3767. function asSchema(schema) {
  3768. if (objects_1.isBoolean(schema)) {
  3769. return schema ? {} : { "not": {} };
  3770. }
  3771. return schema;
  3772. }
  3773. exports.asSchema = asSchema;
  3774. var EnumMatch;
  3775. (function (EnumMatch) {
  3776. EnumMatch[EnumMatch["Key"] = 0] = "Key";
  3777. EnumMatch[EnumMatch["Enum"] = 1] = "Enum";
  3778. })(EnumMatch = exports.EnumMatch || (exports.EnumMatch = {}));
  3779. var SchemaCollector = /** @class */ (function () {
  3780. function SchemaCollector(focusOffset, exclude) {
  3781. if (focusOffset === void 0) { focusOffset = -1; }
  3782. if (exclude === void 0) { exclude = null; }
  3783. this.focusOffset = focusOffset;
  3784. this.exclude = exclude;
  3785. this.schemas = [];
  3786. }
  3787. SchemaCollector.prototype.add = function (schema) {
  3788. this.schemas.push(schema);
  3789. };
  3790. SchemaCollector.prototype.merge = function (other) {
  3791. var _a;
  3792. (_a = this.schemas).push.apply(_a, other.schemas);
  3793. };
  3794. SchemaCollector.prototype.include = function (node) {
  3795. return (this.focusOffset === -1 || contains(node, this.focusOffset)) && (node !== this.exclude);
  3796. };
  3797. SchemaCollector.prototype.newSub = function () {
  3798. return new SchemaCollector(-1, this.exclude);
  3799. };
  3800. return SchemaCollector;
  3801. }());
  3802. var NoOpSchemaCollector = /** @class */ (function () {
  3803. function NoOpSchemaCollector() {
  3804. }
  3805. Object.defineProperty(NoOpSchemaCollector.prototype, "schemas", {
  3806. get: function () { return []; },
  3807. enumerable: true,
  3808. configurable: true
  3809. });
  3810. NoOpSchemaCollector.prototype.add = function (schema) { };
  3811. NoOpSchemaCollector.prototype.merge = function (other) { };
  3812. NoOpSchemaCollector.prototype.include = function (node) { return true; };
  3813. NoOpSchemaCollector.prototype.newSub = function () { return this; };
  3814. NoOpSchemaCollector.instance = new NoOpSchemaCollector();
  3815. return NoOpSchemaCollector;
  3816. }());
  3817. var ValidationResult = /** @class */ (function () {
  3818. function ValidationResult() {
  3819. this.problems = [];
  3820. this.propertiesMatches = 0;
  3821. this.propertiesValueMatches = 0;
  3822. this.primaryValueMatches = 0;
  3823. this.enumValueMatch = false;
  3824. this.enumValues = null;
  3825. }
  3826. ValidationResult.prototype.hasProblems = function () {
  3827. return !!this.problems.length;
  3828. };
  3829. ValidationResult.prototype.mergeAll = function (validationResults) {
  3830. for (var _i = 0, validationResults_1 = validationResults; _i < validationResults_1.length; _i++) {
  3831. var validationResult = validationResults_1[_i];
  3832. this.merge(validationResult);
  3833. }
  3834. };
  3835. ValidationResult.prototype.merge = function (validationResult) {
  3836. this.problems = this.problems.concat(validationResult.problems);
  3837. };
  3838. ValidationResult.prototype.mergeEnumValues = function (validationResult) {
  3839. if (!this.enumValueMatch && !validationResult.enumValueMatch && this.enumValues && validationResult.enumValues) {
  3840. this.enumValues = this.enumValues.concat(validationResult.enumValues);
  3841. for (var _i = 0, _a = this.problems; _i < _a.length; _i++) {
  3842. var error = _a[_i];
  3843. if (error.code === jsonLanguageTypes_1.ErrorCode.EnumValueMismatch) {
  3844. error.message = localize('enumWarning', 'Value is not accepted. Valid values: {0}.', this.enumValues.map(function (v) { return JSON.stringify(v); }).join(', '));
  3845. }
  3846. }
  3847. }
  3848. };
  3849. ValidationResult.prototype.mergePropertyMatch = function (propertyValidationResult) {
  3850. this.merge(propertyValidationResult);
  3851. this.propertiesMatches++;
  3852. if (propertyValidationResult.enumValueMatch || !propertyValidationResult.hasProblems() && propertyValidationResult.propertiesMatches) {
  3853. this.propertiesValueMatches++;
  3854. }
  3855. if (propertyValidationResult.enumValueMatch && propertyValidationResult.enumValues && propertyValidationResult.enumValues.length === 1) {
  3856. this.primaryValueMatches++;
  3857. }
  3858. };
  3859. ValidationResult.prototype.compare = function (other) {
  3860. var hasProblems = this.hasProblems();
  3861. if (hasProblems !== other.hasProblems()) {
  3862. return hasProblems ? -1 : 1;
  3863. }
  3864. if (this.enumValueMatch !== other.enumValueMatch) {
  3865. return other.enumValueMatch ? -1 : 1;
  3866. }
  3867. if (this.primaryValueMatches !== other.primaryValueMatches) {
  3868. return this.primaryValueMatches - other.primaryValueMatches;
  3869. }
  3870. if (this.propertiesValueMatches !== other.propertiesValueMatches) {
  3871. return this.propertiesValueMatches - other.propertiesValueMatches;
  3872. }
  3873. return this.propertiesMatches - other.propertiesMatches;
  3874. };
  3875. return ValidationResult;
  3876. }());
  3877. exports.ValidationResult = ValidationResult;
  3878. function newJSONDocument(root, diagnostics) {
  3879. if (diagnostics === void 0) { diagnostics = []; }
  3880. return new JSONDocument(root, diagnostics, []);
  3881. }
  3882. exports.newJSONDocument = newJSONDocument;
  3883. function getNodeValue(node) {
  3884. return Json.getNodeValue(node);
  3885. }
  3886. exports.getNodeValue = getNodeValue;
  3887. function getNodePath(node) {
  3888. return Json.getNodePath(node);
  3889. }
  3890. exports.getNodePath = getNodePath;
  3891. function contains(node, offset, includeRightBound) {
  3892. if (includeRightBound === void 0) { includeRightBound = false; }
  3893. return offset >= node.offset && offset < (node.offset + node.length) || includeRightBound && offset === (node.offset + node.length);
  3894. }
  3895. exports.contains = contains;
  3896. var JSONDocument = /** @class */ (function () {
  3897. function JSONDocument(root, syntaxErrors, comments) {
  3898. if (syntaxErrors === void 0) { syntaxErrors = []; }
  3899. if (comments === void 0) { comments = []; }
  3900. this.root = root;
  3901. this.syntaxErrors = syntaxErrors;
  3902. this.comments = comments;
  3903. }
  3904. JSONDocument.prototype.getNodeFromOffset = function (offset, includeRightBound) {
  3905. if (includeRightBound === void 0) { includeRightBound = false; }
  3906. if (this.root) {
  3907. return Json.findNodeAtOffset(this.root, offset, includeRightBound);
  3908. }
  3909. return void 0;
  3910. };
  3911. JSONDocument.prototype.visit = function (visitor) {
  3912. if (this.root) {
  3913. var doVisit_1 = function (node) {
  3914. var ctn = visitor(node);
  3915. var children = node.children;
  3916. if (Array.isArray(children)) {
  3917. for (var i = 0; i < children.length && ctn; i++) {
  3918. ctn = doVisit_1(children[i]);
  3919. }
  3920. }
  3921. return ctn;
  3922. };
  3923. doVisit_1(this.root);
  3924. }
  3925. };
  3926. JSONDocument.prototype.validate = function (textDocument, schema) {
  3927. if (this.root && schema) {
  3928. var validationResult = new ValidationResult();
  3929. validate(this.root, schema, validationResult, NoOpSchemaCollector.instance);
  3930. return validationResult.problems.map(function (p) {
  3931. var range = jsonLanguageTypes_1.Range.create(textDocument.positionAt(p.location.offset), textDocument.positionAt(p.location.offset + p.location.length));
  3932. return jsonLanguageTypes_1.Diagnostic.create(range, p.message, p.severity, p.code);
  3933. });
  3934. }
  3935. return null;
  3936. };
  3937. JSONDocument.prototype.getMatchingSchemas = function (schema, focusOffset, exclude) {
  3938. if (focusOffset === void 0) { focusOffset = -1; }
  3939. if (exclude === void 0) { exclude = null; }
  3940. var matchingSchemas = new SchemaCollector(focusOffset, exclude);
  3941. if (this.root && schema) {
  3942. validate(this.root, schema, new ValidationResult(), matchingSchemas);
  3943. }
  3944. return matchingSchemas.schemas;
  3945. };
  3946. return JSONDocument;
  3947. }());
  3948. exports.JSONDocument = JSONDocument;
  3949. function validate(node, schema, validationResult, matchingSchemas) {
  3950. if (!node || !matchingSchemas.include(node)) {
  3951. return;
  3952. }
  3953. switch (node.type) {
  3954. case 'object':
  3955. _validateObjectNode(node, schema, validationResult, matchingSchemas);
  3956. break;
  3957. case 'array':
  3958. _validateArrayNode(node, schema, validationResult, matchingSchemas);
  3959. break;
  3960. case 'string':
  3961. _validateStringNode(node, schema, validationResult, matchingSchemas);
  3962. break;
  3963. case 'number':
  3964. _validateNumberNode(node, schema, validationResult, matchingSchemas);
  3965. break;
  3966. case 'property':
  3967. return validate(node.valueNode, schema, validationResult, matchingSchemas);
  3968. }
  3969. _validateNode();
  3970. matchingSchemas.add({ node: node, schema: schema });
  3971. function _validateNode() {
  3972. function matchesType(type) {
  3973. return node.type === type || (type === 'integer' && node.type === 'number' && node.isInteger);
  3974. }
  3975. if (Array.isArray(schema.type)) {
  3976. if (!schema.type.some(matchesType)) {
  3977. validationResult.problems.push({
  3978. location: { offset: node.offset, length: node.length },
  3979. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  3980. message: schema.errorMessage || localize('typeArrayMismatchWarning', 'Incorrect type. Expected one of {0}.', schema.type.join(', '))
  3981. });
  3982. }
  3983. }
  3984. else if (schema.type) {
  3985. if (!matchesType(schema.type)) {
  3986. validationResult.problems.push({
  3987. location: { offset: node.offset, length: node.length },
  3988. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  3989. message: schema.errorMessage || localize('typeMismatchWarning', 'Incorrect type. Expected "{0}".', schema.type)
  3990. });
  3991. }
  3992. }
  3993. if (Array.isArray(schema.allOf)) {
  3994. for (var _i = 0, _a = schema.allOf; _i < _a.length; _i++) {
  3995. var subSchemaRef = _a[_i];
  3996. validate(node, asSchema(subSchemaRef), validationResult, matchingSchemas);
  3997. }
  3998. }
  3999. var notSchema = asSchema(schema.not);
  4000. if (notSchema) {
  4001. var subValidationResult = new ValidationResult();
  4002. var subMatchingSchemas = matchingSchemas.newSub();
  4003. validate(node, notSchema, subValidationResult, subMatchingSchemas);
  4004. if (!subValidationResult.hasProblems()) {
  4005. validationResult.problems.push({
  4006. location: { offset: node.offset, length: node.length },
  4007. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4008. message: localize('notSchemaWarning', "Matches a schema that is not allowed.")
  4009. });
  4010. }
  4011. for (var _b = 0, _c = subMatchingSchemas.schemas; _b < _c.length; _b++) {
  4012. var ms = _c[_b];
  4013. ms.inverted = !ms.inverted;
  4014. matchingSchemas.add(ms);
  4015. }
  4016. }
  4017. var testAlternatives = function (alternatives, maxOneMatch) {
  4018. var matches = [];
  4019. // remember the best match that is used for error messages
  4020. var bestMatch = null;
  4021. for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) {
  4022. var subSchemaRef = alternatives_1[_i];
  4023. var subSchema = asSchema(subSchemaRef);
  4024. var subValidationResult = new ValidationResult();
  4025. var subMatchingSchemas = matchingSchemas.newSub();
  4026. validate(node, subSchema, subValidationResult, subMatchingSchemas);
  4027. if (!subValidationResult.hasProblems()) {
  4028. matches.push(subSchema);
  4029. }
  4030. if (!bestMatch) {
  4031. bestMatch = { schema: subSchema, validationResult: subValidationResult, matchingSchemas: subMatchingSchemas };
  4032. }
  4033. else {
  4034. if (!maxOneMatch && !subValidationResult.hasProblems() && !bestMatch.validationResult.hasProblems()) {
  4035. // no errors, both are equally good matches
  4036. bestMatch.matchingSchemas.merge(subMatchingSchemas);
  4037. bestMatch.validationResult.propertiesMatches += subValidationResult.propertiesMatches;
  4038. bestMatch.validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches;
  4039. }
  4040. else {
  4041. var compareResult = subValidationResult.compare(bestMatch.validationResult);
  4042. if (compareResult > 0) {
  4043. // our node is the best matching so far
  4044. bestMatch = { schema: subSchema, validationResult: subValidationResult, matchingSchemas: subMatchingSchemas };
  4045. }
  4046. else if (compareResult === 0) {
  4047. // there's already a best matching but we are as good
  4048. bestMatch.matchingSchemas.merge(subMatchingSchemas);
  4049. bestMatch.validationResult.mergeEnumValues(subValidationResult);
  4050. }
  4051. }
  4052. }
  4053. }
  4054. if (matches.length > 1 && maxOneMatch) {
  4055. validationResult.problems.push({
  4056. location: { offset: node.offset, length: 1 },
  4057. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4058. message: localize('oneOfWarning', "Matches multiple schemas when only one must validate.")
  4059. });
  4060. }
  4061. if (bestMatch !== null) {
  4062. validationResult.merge(bestMatch.validationResult);
  4063. validationResult.propertiesMatches += bestMatch.validationResult.propertiesMatches;
  4064. validationResult.propertiesValueMatches += bestMatch.validationResult.propertiesValueMatches;
  4065. matchingSchemas.merge(bestMatch.matchingSchemas);
  4066. }
  4067. return matches.length;
  4068. };
  4069. if (Array.isArray(schema.anyOf)) {
  4070. testAlternatives(schema.anyOf, false);
  4071. }
  4072. if (Array.isArray(schema.oneOf)) {
  4073. testAlternatives(schema.oneOf, true);
  4074. }
  4075. var testBranch = function (schema) {
  4076. var subValidationResult = new ValidationResult();
  4077. var subMatchingSchemas = matchingSchemas.newSub();
  4078. validate(node, asSchema(schema), subValidationResult, subMatchingSchemas);
  4079. validationResult.merge(subValidationResult);
  4080. validationResult.propertiesMatches += subValidationResult.propertiesMatches;
  4081. validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches;
  4082. matchingSchemas.merge(subMatchingSchemas);
  4083. };
  4084. var testCondition = function (ifSchema, thenSchema, elseSchema) {
  4085. var subSchema = asSchema(ifSchema);
  4086. var subValidationResult = new ValidationResult();
  4087. var subMatchingSchemas = matchingSchemas.newSub();
  4088. validate(node, subSchema, subValidationResult, subMatchingSchemas);
  4089. matchingSchemas.merge(subMatchingSchemas);
  4090. if (!subValidationResult.hasProblems()) {
  4091. if (thenSchema) {
  4092. testBranch(thenSchema);
  4093. }
  4094. }
  4095. else if (elseSchema) {
  4096. testBranch(elseSchema);
  4097. }
  4098. };
  4099. var ifSchema = asSchema(schema.if);
  4100. if (ifSchema) {
  4101. testCondition(ifSchema, asSchema(schema.then), asSchema(schema.else));
  4102. }
  4103. if (Array.isArray(schema.enum)) {
  4104. var val = getNodeValue(node);
  4105. var enumValueMatch = false;
  4106. for (var _d = 0, _e = schema.enum; _d < _e.length; _d++) {
  4107. var e = _e[_d];
  4108. if (objects_1.equals(val, e)) {
  4109. enumValueMatch = true;
  4110. break;
  4111. }
  4112. }
  4113. validationResult.enumValues = schema.enum;
  4114. validationResult.enumValueMatch = enumValueMatch;
  4115. if (!enumValueMatch) {
  4116. validationResult.problems.push({
  4117. location: { offset: node.offset, length: node.length },
  4118. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4119. code: jsonLanguageTypes_1.ErrorCode.EnumValueMismatch,
  4120. message: schema.errorMessage || localize('enumWarning', 'Value is not accepted. Valid values: {0}.', schema.enum.map(function (v) { return JSON.stringify(v); }).join(', '))
  4121. });
  4122. }
  4123. }
  4124. if (objects_1.isDefined(schema.const)) {
  4125. var val = getNodeValue(node);
  4126. if (!objects_1.equals(val, schema.const)) {
  4127. validationResult.problems.push({
  4128. location: { offset: node.offset, length: node.length },
  4129. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4130. code: jsonLanguageTypes_1.ErrorCode.EnumValueMismatch,
  4131. message: schema.errorMessage || localize('constWarning', 'Value must be {0}.', JSON.stringify(schema.const))
  4132. });
  4133. validationResult.enumValueMatch = false;
  4134. }
  4135. else {
  4136. validationResult.enumValueMatch = true;
  4137. }
  4138. validationResult.enumValues = [schema.const];
  4139. }
  4140. if (schema.deprecationMessage && node.parent) {
  4141. validationResult.problems.push({
  4142. location: { offset: node.parent.offset, length: node.parent.length },
  4143. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4144. message: schema.deprecationMessage
  4145. });
  4146. }
  4147. }
  4148. function _validateNumberNode(node, schema, validationResult, matchingSchemas) {
  4149. var val = node.value;
  4150. if (objects_1.isNumber(schema.multipleOf)) {
  4151. if (val % schema.multipleOf !== 0) {
  4152. validationResult.problems.push({
  4153. location: { offset: node.offset, length: node.length },
  4154. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4155. message: localize('multipleOfWarning', 'Value is not divisible by {0}.', schema.multipleOf)
  4156. });
  4157. }
  4158. }
  4159. function getExclusiveLimit(limit, exclusive) {
  4160. if (objects_1.isNumber(exclusive)) {
  4161. return exclusive;
  4162. }
  4163. if (objects_1.isBoolean(exclusive) && exclusive) {
  4164. return limit;
  4165. }
  4166. return void 0;
  4167. }
  4168. function getLimit(limit, exclusive) {
  4169. if (!objects_1.isBoolean(exclusive) || !exclusive) {
  4170. return limit;
  4171. }
  4172. return void 0;
  4173. }
  4174. var exclusiveMinimum = getExclusiveLimit(schema.minimum, schema.exclusiveMinimum);
  4175. if (objects_1.isNumber(exclusiveMinimum) && val <= exclusiveMinimum) {
  4176. validationResult.problems.push({
  4177. location: { offset: node.offset, length: node.length },
  4178. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4179. message: localize('exclusiveMinimumWarning', 'Value is below the exclusive minimum of {0}.', exclusiveMinimum)
  4180. });
  4181. }
  4182. var exclusiveMaximum = getExclusiveLimit(schema.maximum, schema.exclusiveMaximum);
  4183. if (objects_1.isNumber(exclusiveMaximum) && val >= exclusiveMaximum) {
  4184. validationResult.problems.push({
  4185. location: { offset: node.offset, length: node.length },
  4186. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4187. message: localize('exclusiveMaximumWarning', 'Value is above the exclusive maximum of {0}.', exclusiveMaximum)
  4188. });
  4189. }
  4190. var minimum = getLimit(schema.minimum, schema.exclusiveMinimum);
  4191. if (objects_1.isNumber(minimum) && val < minimum) {
  4192. validationResult.problems.push({
  4193. location: { offset: node.offset, length: node.length },
  4194. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4195. message: localize('minimumWarning', 'Value is below the minimum of {0}.', minimum)
  4196. });
  4197. }
  4198. var maximum = getLimit(schema.maximum, schema.exclusiveMaximum);
  4199. if (objects_1.isNumber(maximum) && val > maximum) {
  4200. validationResult.problems.push({
  4201. location: { offset: node.offset, length: node.length },
  4202. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4203. message: localize('maximumWarning', 'Value is above the maximum of {0}.', maximum)
  4204. });
  4205. }
  4206. }
  4207. function _validateStringNode(node, schema, validationResult, matchingSchemas) {
  4208. if (objects_1.isNumber(schema.minLength) && node.value.length < schema.minLength) {
  4209. validationResult.problems.push({
  4210. location: { offset: node.offset, length: node.length },
  4211. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4212. message: localize('minLengthWarning', 'String is shorter than the minimum length of {0}.', schema.minLength)
  4213. });
  4214. }
  4215. if (objects_1.isNumber(schema.maxLength) && node.value.length > schema.maxLength) {
  4216. validationResult.problems.push({
  4217. location: { offset: node.offset, length: node.length },
  4218. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4219. message: localize('maxLengthWarning', 'String is longer than the maximum length of {0}.', schema.maxLength)
  4220. });
  4221. }
  4222. if (objects_1.isString(schema.pattern)) {
  4223. var regex = new RegExp(schema.pattern);
  4224. if (!regex.test(node.value)) {
  4225. validationResult.problems.push({
  4226. location: { offset: node.offset, length: node.length },
  4227. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4228. message: schema.patternErrorMessage || schema.errorMessage || localize('patternWarning', 'String does not match the pattern of "{0}".', schema.pattern)
  4229. });
  4230. }
  4231. }
  4232. if (schema.format) {
  4233. switch (schema.format) {
  4234. case 'uri':
  4235. case 'uri-reference':
  4236. {
  4237. var errorMessage = void 0;
  4238. if (!node.value) {
  4239. errorMessage = localize('uriEmpty', 'URI expected.');
  4240. }
  4241. else {
  4242. var match = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/.exec(node.value);
  4243. if (!match) {
  4244. errorMessage = localize('uriMissing', 'URI is expected.');
  4245. }
  4246. else if (!match[2] && schema.format === 'uri') {
  4247. errorMessage = localize('uriSchemeMissing', 'URI with a scheme is expected.');
  4248. }
  4249. }
  4250. if (errorMessage) {
  4251. validationResult.problems.push({
  4252. location: { offset: node.offset, length: node.length },
  4253. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4254. message: schema.patternErrorMessage || schema.errorMessage || localize('uriFormatWarning', 'String is not a URI: {0}', errorMessage)
  4255. });
  4256. }
  4257. }
  4258. break;
  4259. case 'color-hex':
  4260. case 'date-time':
  4261. case 'date':
  4262. case 'time':
  4263. case 'email':
  4264. var format = formats[schema.format];
  4265. if (!node.value || !format.pattern.exec(node.value)) {
  4266. validationResult.problems.push({
  4267. location: { offset: node.offset, length: node.length },
  4268. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4269. message: schema.patternErrorMessage || schema.errorMessage || format.errorMessage
  4270. });
  4271. }
  4272. default:
  4273. }
  4274. }
  4275. }
  4276. function _validateArrayNode(node, schema, validationResult, matchingSchemas) {
  4277. if (Array.isArray(schema.items)) {
  4278. var subSchemas = schema.items;
  4279. for (var index = 0; index < subSchemas.length; index++) {
  4280. var subSchemaRef = subSchemas[index];
  4281. var subSchema = asSchema(subSchemaRef);
  4282. var itemValidationResult = new ValidationResult();
  4283. var item = node.items[index];
  4284. if (item) {
  4285. validate(item, subSchema, itemValidationResult, matchingSchemas);
  4286. validationResult.mergePropertyMatch(itemValidationResult);
  4287. }
  4288. else if (node.items.length >= subSchemas.length) {
  4289. validationResult.propertiesValueMatches++;
  4290. }
  4291. }
  4292. if (node.items.length > subSchemas.length) {
  4293. if (typeof schema.additionalItems === 'object') {
  4294. for (var i = subSchemas.length; i < node.items.length; i++) {
  4295. var itemValidationResult = new ValidationResult();
  4296. validate(node.items[i], schema.additionalItems, itemValidationResult, matchingSchemas);
  4297. validationResult.mergePropertyMatch(itemValidationResult);
  4298. }
  4299. }
  4300. else if (schema.additionalItems === false) {
  4301. validationResult.problems.push({
  4302. location: { offset: node.offset, length: node.length },
  4303. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4304. message: localize('additionalItemsWarning', 'Array has too many items according to schema. Expected {0} or fewer.', subSchemas.length)
  4305. });
  4306. }
  4307. }
  4308. }
  4309. else {
  4310. var itemSchema = asSchema(schema.items);
  4311. if (itemSchema) {
  4312. for (var _i = 0, _a = node.items; _i < _a.length; _i++) {
  4313. var item = _a[_i];
  4314. var itemValidationResult = new ValidationResult();
  4315. validate(item, itemSchema, itemValidationResult, matchingSchemas);
  4316. validationResult.mergePropertyMatch(itemValidationResult);
  4317. }
  4318. }
  4319. }
  4320. var containsSchema = asSchema(schema.contains);
  4321. if (containsSchema) {
  4322. var doesContain = node.items.some(function (item) {
  4323. var itemValidationResult = new ValidationResult();
  4324. validate(item, containsSchema, itemValidationResult, NoOpSchemaCollector.instance);
  4325. return !itemValidationResult.hasProblems();
  4326. });
  4327. if (!doesContain) {
  4328. validationResult.problems.push({
  4329. location: { offset: node.offset, length: node.length },
  4330. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4331. message: schema.errorMessage || localize('requiredItemMissingWarning', 'Array does not contain required item.')
  4332. });
  4333. }
  4334. }
  4335. if (objects_1.isNumber(schema.minItems) && node.items.length < schema.minItems) {
  4336. validationResult.problems.push({
  4337. location: { offset: node.offset, length: node.length },
  4338. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4339. message: localize('minItemsWarning', 'Array has too few items. Expected {0} or more.', schema.minItems)
  4340. });
  4341. }
  4342. if (objects_1.isNumber(schema.maxItems) && node.items.length > schema.maxItems) {
  4343. validationResult.problems.push({
  4344. location: { offset: node.offset, length: node.length },
  4345. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4346. message: localize('maxItemsWarning', 'Array has too many items. Expected {0} or fewer.', schema.maxItems)
  4347. });
  4348. }
  4349. if (schema.uniqueItems === true) {
  4350. var values_1 = getNodeValue(node);
  4351. var duplicates = values_1.some(function (value, index) {
  4352. return index !== values_1.lastIndexOf(value);
  4353. });
  4354. if (duplicates) {
  4355. validationResult.problems.push({
  4356. location: { offset: node.offset, length: node.length },
  4357. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4358. message: localize('uniqueItemsWarning', 'Array has duplicate items.')
  4359. });
  4360. }
  4361. }
  4362. }
  4363. function _validateObjectNode(node, schema, validationResult, matchingSchemas) {
  4364. var seenKeys = Object.create(null);
  4365. var unprocessedProperties = [];
  4366. for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
  4367. var propertyNode = _a[_i];
  4368. var key = propertyNode.keyNode.value;
  4369. seenKeys[key] = propertyNode.valueNode;
  4370. unprocessedProperties.push(key);
  4371. }
  4372. if (Array.isArray(schema.required)) {
  4373. for (var _b = 0, _c = schema.required; _b < _c.length; _b++) {
  4374. var propertyName = _c[_b];
  4375. if (!seenKeys[propertyName]) {
  4376. var keyNode = node.parent && node.parent.type === 'property' && node.parent.keyNode;
  4377. var location = keyNode ? { offset: keyNode.offset, length: keyNode.length } : { offset: node.offset, length: 1 };
  4378. validationResult.problems.push({
  4379. location: location,
  4380. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4381. message: localize('MissingRequiredPropWarning', 'Missing property "{0}".', propertyName)
  4382. });
  4383. }
  4384. }
  4385. }
  4386. var propertyProcessed = function (prop) {
  4387. var index = unprocessedProperties.indexOf(prop);
  4388. while (index >= 0) {
  4389. unprocessedProperties.splice(index, 1);
  4390. index = unprocessedProperties.indexOf(prop);
  4391. }
  4392. };
  4393. if (schema.properties) {
  4394. for (var _d = 0, _e = Object.keys(schema.properties); _d < _e.length; _d++) {
  4395. var propertyName = _e[_d];
  4396. propertyProcessed(propertyName);
  4397. var propertySchema = schema.properties[propertyName];
  4398. var child = seenKeys[propertyName];
  4399. if (child) {
  4400. if (objects_1.isBoolean(propertySchema)) {
  4401. if (!propertySchema) {
  4402. var propertyNode = child.parent;
  4403. validationResult.problems.push({
  4404. location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
  4405. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4406. message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
  4407. });
  4408. }
  4409. else {
  4410. validationResult.propertiesMatches++;
  4411. validationResult.propertiesValueMatches++;
  4412. }
  4413. }
  4414. else {
  4415. var propertyValidationResult = new ValidationResult();
  4416. validate(child, propertySchema, propertyValidationResult, matchingSchemas);
  4417. validationResult.mergePropertyMatch(propertyValidationResult);
  4418. }
  4419. }
  4420. }
  4421. }
  4422. if (schema.patternProperties) {
  4423. for (var _f = 0, _g = Object.keys(schema.patternProperties); _f < _g.length; _f++) {
  4424. var propertyPattern = _g[_f];
  4425. var regex = new RegExp(propertyPattern);
  4426. for (var _h = 0, _j = unprocessedProperties.slice(0); _h < _j.length; _h++) {
  4427. var propertyName = _j[_h];
  4428. if (regex.test(propertyName)) {
  4429. propertyProcessed(propertyName);
  4430. var child = seenKeys[propertyName];
  4431. if (child) {
  4432. var propertySchema = schema.patternProperties[propertyPattern];
  4433. if (objects_1.isBoolean(propertySchema)) {
  4434. if (!propertySchema) {
  4435. var propertyNode = child.parent;
  4436. validationResult.problems.push({
  4437. location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
  4438. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4439. message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
  4440. });
  4441. }
  4442. else {
  4443. validationResult.propertiesMatches++;
  4444. validationResult.propertiesValueMatches++;
  4445. }
  4446. }
  4447. else {
  4448. var propertyValidationResult = new ValidationResult();
  4449. validate(child, propertySchema, propertyValidationResult, matchingSchemas);
  4450. validationResult.mergePropertyMatch(propertyValidationResult);
  4451. }
  4452. }
  4453. }
  4454. }
  4455. }
  4456. }
  4457. if (typeof schema.additionalProperties === 'object') {
  4458. for (var _k = 0, unprocessedProperties_1 = unprocessedProperties; _k < unprocessedProperties_1.length; _k++) {
  4459. var propertyName = unprocessedProperties_1[_k];
  4460. var child = seenKeys[propertyName];
  4461. if (child) {
  4462. var propertyValidationResult = new ValidationResult();
  4463. validate(child, schema.additionalProperties, propertyValidationResult, matchingSchemas);
  4464. validationResult.mergePropertyMatch(propertyValidationResult);
  4465. }
  4466. }
  4467. }
  4468. else if (schema.additionalProperties === false) {
  4469. if (unprocessedProperties.length > 0) {
  4470. for (var _l = 0, unprocessedProperties_2 = unprocessedProperties; _l < unprocessedProperties_2.length; _l++) {
  4471. var propertyName = unprocessedProperties_2[_l];
  4472. var child = seenKeys[propertyName];
  4473. if (child) {
  4474. var propertyNode = child.parent;
  4475. validationResult.problems.push({
  4476. location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
  4477. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4478. message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
  4479. });
  4480. }
  4481. }
  4482. }
  4483. }
  4484. if (objects_1.isNumber(schema.maxProperties)) {
  4485. if (node.properties.length > schema.maxProperties) {
  4486. validationResult.problems.push({
  4487. location: { offset: node.offset, length: node.length },
  4488. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4489. message: localize('MaxPropWarning', 'Object has more properties than limit of {0}.', schema.maxProperties)
  4490. });
  4491. }
  4492. }
  4493. if (objects_1.isNumber(schema.minProperties)) {
  4494. if (node.properties.length < schema.minProperties) {
  4495. validationResult.problems.push({
  4496. location: { offset: node.offset, length: node.length },
  4497. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4498. message: localize('MinPropWarning', 'Object has fewer properties than the required number of {0}', schema.minProperties)
  4499. });
  4500. }
  4501. }
  4502. if (schema.dependencies) {
  4503. for (var _m = 0, _o = Object.keys(schema.dependencies); _m < _o.length; _m++) {
  4504. var key = _o[_m];
  4505. var prop = seenKeys[key];
  4506. if (prop) {
  4507. var propertyDep = schema.dependencies[key];
  4508. if (Array.isArray(propertyDep)) {
  4509. for (var _p = 0, propertyDep_1 = propertyDep; _p < propertyDep_1.length; _p++) {
  4510. var requiredProp = propertyDep_1[_p];
  4511. if (!seenKeys[requiredProp]) {
  4512. validationResult.problems.push({
  4513. location: { offset: node.offset, length: node.length },
  4514. severity: jsonLanguageTypes_1.DiagnosticSeverity.Warning,
  4515. message: localize('RequiredDependentPropWarning', 'Object is missing property {0} required by property {1}.', requiredProp, key)
  4516. });
  4517. }
  4518. else {
  4519. validationResult.propertiesValueMatches++;
  4520. }
  4521. }
  4522. }
  4523. else {
  4524. var propertySchema = asSchema(propertyDep);
  4525. if (propertySchema) {
  4526. var propertyValidationResult = new ValidationResult();
  4527. validate(node, propertySchema, propertyValidationResult, matchingSchemas);
  4528. validationResult.mergePropertyMatch(propertyValidationResult);
  4529. }
  4530. }
  4531. }
  4532. }
  4533. }
  4534. var propertyNames = asSchema(schema.propertyNames);
  4535. if (propertyNames) {
  4536. for (var _q = 0, _r = node.properties; _q < _r.length; _q++) {
  4537. var f = _r[_q];
  4538. var key = f.keyNode;
  4539. if (key) {
  4540. validate(key, propertyNames, validationResult, NoOpSchemaCollector.instance);
  4541. }
  4542. }
  4543. }
  4544. }
  4545. }
  4546. function parse(textDocument, config) {
  4547. var problems = [];
  4548. var lastProblemOffset = -1;
  4549. var text = textDocument.getText();
  4550. var scanner = Json.createScanner(text, false);
  4551. var commentRanges = config && config.collectComments ? [] : void 0;
  4552. function _scanNext() {
  4553. while (true) {
  4554. var token_1 = scanner.scan();
  4555. _checkScanError();
  4556. switch (token_1) {
  4557. case 12 /* LineCommentTrivia */:
  4558. case 13 /* BlockCommentTrivia */:
  4559. if (Array.isArray(commentRanges)) {
  4560. commentRanges.push(jsonLanguageTypes_1.Range.create(textDocument.positionAt(scanner.getTokenOffset()), textDocument.positionAt(scanner.getTokenOffset() + scanner.getTokenLength())));
  4561. }
  4562. break;
  4563. case 15 /* Trivia */:
  4564. case 14 /* LineBreakTrivia */:
  4565. break;
  4566. default:
  4567. return token_1;
  4568. }
  4569. }
  4570. }
  4571. function _accept(token) {
  4572. if (scanner.getToken() === token) {
  4573. _scanNext();
  4574. return true;
  4575. }
  4576. return false;
  4577. }
  4578. function _errorAtRange(message, code, startOffset, endOffset, severity) {
  4579. if (severity === void 0) { severity = jsonLanguageTypes_1.DiagnosticSeverity.Error; }
  4580. if (problems.length === 0 || startOffset !== lastProblemOffset) {
  4581. var range = jsonLanguageTypes_1.Range.create(textDocument.positionAt(startOffset), textDocument.positionAt(endOffset));
  4582. problems.push(jsonLanguageTypes_1.Diagnostic.create(range, message, severity, code, textDocument.languageId));
  4583. lastProblemOffset = startOffset;
  4584. }
  4585. }
  4586. function _error(message, code, node, skipUntilAfter, skipUntil) {
  4587. if (node === void 0) { node = null; }
  4588. if (skipUntilAfter === void 0) { skipUntilAfter = []; }
  4589. if (skipUntil === void 0) { skipUntil = []; }
  4590. var start = scanner.getTokenOffset();
  4591. var end = scanner.getTokenOffset() + scanner.getTokenLength();
  4592. if (start === end && start > 0) {
  4593. start--;
  4594. while (start > 0 && /\s/.test(text.charAt(start))) {
  4595. start--;
  4596. }
  4597. end = start + 1;
  4598. }
  4599. _errorAtRange(message, code, start, end);
  4600. if (node) {
  4601. _finalize(node, false);
  4602. }
  4603. if (skipUntilAfter.length + skipUntil.length > 0) {
  4604. var token_2 = scanner.getToken();
  4605. while (token_2 !== 17 /* EOF */) {
  4606. if (skipUntilAfter.indexOf(token_2) !== -1) {
  4607. _scanNext();
  4608. break;
  4609. }
  4610. else if (skipUntil.indexOf(token_2) !== -1) {
  4611. break;
  4612. }
  4613. token_2 = _scanNext();
  4614. }
  4615. }
  4616. return node;
  4617. }
  4618. function _checkScanError() {
  4619. switch (scanner.getTokenError()) {
  4620. case 4 /* InvalidUnicode */:
  4621. _error(localize('InvalidUnicode', 'Invalid unicode sequence in string.'), jsonLanguageTypes_1.ErrorCode.InvalidUnicode);
  4622. return true;
  4623. case 5 /* InvalidEscapeCharacter */:
  4624. _error(localize('InvalidEscapeCharacter', 'Invalid escape character in string.'), jsonLanguageTypes_1.ErrorCode.InvalidEscapeCharacter);
  4625. return true;
  4626. case 3 /* UnexpectedEndOfNumber */:
  4627. _error(localize('UnexpectedEndOfNumber', 'Unexpected end of number.'), jsonLanguageTypes_1.ErrorCode.UnexpectedEndOfNumber);
  4628. return true;
  4629. case 1 /* UnexpectedEndOfComment */:
  4630. _error(localize('UnexpectedEndOfComment', 'Unexpected end of comment.'), jsonLanguageTypes_1.ErrorCode.UnexpectedEndOfComment);
  4631. return true;
  4632. case 2 /* UnexpectedEndOfString */:
  4633. _error(localize('UnexpectedEndOfString', 'Unexpected end of string.'), jsonLanguageTypes_1.ErrorCode.UnexpectedEndOfString);
  4634. return true;
  4635. case 6 /* InvalidCharacter */:
  4636. _error(localize('InvalidCharacter', 'Invalid characters in string. Control characters must be escaped.'), jsonLanguageTypes_1.ErrorCode.InvalidCharacter);
  4637. return true;
  4638. }
  4639. return false;
  4640. }
  4641. function _finalize(node, scanNext) {
  4642. node.length = scanner.getTokenOffset() + scanner.getTokenLength() - node.offset;
  4643. if (scanNext) {
  4644. _scanNext();
  4645. }
  4646. return node;
  4647. }
  4648. function _parseArray(parent) {
  4649. if (scanner.getToken() !== 3 /* OpenBracketToken */) {
  4650. return null;
  4651. }
  4652. var node = new ArrayASTNodeImpl(parent, scanner.getTokenOffset());
  4653. _scanNext(); // consume OpenBracketToken
  4654. var count = 0;
  4655. var needsComma = false;
  4656. while (scanner.getToken() !== 4 /* CloseBracketToken */ && scanner.getToken() !== 17 /* EOF */) {
  4657. if (scanner.getToken() === 5 /* CommaToken */) {
  4658. if (!needsComma) {
  4659. _error(localize('ValueExpected', 'Value expected'), jsonLanguageTypes_1.ErrorCode.ValueExpected);
  4660. }
  4661. var commaOffset = scanner.getTokenOffset();
  4662. _scanNext(); // consume comma
  4663. if (scanner.getToken() === 4 /* CloseBracketToken */) {
  4664. if (needsComma) {
  4665. _errorAtRange(localize('TrailingComma', 'Trailing comma'), jsonLanguageTypes_1.ErrorCode.TrailingComma, commaOffset, commaOffset + 1);
  4666. }
  4667. continue;
  4668. }
  4669. }
  4670. else if (needsComma) {
  4671. _error(localize('ExpectedComma', 'Expected comma'), jsonLanguageTypes_1.ErrorCode.CommaExpected);
  4672. }
  4673. var item = _parseValue(node, count++);
  4674. if (!item) {
  4675. _error(localize('PropertyExpected', 'Value expected'), jsonLanguageTypes_1.ErrorCode.ValueExpected, null, [], [4 /* CloseBracketToken */, 5 /* CommaToken */]);
  4676. }
  4677. else {
  4678. node.items.push(item);
  4679. }
  4680. needsComma = true;
  4681. }
  4682. if (scanner.getToken() !== 4 /* CloseBracketToken */) {
  4683. return _error(localize('ExpectedCloseBracket', 'Expected comma or closing bracket'), jsonLanguageTypes_1.ErrorCode.CommaOrCloseBacketExpected, node);
  4684. }
  4685. return _finalize(node, true);
  4686. }
  4687. function _parseProperty(parent, keysSeen) {
  4688. var node = new PropertyASTNodeImpl(parent, scanner.getTokenOffset());
  4689. var key = _parseString(node);
  4690. if (!key) {
  4691. if (scanner.getToken() === 16 /* Unknown */) {
  4692. // give a more helpful error message
  4693. _error(localize('DoubleQuotesExpected', 'Property keys must be doublequoted'), jsonLanguageTypes_1.ErrorCode.Undefined);
  4694. var keyNode = new StringASTNodeImpl(node, scanner.getTokenOffset(), scanner.getTokenLength());
  4695. keyNode.value = scanner.getTokenValue();
  4696. key = keyNode;
  4697. _scanNext(); // consume Unknown
  4698. }
  4699. else {
  4700. return null;
  4701. }
  4702. }
  4703. node.keyNode = key;
  4704. var seen = keysSeen[key.value];
  4705. if (seen) {
  4706. _errorAtRange(localize('DuplicateKeyWarning', "Duplicate object key"), jsonLanguageTypes_1.ErrorCode.DuplicateKey, node.keyNode.offset, node.keyNode.offset + node.keyNode.length, jsonLanguageTypes_1.DiagnosticSeverity.Warning);
  4707. if (typeof seen === 'object') {
  4708. _errorAtRange(localize('DuplicateKeyWarning', "Duplicate object key"), jsonLanguageTypes_1.ErrorCode.DuplicateKey, seen.keyNode.offset, seen.keyNode.offset + seen.keyNode.length, jsonLanguageTypes_1.DiagnosticSeverity.Warning);
  4709. }
  4710. keysSeen[key.value] = true; // if the same key is duplicate again, avoid duplicate error reporting
  4711. }
  4712. else {
  4713. keysSeen[key.value] = node;
  4714. }
  4715. if (scanner.getToken() === 6 /* ColonToken */) {
  4716. node.colonOffset = scanner.getTokenOffset();
  4717. _scanNext(); // consume ColonToken
  4718. }
  4719. else {
  4720. _error(localize('ColonExpected', 'Colon expected'), jsonLanguageTypes_1.ErrorCode.ColonExpected);
  4721. if (scanner.getToken() === 10 /* StringLiteral */ && textDocument.positionAt(key.offset + key.length).line < textDocument.positionAt(scanner.getTokenOffset()).line) {
  4722. node.length = key.length;
  4723. return node;
  4724. }
  4725. }
  4726. var value = _parseValue(node, key.value);
  4727. if (!value) {
  4728. return _error(localize('ValueExpected', 'Value expected'), jsonLanguageTypes_1.ErrorCode.ValueExpected, node, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  4729. }
  4730. node.valueNode = value;
  4731. node.length = value.offset + value.length - node.offset;
  4732. return node;
  4733. }
  4734. function _parseObject(parent) {
  4735. if (scanner.getToken() !== 1 /* OpenBraceToken */) {
  4736. return null;
  4737. }
  4738. var node = new ObjectASTNodeImpl(parent, scanner.getTokenOffset());
  4739. var keysSeen = Object.create(null);
  4740. _scanNext(); // consume OpenBraceToken
  4741. var needsComma = false;
  4742. while (scanner.getToken() !== 2 /* CloseBraceToken */ && scanner.getToken() !== 17 /* EOF */) {
  4743. if (scanner.getToken() === 5 /* CommaToken */) {
  4744. if (!needsComma) {
  4745. _error(localize('PropertyExpected', 'Property expected'), jsonLanguageTypes_1.ErrorCode.PropertyExpected);
  4746. }
  4747. var commaOffset = scanner.getTokenOffset();
  4748. _scanNext(); // consume comma
  4749. if (scanner.getToken() === 2 /* CloseBraceToken */) {
  4750. if (needsComma) {
  4751. _errorAtRange(localize('TrailingComma', 'Trailing comma'), jsonLanguageTypes_1.ErrorCode.TrailingComma, commaOffset, commaOffset + 1);
  4752. }
  4753. continue;
  4754. }
  4755. }
  4756. else if (needsComma) {
  4757. _error(localize('ExpectedComma', 'Expected comma'), jsonLanguageTypes_1.ErrorCode.CommaExpected);
  4758. }
  4759. var property = _parseProperty(node, keysSeen);
  4760. if (!property) {
  4761. _error(localize('PropertyExpected', 'Property expected'), jsonLanguageTypes_1.ErrorCode.PropertyExpected, null, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  4762. }
  4763. else {
  4764. node.properties.push(property);
  4765. }
  4766. needsComma = true;
  4767. }
  4768. if (scanner.getToken() !== 2 /* CloseBraceToken */) {
  4769. return _error(localize('ExpectedCloseBrace', 'Expected comma or closing brace'), jsonLanguageTypes_1.ErrorCode.CommaOrCloseBraceExpected, node);
  4770. }
  4771. return _finalize(node, true);
  4772. }
  4773. function _parseString(parent) {
  4774. if (scanner.getToken() !== 10 /* StringLiteral */) {
  4775. return null;
  4776. }
  4777. var node = new StringASTNodeImpl(parent, scanner.getTokenOffset());
  4778. node.value = scanner.getTokenValue();
  4779. return _finalize(node, true);
  4780. }
  4781. function _parseNumber(parent) {
  4782. if (scanner.getToken() !== 11 /* NumericLiteral */) {
  4783. return null;
  4784. }
  4785. var node = new NumberASTNodeImpl(parent, scanner.getTokenOffset());
  4786. if (scanner.getTokenError() === 0 /* None */) {
  4787. var tokenValue = scanner.getTokenValue();
  4788. try {
  4789. var numberValue = JSON.parse(tokenValue);
  4790. if (!objects_1.isNumber(numberValue)) {
  4791. return _error(localize('InvalidNumberFormat', 'Invalid number format.'), jsonLanguageTypes_1.ErrorCode.Undefined, node);
  4792. }
  4793. node.value = numberValue;
  4794. }
  4795. catch (e) {
  4796. return _error(localize('InvalidNumberFormat', 'Invalid number format.'), jsonLanguageTypes_1.ErrorCode.Undefined, node);
  4797. }
  4798. node.isInteger = tokenValue.indexOf('.') === -1;
  4799. }
  4800. return _finalize(node, true);
  4801. }
  4802. function _parseLiteral(parent) {
  4803. var node;
  4804. switch (scanner.getToken()) {
  4805. case 7 /* NullKeyword */:
  4806. return _finalize(new NullASTNodeImpl(parent, scanner.getTokenOffset()), true);
  4807. case 8 /* TrueKeyword */:
  4808. return _finalize(new BooleanASTNodeImpl(parent, true, scanner.getTokenOffset()), true);
  4809. case 9 /* FalseKeyword */:
  4810. return _finalize(new BooleanASTNodeImpl(parent, false, scanner.getTokenOffset()), true);
  4811. default:
  4812. return null;
  4813. }
  4814. }
  4815. function _parseValue(parent, name) {
  4816. return _parseArray(parent) || _parseObject(parent) || _parseString(parent) || _parseNumber(parent) || _parseLiteral(parent);
  4817. }
  4818. var _root = null;
  4819. var token = _scanNext();
  4820. if (token !== 17 /* EOF */) {
  4821. _root = _parseValue(null, null);
  4822. if (!_root) {
  4823. _error(localize('Invalid symbol', 'Expected a JSON object, array or literal.'), jsonLanguageTypes_1.ErrorCode.Undefined);
  4824. }
  4825. else if (scanner.getToken() !== 17 /* EOF */) {
  4826. _error(localize('End of file expected', 'End of file expected.'), jsonLanguageTypes_1.ErrorCode.Undefined);
  4827. }
  4828. }
  4829. return new JSONDocument(_root, problems, commentRanges);
  4830. }
  4831. exports.parse = parse;
  4832. });
  4833. /*---------------------------------------------------------------------------------------------
  4834. * Copyright (c) Microsoft Corporation. All rights reserved.
  4835. * Licensed under the MIT License. See License.txt in the project root for license information.
  4836. *--------------------------------------------------------------------------------------------*/
  4837. (function (factory) {
  4838. if (typeof module === "object" && typeof module.exports === "object") {
  4839. var v = factory(require, exports);
  4840. if (v !== undefined) module.exports = v;
  4841. }
  4842. else if (typeof define === "function" && define.amd) {
  4843. define('vscode-json-languageservice/utils/json',["require", "exports"], factory);
  4844. }
  4845. })(function (require, exports) {
  4846. "use strict";
  4847. Object.defineProperty(exports, "__esModule", { value: true });
  4848. function stringifyObject(obj, indent, stringifyLiteral) {
  4849. if (obj !== null && typeof obj === 'object') {
  4850. var newIndent = indent + '\t';
  4851. if (Array.isArray(obj)) {
  4852. if (obj.length === 0) {
  4853. return '[]';
  4854. }
  4855. var result = '[\n';
  4856. for (var i = 0; i < obj.length; i++) {
  4857. result += newIndent + stringifyObject(obj[i], newIndent, stringifyLiteral);
  4858. if (i < obj.length - 1) {
  4859. result += ',';
  4860. }
  4861. result += '\n';
  4862. }
  4863. result += indent + ']';
  4864. return result;
  4865. }
  4866. else {
  4867. var keys = Object.keys(obj);
  4868. if (keys.length === 0) {
  4869. return '{}';
  4870. }
  4871. var result = '{\n';
  4872. for (var i = 0; i < keys.length; i++) {
  4873. var key = keys[i];
  4874. result += newIndent + JSON.stringify(key) + ': ' + stringifyObject(obj[key], newIndent, stringifyLiteral);
  4875. if (i < keys.length - 1) {
  4876. result += ',';
  4877. }
  4878. result += '\n';
  4879. }
  4880. result += indent + '}';
  4881. return result;
  4882. }
  4883. }
  4884. return stringifyLiteral(obj);
  4885. }
  4886. exports.stringifyObject = stringifyObject;
  4887. });
  4888. /*---------------------------------------------------------------------------------------------
  4889. * Copyright (c) Microsoft Corporation. All rights reserved.
  4890. * Licensed under the MIT License. See License.txt in the project root for license information.
  4891. *--------------------------------------------------------------------------------------------*/
  4892. (function (factory) {
  4893. if (typeof module === "object" && typeof module.exports === "object") {
  4894. var v = factory(require, exports);
  4895. if (v !== undefined) module.exports = v;
  4896. }
  4897. else if (typeof define === "function" && define.amd) {
  4898. define('vscode-json-languageservice/utils/strings',["require", "exports"], factory);
  4899. }
  4900. })(function (require, exports) {
  4901. "use strict";
  4902. Object.defineProperty(exports, "__esModule", { value: true });
  4903. function startsWith(haystack, needle) {
  4904. if (haystack.length < needle.length) {
  4905. return false;
  4906. }
  4907. for (var i = 0; i < needle.length; i++) {
  4908. if (haystack[i] !== needle[i]) {
  4909. return false;
  4910. }
  4911. }
  4912. return true;
  4913. }
  4914. exports.startsWith = startsWith;
  4915. /**
  4916. * Determines if haystack ends with needle.
  4917. */
  4918. function endsWith(haystack, needle) {
  4919. var diff = haystack.length - needle.length;
  4920. if (diff > 0) {
  4921. return haystack.lastIndexOf(needle) === diff;
  4922. }
  4923. else if (diff === 0) {
  4924. return haystack === needle;
  4925. }
  4926. else {
  4927. return false;
  4928. }
  4929. }
  4930. exports.endsWith = endsWith;
  4931. function convertSimple2RegExpPattern(pattern) {
  4932. return pattern.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&').replace(/[\*]/g, '.*');
  4933. }
  4934. exports.convertSimple2RegExpPattern = convertSimple2RegExpPattern;
  4935. function repeat(value, count) {
  4936. var s = '';
  4937. while (count > 0) {
  4938. if ((count & 1) === 1) {
  4939. s += value;
  4940. }
  4941. value += value;
  4942. count = count >>> 1;
  4943. }
  4944. return s;
  4945. }
  4946. exports.repeat = repeat;
  4947. });
  4948. /*---------------------------------------------------------------------------------------------
  4949. * Copyright (c) Microsoft Corporation. All rights reserved.
  4950. * Licensed under the MIT License. See License.txt in the project root for license information.
  4951. *--------------------------------------------------------------------------------------------*/
  4952. (function (factory) {
  4953. if (typeof module === "object" && typeof module.exports === "object") {
  4954. var v = factory(require, exports);
  4955. if (v !== undefined) module.exports = v;
  4956. }
  4957. else if (typeof define === "function" && define.amd) {
  4958. define('vscode-json-languageservice/services/jsonCompletion',["require", "exports", "../parser/jsonParser", "jsonc-parser", "../utils/json", "../utils/strings", "../utils/objects", "../jsonLanguageTypes", "vscode-nls"], factory);
  4959. }
  4960. })(function (require, exports) {
  4961. "use strict";
  4962. Object.defineProperty(exports, "__esModule", { value: true });
  4963. var Parser = require("../parser/jsonParser");
  4964. var Json = require("jsonc-parser");
  4965. var json_1 = require("../utils/json");
  4966. var strings_1 = require("../utils/strings");
  4967. var objects_1 = require("../utils/objects");
  4968. var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
  4969. var nls = require("vscode-nls");
  4970. var localize = nls.loadMessageBundle();
  4971. var valueCommitCharacters = [',', '}', ']'];
  4972. var propertyCommitCharacters = [':'];
  4973. var JSONCompletion = /** @class */ (function () {
  4974. function JSONCompletion(schemaService, contributions, promiseConstructor, clientCapabilities) {
  4975. if (contributions === void 0) { contributions = []; }
  4976. if (promiseConstructor === void 0) { promiseConstructor = Promise; }
  4977. if (clientCapabilities === void 0) { clientCapabilities = {}; }
  4978. this.schemaService = schemaService;
  4979. this.contributions = contributions;
  4980. this.promiseConstructor = promiseConstructor;
  4981. this.clientCapabilities = clientCapabilities;
  4982. this.templateVarIdCounter = 0;
  4983. }
  4984. JSONCompletion.prototype.doResolve = function (item) {
  4985. for (var i = this.contributions.length - 1; i >= 0; i--) {
  4986. if (this.contributions[i].resolveCompletion) {
  4987. var resolver = this.contributions[i].resolveCompletion(item);
  4988. if (resolver) {
  4989. return resolver;
  4990. }
  4991. }
  4992. }
  4993. return this.promiseConstructor.resolve(item);
  4994. };
  4995. JSONCompletion.prototype.doComplete = function (document, position, doc) {
  4996. var _this = this;
  4997. var result = {
  4998. items: [],
  4999. isIncomplete: false
  5000. };
  5001. var text = document.getText();
  5002. var offset = document.offsetAt(position);
  5003. var node = doc.getNodeFromOffset(offset, true);
  5004. if (this.isInComment(document, node ? node.offset : 0, offset)) {
  5005. return Promise.resolve(result);
  5006. }
  5007. if (node && (offset === node.offset + node.length) && offset > 0) {
  5008. var ch = text[offset - 1];
  5009. if (node.type === 'object' && ch === '}' || node.type === 'array' && ch === ']') {
  5010. // after ] or }
  5011. node = node.parent;
  5012. }
  5013. }
  5014. var currentWord = this.getCurrentWord(document, offset);
  5015. var overwriteRange = null;
  5016. if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
  5017. overwriteRange = jsonLanguageTypes_1.Range.create(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
  5018. }
  5019. else {
  5020. var overwriteStart = offset - currentWord.length;
  5021. if (overwriteStart > 0 && text[overwriteStart - 1] === '"') {
  5022. overwriteStart--;
  5023. }
  5024. overwriteRange = jsonLanguageTypes_1.Range.create(document.positionAt(overwriteStart), position);
  5025. }
  5026. var supportsCommitCharacters = false; //this.doesSupportsCommitCharacters(); disabled for now, waiting for new API: https://github.com/microsoft/vscode/issues/42544
  5027. var proposed = {};
  5028. var collector = {
  5029. add: function (suggestion) {
  5030. var label = suggestion.label;
  5031. var existing = proposed[label];
  5032. if (!existing) {
  5033. label = label.replace(/[\n]/g, '↵');
  5034. if (label.length > 60) {
  5035. var shortendedLabel = label.substr(0, 57).trim() + '...';
  5036. if (!proposed[shortendedLabel]) {
  5037. label = shortendedLabel;
  5038. }
  5039. }
  5040. if (overwriteRange) {
  5041. suggestion.textEdit = jsonLanguageTypes_1.TextEdit.replace(overwriteRange, suggestion.insertText);
  5042. }
  5043. if (supportsCommitCharacters) {
  5044. suggestion.commitCharacters = suggestion.kind === jsonLanguageTypes_1.CompletionItemKind.Property ? propertyCommitCharacters : valueCommitCharacters;
  5045. }
  5046. suggestion.label = label;
  5047. proposed[label] = suggestion;
  5048. result.items.push(suggestion);
  5049. }
  5050. else if (!existing.documentation) {
  5051. existing.documentation = suggestion.documentation;
  5052. }
  5053. },
  5054. setAsIncomplete: function () {
  5055. result.isIncomplete = true;
  5056. },
  5057. error: function (message) {
  5058. console.error(message);
  5059. },
  5060. log: function (message) {
  5061. console.log(message);
  5062. },
  5063. getNumberOfProposals: function () {
  5064. return result.items.length;
  5065. }
  5066. };
  5067. return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
  5068. var collectionPromises = [];
  5069. var addValue = true;
  5070. var currentKey = '';
  5071. var currentProperty = null;
  5072. if (node) {
  5073. if (node.type === 'string') {
  5074. var parent = node.parent;
  5075. if (parent && parent.type === 'property' && parent.keyNode === node) {
  5076. addValue = !parent.valueNode;
  5077. currentProperty = parent;
  5078. currentKey = text.substr(node.offset + 1, node.length - 2);
  5079. if (parent) {
  5080. node = parent.parent;
  5081. }
  5082. }
  5083. }
  5084. }
  5085. // proposals for properties
  5086. if (node && node.type === 'object') {
  5087. // don't suggest keys when the cursor is just before the opening curly brace
  5088. if (node.offset === offset) {
  5089. return result;
  5090. }
  5091. // don't suggest properties that are already present
  5092. var properties = node.properties;
  5093. properties.forEach(function (p) {
  5094. if (!currentProperty || currentProperty !== p) {
  5095. proposed[p.keyNode.value] = jsonLanguageTypes_1.CompletionItem.create('__');
  5096. }
  5097. });
  5098. var separatorAfter_1 = '';
  5099. if (addValue) {
  5100. separatorAfter_1 = _this.evaluateSeparatorAfter(document, document.offsetAt(overwriteRange.end));
  5101. }
  5102. if (schema) {
  5103. // property proposals with schema
  5104. _this.getPropertyCompletions(schema, doc, node, addValue, separatorAfter_1, collector);
  5105. }
  5106. else {
  5107. // property proposals without schema
  5108. _this.getSchemaLessPropertyCompletions(doc, node, currentKey, collector);
  5109. }
  5110. var location_1 = Parser.getNodePath(node);
  5111. _this.contributions.forEach(function (contribution) {
  5112. var collectPromise = contribution.collectPropertyCompletions(document.uri, location_1, currentWord, addValue, separatorAfter_1 === '', collector);
  5113. if (collectPromise) {
  5114. collectionPromises.push(collectPromise);
  5115. }
  5116. });
  5117. if ((!schema && currentWord.length > 0 && text.charAt(offset - currentWord.length - 1) !== '"')) {
  5118. collector.add({
  5119. kind: jsonLanguageTypes_1.CompletionItemKind.Property,
  5120. label: _this.getLabelForValue(currentWord),
  5121. insertText: _this.getInsertTextForProperty(currentWord, null, false, separatorAfter_1),
  5122. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet, documentation: '',
  5123. });
  5124. collector.setAsIncomplete();
  5125. }
  5126. }
  5127. // proposals for values
  5128. var types = {};
  5129. if (schema) {
  5130. // value proposals with schema
  5131. _this.getValueCompletions(schema, doc, node, offset, document, collector, types);
  5132. }
  5133. else {
  5134. // value proposals without schema
  5135. _this.getSchemaLessValueCompletions(doc, node, offset, document, collector);
  5136. }
  5137. if (_this.contributions.length > 0) {
  5138. _this.getContributedValueCompletions(doc, node, offset, document, collector, collectionPromises);
  5139. }
  5140. return _this.promiseConstructor.all(collectionPromises).then(function () {
  5141. if (collector.getNumberOfProposals() === 0) {
  5142. var offsetForSeparator = offset;
  5143. if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
  5144. offsetForSeparator = node.offset + node.length;
  5145. }
  5146. var separatorAfter = _this.evaluateSeparatorAfter(document, offsetForSeparator);
  5147. _this.addFillerValueCompletions(types, separatorAfter, collector);
  5148. }
  5149. return result;
  5150. });
  5151. });
  5152. };
  5153. JSONCompletion.prototype.getPropertyCompletions = function (schema, doc, node, addValue, separatorAfter, collector) {
  5154. var _this = this;
  5155. var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset);
  5156. matchingSchemas.forEach(function (s) {
  5157. if (s.node === node && !s.inverted) {
  5158. var schemaProperties_1 = s.schema.properties;
  5159. if (schemaProperties_1) {
  5160. Object.keys(schemaProperties_1).forEach(function (key) {
  5161. var propertySchema = schemaProperties_1[key];
  5162. if (typeof propertySchema === 'object' && !propertySchema.deprecationMessage && !propertySchema.doNotSuggest) {
  5163. var proposal = {
  5164. kind: jsonLanguageTypes_1.CompletionItemKind.Property,
  5165. label: key,
  5166. insertText: _this.getInsertTextForProperty(key, propertySchema, addValue, separatorAfter),
  5167. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5168. filterText: _this.getFilterTextForValue(key),
  5169. documentation: _this.fromMarkup(propertySchema.markdownDescription) || propertySchema.description || '',
  5170. };
  5171. if (strings_1.endsWith(proposal.insertText, "$1" + separatorAfter)) {
  5172. proposal.command = {
  5173. title: 'Suggest',
  5174. command: 'editor.action.triggerSuggest'
  5175. };
  5176. }
  5177. collector.add(proposal);
  5178. }
  5179. });
  5180. }
  5181. }
  5182. });
  5183. };
  5184. JSONCompletion.prototype.getSchemaLessPropertyCompletions = function (doc, node, currentKey, collector) {
  5185. var _this = this;
  5186. var collectCompletionsForSimilarObject = function (obj) {
  5187. obj.properties.forEach(function (p) {
  5188. var key = p.keyNode.value;
  5189. collector.add({
  5190. kind: jsonLanguageTypes_1.CompletionItemKind.Property,
  5191. label: key,
  5192. insertText: _this.getInsertTextForValue(key, ''),
  5193. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5194. filterText: _this.getFilterTextForValue(key),
  5195. documentation: ''
  5196. });
  5197. });
  5198. };
  5199. if (node.parent) {
  5200. if (node.parent.type === 'property') {
  5201. // if the object is a property value, check the tree for other objects that hang under a property of the same name
  5202. var parentKey_1 = node.parent.keyNode.value;
  5203. doc.visit(function (n) {
  5204. if (n.type === 'property' && n !== node.parent && n.keyNode.value === parentKey_1 && n.valueNode && n.valueNode.type === 'object') {
  5205. collectCompletionsForSimilarObject(n.valueNode);
  5206. }
  5207. return true;
  5208. });
  5209. }
  5210. else if (node.parent.type === 'array') {
  5211. // if the object is in an array, use all other array elements as similar objects
  5212. node.parent.items.forEach(function (n) {
  5213. if (n.type === 'object' && n !== node) {
  5214. collectCompletionsForSimilarObject(n);
  5215. }
  5216. });
  5217. }
  5218. }
  5219. else if (node.type === 'object') {
  5220. collector.add({
  5221. kind: jsonLanguageTypes_1.CompletionItemKind.Property,
  5222. label: '$schema',
  5223. insertText: this.getInsertTextForProperty('$schema', null, true, ''),
  5224. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet, documentation: '',
  5225. filterText: this.getFilterTextForValue("$schema")
  5226. });
  5227. }
  5228. };
  5229. JSONCompletion.prototype.getSchemaLessValueCompletions = function (doc, node, offset, document, collector) {
  5230. var _this = this;
  5231. var offsetForSeparator = offset;
  5232. if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
  5233. offsetForSeparator = node.offset + node.length;
  5234. node = node.parent;
  5235. }
  5236. if (!node) {
  5237. collector.add({
  5238. kind: this.getSuggestionKind('object'),
  5239. label: 'Empty object',
  5240. insertText: this.getInsertTextForValue({}, ''),
  5241. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5242. documentation: ''
  5243. });
  5244. collector.add({
  5245. kind: this.getSuggestionKind('array'),
  5246. label: 'Empty array',
  5247. insertText: this.getInsertTextForValue([], ''),
  5248. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5249. documentation: ''
  5250. });
  5251. return;
  5252. }
  5253. var separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator);
  5254. var collectSuggestionsForValues = function (value) {
  5255. if (!Parser.contains(value.parent, offset, true)) {
  5256. collector.add({
  5257. kind: _this.getSuggestionKind(value.type),
  5258. label: _this.getLabelTextForMatchingNode(value, document),
  5259. insertText: _this.getInsertTextForMatchingNode(value, document, separatorAfter),
  5260. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet, documentation: ''
  5261. });
  5262. }
  5263. if (value.type === 'boolean') {
  5264. _this.addBooleanValueCompletion(!value.value, separatorAfter, collector);
  5265. }
  5266. };
  5267. if (node.type === 'property') {
  5268. if (offset > node.colonOffset) {
  5269. var valueNode = node.valueNode;
  5270. if (valueNode && (offset > (valueNode.offset + valueNode.length) || valueNode.type === 'object' || valueNode.type === 'array')) {
  5271. return;
  5272. }
  5273. // suggest values at the same key
  5274. var parentKey_2 = node.keyNode.value;
  5275. doc.visit(function (n) {
  5276. if (n.type === 'property' && n.keyNode.value === parentKey_2 && n.valueNode) {
  5277. collectSuggestionsForValues(n.valueNode);
  5278. }
  5279. return true;
  5280. });
  5281. if (parentKey_2 === '$schema' && node.parent && !node.parent.parent) {
  5282. this.addDollarSchemaCompletions(separatorAfter, collector);
  5283. }
  5284. }
  5285. }
  5286. if (node.type === 'array') {
  5287. if (node.parent && node.parent.type === 'property') {
  5288. // suggest items of an array at the same key
  5289. var parentKey_3 = node.parent.keyNode.value;
  5290. doc.visit(function (n) {
  5291. if (n.type === 'property' && n.keyNode.value === parentKey_3 && n.valueNode && n.valueNode.type === 'array') {
  5292. n.valueNode.items.forEach(collectSuggestionsForValues);
  5293. }
  5294. return true;
  5295. });
  5296. }
  5297. else {
  5298. // suggest items in the same array
  5299. node.items.forEach(collectSuggestionsForValues);
  5300. }
  5301. }
  5302. };
  5303. JSONCompletion.prototype.getValueCompletions = function (schema, doc, node, offset, document, collector, types) {
  5304. var _this = this;
  5305. var offsetForSeparator = offset;
  5306. var parentKey = null;
  5307. var valueNode = null;
  5308. if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
  5309. offsetForSeparator = node.offset + node.length;
  5310. valueNode = node;
  5311. node = node.parent;
  5312. }
  5313. if (!node) {
  5314. this.addSchemaValueCompletions(schema.schema, '', collector, types);
  5315. return;
  5316. }
  5317. if ((node.type === 'property') && offset > node.colonOffset) {
  5318. var valueNode_1 = node.valueNode;
  5319. if (valueNode_1 && offset > (valueNode_1.offset + valueNode_1.length)) {
  5320. return; // we are past the value node
  5321. }
  5322. parentKey = node.keyNode.value;
  5323. node = node.parent;
  5324. }
  5325. if (node && (parentKey !== null || node.type === 'array')) {
  5326. var separatorAfter_2 = this.evaluateSeparatorAfter(document, offsetForSeparator);
  5327. var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset, valueNode);
  5328. matchingSchemas.forEach(function (s) {
  5329. if (s.node === node && !s.inverted && s.schema) {
  5330. if (node.type === 'array' && s.schema.items) {
  5331. if (Array.isArray(s.schema.items)) {
  5332. var index = _this.findItemAtOffset(node, document, offset);
  5333. if (index < s.schema.items.length) {
  5334. _this.addSchemaValueCompletions(s.schema.items[index], separatorAfter_2, collector, types);
  5335. }
  5336. }
  5337. else {
  5338. _this.addSchemaValueCompletions(s.schema.items, separatorAfter_2, collector, types);
  5339. }
  5340. }
  5341. if (s.schema.properties) {
  5342. var propertySchema = s.schema.properties[parentKey];
  5343. if (propertySchema) {
  5344. _this.addSchemaValueCompletions(propertySchema, separatorAfter_2, collector, types);
  5345. }
  5346. }
  5347. }
  5348. });
  5349. if (parentKey === '$schema' && !node.parent) {
  5350. this.addDollarSchemaCompletions(separatorAfter_2, collector);
  5351. }
  5352. if (types['boolean']) {
  5353. this.addBooleanValueCompletion(true, separatorAfter_2, collector);
  5354. this.addBooleanValueCompletion(false, separatorAfter_2, collector);
  5355. }
  5356. if (types['null']) {
  5357. this.addNullValueCompletion(separatorAfter_2, collector);
  5358. }
  5359. }
  5360. };
  5361. JSONCompletion.prototype.getContributedValueCompletions = function (doc, node, offset, document, collector, collectionPromises) {
  5362. if (!node) {
  5363. this.contributions.forEach(function (contribution) {
  5364. var collectPromise = contribution.collectDefaultCompletions(document.uri, collector);
  5365. if (collectPromise) {
  5366. collectionPromises.push(collectPromise);
  5367. }
  5368. });
  5369. }
  5370. else {
  5371. if (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null') {
  5372. node = node.parent;
  5373. }
  5374. if ((node.type === 'property') && offset > node.colonOffset) {
  5375. var parentKey_4 = node.keyNode.value;
  5376. var valueNode = node.valueNode;
  5377. if (!valueNode || offset <= (valueNode.offset + valueNode.length)) {
  5378. var location_2 = Parser.getNodePath(node.parent);
  5379. this.contributions.forEach(function (contribution) {
  5380. var collectPromise = contribution.collectValueCompletions(document.uri, location_2, parentKey_4, collector);
  5381. if (collectPromise) {
  5382. collectionPromises.push(collectPromise);
  5383. }
  5384. });
  5385. }
  5386. }
  5387. }
  5388. };
  5389. JSONCompletion.prototype.addSchemaValueCompletions = function (schema, separatorAfter, collector, types) {
  5390. var _this = this;
  5391. if (typeof schema === 'object') {
  5392. this.addEnumValueCompletions(schema, separatorAfter, collector);
  5393. this.addDefaultValueCompletions(schema, separatorAfter, collector);
  5394. this.collectTypes(schema, types);
  5395. if (Array.isArray(schema.allOf)) {
  5396. schema.allOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
  5397. }
  5398. if (Array.isArray(schema.anyOf)) {
  5399. schema.anyOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
  5400. }
  5401. if (Array.isArray(schema.oneOf)) {
  5402. schema.oneOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
  5403. }
  5404. }
  5405. };
  5406. JSONCompletion.prototype.addDefaultValueCompletions = function (schema, separatorAfter, collector, arrayDepth) {
  5407. var _this = this;
  5408. if (arrayDepth === void 0) { arrayDepth = 0; }
  5409. var hasProposals = false;
  5410. if (objects_1.isDefined(schema.default)) {
  5411. var type = schema.type;
  5412. var value = schema.default;
  5413. for (var i = arrayDepth; i > 0; i--) {
  5414. value = [value];
  5415. type = 'array';
  5416. }
  5417. collector.add({
  5418. kind: this.getSuggestionKind(type),
  5419. label: this.getLabelForValue(value),
  5420. insertText: this.getInsertTextForValue(value, separatorAfter),
  5421. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5422. detail: localize('json.suggest.default', 'Default value')
  5423. });
  5424. hasProposals = true;
  5425. }
  5426. if (Array.isArray(schema.examples)) {
  5427. schema.examples.forEach(function (example) {
  5428. var type = schema.type;
  5429. var value = example;
  5430. for (var i = arrayDepth; i > 0; i--) {
  5431. value = [value];
  5432. type = 'array';
  5433. }
  5434. collector.add({
  5435. kind: _this.getSuggestionKind(type),
  5436. label: _this.getLabelForValue(value),
  5437. insertText: _this.getInsertTextForValue(value, separatorAfter),
  5438. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet
  5439. });
  5440. hasProposals = true;
  5441. });
  5442. }
  5443. if (Array.isArray(schema.defaultSnippets)) {
  5444. schema.defaultSnippets.forEach(function (s) {
  5445. var type = schema.type;
  5446. var value = s.body;
  5447. var label = s.label;
  5448. var insertText;
  5449. var filterText;
  5450. if (objects_1.isDefined(value)) {
  5451. var type_1 = schema.type;
  5452. for (var i = arrayDepth; i > 0; i--) {
  5453. value = [value];
  5454. type_1 = 'array';
  5455. }
  5456. insertText = _this.getInsertTextForSnippetValue(value, separatorAfter);
  5457. filterText = _this.getFilterTextForSnippetValue(value);
  5458. label = label || _this.getLabelForSnippetValue(value);
  5459. }
  5460. else if (typeof s.bodyText === 'string') {
  5461. var prefix = '', suffix = '', indent = '';
  5462. for (var i = arrayDepth; i > 0; i--) {
  5463. prefix = prefix + indent + '[\n';
  5464. suffix = suffix + '\n' + indent + ']';
  5465. indent += '\t';
  5466. type = 'array';
  5467. }
  5468. insertText = prefix + indent + s.bodyText.split('\n').join('\n' + indent) + suffix + separatorAfter;
  5469. label = label || insertText,
  5470. filterText = insertText.replace(/[\n]/g, ''); // remove new lines
  5471. }
  5472. collector.add({
  5473. kind: _this.getSuggestionKind(type),
  5474. label: label,
  5475. documentation: _this.fromMarkup(s.markdownDescription) || s.description,
  5476. insertText: insertText,
  5477. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5478. filterText: filterText
  5479. });
  5480. hasProposals = true;
  5481. });
  5482. }
  5483. if (!hasProposals && typeof schema.items === 'object' && !Array.isArray(schema.items)) {
  5484. this.addDefaultValueCompletions(schema.items, separatorAfter, collector, arrayDepth + 1);
  5485. }
  5486. };
  5487. JSONCompletion.prototype.addEnumValueCompletions = function (schema, separatorAfter, collector) {
  5488. if (objects_1.isDefined(schema.const)) {
  5489. collector.add({
  5490. kind: this.getSuggestionKind(schema.type),
  5491. label: this.getLabelForValue(schema.const),
  5492. insertText: this.getInsertTextForValue(schema.const, separatorAfter),
  5493. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5494. documentation: this.fromMarkup(schema.markdownDescription) || schema.description
  5495. });
  5496. }
  5497. if (Array.isArray(schema.enum)) {
  5498. for (var i = 0, length = schema.enum.length; i < length; i++) {
  5499. var enm = schema.enum[i];
  5500. var documentation = this.fromMarkup(schema.markdownDescription) || schema.description;
  5501. if (schema.markdownEnumDescriptions && i < schema.markdownEnumDescriptions.length && this.doesSupportMarkdown()) {
  5502. documentation = this.fromMarkup(schema.markdownEnumDescriptions[i]);
  5503. }
  5504. else if (schema.enumDescriptions && i < schema.enumDescriptions.length) {
  5505. documentation = schema.enumDescriptions[i];
  5506. }
  5507. collector.add({
  5508. kind: this.getSuggestionKind(schema.type),
  5509. label: this.getLabelForValue(enm),
  5510. insertText: this.getInsertTextForValue(enm, separatorAfter),
  5511. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5512. documentation: documentation
  5513. });
  5514. }
  5515. }
  5516. };
  5517. JSONCompletion.prototype.collectTypes = function (schema, types) {
  5518. if (Array.isArray(schema.enum) || objects_1.isDefined(schema.const)) {
  5519. return;
  5520. }
  5521. var type = schema.type;
  5522. if (Array.isArray(type)) {
  5523. type.forEach(function (t) { return types[t] = true; });
  5524. }
  5525. else {
  5526. types[type] = true;
  5527. }
  5528. };
  5529. JSONCompletion.prototype.addFillerValueCompletions = function (types, separatorAfter, collector) {
  5530. if (types['object']) {
  5531. collector.add({
  5532. kind: this.getSuggestionKind('object'),
  5533. label: '{}',
  5534. insertText: this.getInsertTextForGuessedValue({}, separatorAfter),
  5535. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5536. detail: localize('defaults.object', 'New object'),
  5537. documentation: ''
  5538. });
  5539. }
  5540. if (types['array']) {
  5541. collector.add({
  5542. kind: this.getSuggestionKind('array'),
  5543. label: '[]',
  5544. insertText: this.getInsertTextForGuessedValue([], separatorAfter),
  5545. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5546. detail: localize('defaults.array', 'New array'),
  5547. documentation: ''
  5548. });
  5549. }
  5550. };
  5551. JSONCompletion.prototype.addBooleanValueCompletion = function (value, separatorAfter, collector) {
  5552. collector.add({
  5553. kind: this.getSuggestionKind('boolean'),
  5554. label: value ? 'true' : 'false',
  5555. insertText: this.getInsertTextForValue(value, separatorAfter),
  5556. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5557. documentation: ''
  5558. });
  5559. };
  5560. JSONCompletion.prototype.addNullValueCompletion = function (separatorAfter, collector) {
  5561. collector.add({
  5562. kind: this.getSuggestionKind('null'),
  5563. label: 'null',
  5564. insertText: 'null' + separatorAfter,
  5565. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
  5566. documentation: ''
  5567. });
  5568. };
  5569. JSONCompletion.prototype.addDollarSchemaCompletions = function (separatorAfter, collector) {
  5570. var _this = this;
  5571. var schemaIds = this.schemaService.getRegisteredSchemaIds(function (schema) { return schema === 'http' || schema === 'https'; });
  5572. schemaIds.forEach(function (schemaId) { return collector.add({
  5573. kind: jsonLanguageTypes_1.CompletionItemKind.Module,
  5574. label: _this.getLabelForValue(schemaId),
  5575. filterText: _this.getFilterTextForValue(schemaId),
  5576. insertText: _this.getInsertTextForValue(schemaId, separatorAfter),
  5577. insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet, documentation: ''
  5578. }); });
  5579. };
  5580. JSONCompletion.prototype.getLabelForValue = function (value) {
  5581. return JSON.stringify(value);
  5582. };
  5583. JSONCompletion.prototype.getFilterTextForValue = function (value) {
  5584. return JSON.stringify(value);
  5585. };
  5586. JSONCompletion.prototype.getFilterTextForSnippetValue = function (value) {
  5587. return JSON.stringify(value).replace(/\$\{\d+:([^}]+)\}|\$\d+/g, '$1');
  5588. };
  5589. JSONCompletion.prototype.getLabelForSnippetValue = function (value) {
  5590. var label = JSON.stringify(value);
  5591. return label.replace(/\$\{\d+:([^}]+)\}|\$\d+/g, '$1');
  5592. };
  5593. JSONCompletion.prototype.getInsertTextForPlainText = function (text) {
  5594. return text.replace(/[\\\$\}]/g, '\\$&'); // escape $, \ and }
  5595. };
  5596. JSONCompletion.prototype.getInsertTextForValue = function (value, separatorAfter) {
  5597. var text = JSON.stringify(value, null, '\t');
  5598. if (text === '{}') {
  5599. return '{$1}' + separatorAfter;
  5600. }
  5601. else if (text === '[]') {
  5602. return '[$1]' + separatorAfter;
  5603. }
  5604. return this.getInsertTextForPlainText(text + separatorAfter);
  5605. };
  5606. JSONCompletion.prototype.getInsertTextForSnippetValue = function (value, separatorAfter) {
  5607. var replacer = function (value) {
  5608. if (typeof value === 'string') {
  5609. if (value[0] === '^') {
  5610. return value.substr(1);
  5611. }
  5612. }
  5613. return JSON.stringify(value);
  5614. };
  5615. return json_1.stringifyObject(value, '', replacer) + separatorAfter;
  5616. };
  5617. JSONCompletion.prototype.getInsertTextForGuessedValue = function (value, separatorAfter) {
  5618. switch (typeof value) {
  5619. case 'object':
  5620. if (value === null) {
  5621. return '${1:null}' + separatorAfter;
  5622. }
  5623. return this.getInsertTextForValue(value, separatorAfter);
  5624. case 'string':
  5625. var snippetValue = JSON.stringify(value);
  5626. snippetValue = snippetValue.substr(1, snippetValue.length - 2); // remove quotes
  5627. snippetValue = this.getInsertTextForPlainText(snippetValue); // escape \ and }
  5628. return '"${1:' + snippetValue + '}"' + separatorAfter;
  5629. case 'number':
  5630. case 'boolean':
  5631. return '${1:' + JSON.stringify(value) + '}' + separatorAfter;
  5632. }
  5633. return this.getInsertTextForValue(value, separatorAfter);
  5634. };
  5635. JSONCompletion.prototype.getSuggestionKind = function (type) {
  5636. if (Array.isArray(type)) {
  5637. var array = type;
  5638. type = array.length > 0 ? array[0] : null;
  5639. }
  5640. if (!type) {
  5641. return jsonLanguageTypes_1.CompletionItemKind.Value;
  5642. }
  5643. switch (type) {
  5644. case 'string': return jsonLanguageTypes_1.CompletionItemKind.Value;
  5645. case 'object': return jsonLanguageTypes_1.CompletionItemKind.Module;
  5646. case 'property': return jsonLanguageTypes_1.CompletionItemKind.Property;
  5647. default: return jsonLanguageTypes_1.CompletionItemKind.Value;
  5648. }
  5649. };
  5650. JSONCompletion.prototype.getLabelTextForMatchingNode = function (node, document) {
  5651. switch (node.type) {
  5652. case 'array':
  5653. return '[]';
  5654. case 'object':
  5655. return '{}';
  5656. default:
  5657. var content = document.getText().substr(node.offset, node.length);
  5658. return content;
  5659. }
  5660. };
  5661. JSONCompletion.prototype.getInsertTextForMatchingNode = function (node, document, separatorAfter) {
  5662. switch (node.type) {
  5663. case 'array':
  5664. return this.getInsertTextForValue([], separatorAfter);
  5665. case 'object':
  5666. return this.getInsertTextForValue({}, separatorAfter);
  5667. default:
  5668. var content = document.getText().substr(node.offset, node.length) + separatorAfter;
  5669. return this.getInsertTextForPlainText(content);
  5670. }
  5671. };
  5672. JSONCompletion.prototype.getInsertTextForProperty = function (key, propertySchema, addValue, separatorAfter) {
  5673. var propertyText = this.getInsertTextForValue(key, '');
  5674. if (!addValue) {
  5675. return propertyText;
  5676. }
  5677. var resultText = propertyText + ': ';
  5678. var value;
  5679. var nValueProposals = 0;
  5680. if (propertySchema) {
  5681. if (Array.isArray(propertySchema.defaultSnippets)) {
  5682. if (propertySchema.defaultSnippets.length === 1) {
  5683. var body = propertySchema.defaultSnippets[0].body;
  5684. if (objects_1.isDefined(body)) {
  5685. value = this.getInsertTextForSnippetValue(body, '');
  5686. }
  5687. }
  5688. nValueProposals += propertySchema.defaultSnippets.length;
  5689. }
  5690. if (propertySchema.enum) {
  5691. if (!value && propertySchema.enum.length === 1) {
  5692. value = this.getInsertTextForGuessedValue(propertySchema.enum[0], '');
  5693. }
  5694. nValueProposals += propertySchema.enum.length;
  5695. }
  5696. if (objects_1.isDefined(propertySchema.default)) {
  5697. if (!value) {
  5698. value = this.getInsertTextForGuessedValue(propertySchema.default, '');
  5699. }
  5700. nValueProposals++;
  5701. }
  5702. if (Array.isArray(propertySchema.examples) && propertySchema.examples.length) {
  5703. if (!value) {
  5704. value = this.getInsertTextForGuessedValue(propertySchema.examples[0], '');
  5705. }
  5706. nValueProposals += propertySchema.examples.length;
  5707. }
  5708. if (nValueProposals === 0) {
  5709. var type = Array.isArray(propertySchema.type) ? propertySchema.type[0] : propertySchema.type;
  5710. if (!type) {
  5711. if (propertySchema.properties) {
  5712. type = 'object';
  5713. }
  5714. else if (propertySchema.items) {
  5715. type = 'array';
  5716. }
  5717. }
  5718. switch (type) {
  5719. case 'boolean':
  5720. value = '$1';
  5721. break;
  5722. case 'string':
  5723. value = '"$1"';
  5724. break;
  5725. case 'object':
  5726. value = '{$1}';
  5727. break;
  5728. case 'array':
  5729. value = '[$1]';
  5730. break;
  5731. case 'number':
  5732. case 'integer':
  5733. value = '${1:0}';
  5734. break;
  5735. case 'null':
  5736. value = '${1:null}';
  5737. break;
  5738. default:
  5739. return propertyText;
  5740. }
  5741. }
  5742. }
  5743. if (!value || nValueProposals > 1) {
  5744. value = '$1';
  5745. }
  5746. return resultText + value + separatorAfter;
  5747. };
  5748. JSONCompletion.prototype.getCurrentWord = function (document, offset) {
  5749. var i = offset - 1;
  5750. var text = document.getText();
  5751. while (i >= 0 && ' \t\n\r\v":{[,]}'.indexOf(text.charAt(i)) === -1) {
  5752. i--;
  5753. }
  5754. return text.substring(i + 1, offset);
  5755. };
  5756. JSONCompletion.prototype.evaluateSeparatorAfter = function (document, offset) {
  5757. var scanner = Json.createScanner(document.getText(), true);
  5758. scanner.setPosition(offset);
  5759. var token = scanner.scan();
  5760. switch (token) {
  5761. case 5 /* CommaToken */:
  5762. case 2 /* CloseBraceToken */:
  5763. case 4 /* CloseBracketToken */:
  5764. case 17 /* EOF */:
  5765. return '';
  5766. default:
  5767. return ',';
  5768. }
  5769. };
  5770. JSONCompletion.prototype.findItemAtOffset = function (node, document, offset) {
  5771. var scanner = Json.createScanner(document.getText(), true);
  5772. var children = node.items;
  5773. for (var i = children.length - 1; i >= 0; i--) {
  5774. var child = children[i];
  5775. if (offset > child.offset + child.length) {
  5776. scanner.setPosition(child.offset + child.length);
  5777. var token = scanner.scan();
  5778. if (token === 5 /* CommaToken */ && offset >= scanner.getTokenOffset() + scanner.getTokenLength()) {
  5779. return i + 1;
  5780. }
  5781. return i;
  5782. }
  5783. else if (offset >= child.offset) {
  5784. return i;
  5785. }
  5786. }
  5787. return 0;
  5788. };
  5789. JSONCompletion.prototype.isInComment = function (document, start, offset) {
  5790. var scanner = Json.createScanner(document.getText(), false);
  5791. scanner.setPosition(start);
  5792. var token = scanner.scan();
  5793. while (token !== 17 /* EOF */ && (scanner.getTokenOffset() + scanner.getTokenLength() < offset)) {
  5794. token = scanner.scan();
  5795. }
  5796. return (token === 12 /* LineCommentTrivia */ || token === 13 /* BlockCommentTrivia */) && scanner.getTokenOffset() <= offset;
  5797. };
  5798. JSONCompletion.prototype.fromMarkup = function (markupString) {
  5799. if (markupString && this.doesSupportMarkdown()) {
  5800. return {
  5801. kind: jsonLanguageTypes_1.MarkupKind.Markdown,
  5802. value: markupString
  5803. };
  5804. }
  5805. return undefined;
  5806. };
  5807. JSONCompletion.prototype.doesSupportMarkdown = function () {
  5808. if (!objects_1.isDefined(this.supportsMarkdown)) {
  5809. var completion = this.clientCapabilities.textDocument && this.clientCapabilities.textDocument.completion;
  5810. this.supportsMarkdown = completion && completion.completionItem && Array.isArray(completion.completionItem.documentationFormat) && completion.completionItem.documentationFormat.indexOf(jsonLanguageTypes_1.MarkupKind.Markdown) !== -1;
  5811. }
  5812. return this.supportsMarkdown;
  5813. };
  5814. JSONCompletion.prototype.doesSupportsCommitCharacters = function () {
  5815. if (!objects_1.isDefined(this.supportsCommitCharacters)) {
  5816. var completion = this.clientCapabilities.textDocument && this.clientCapabilities.textDocument.completion;
  5817. this.supportsCommitCharacters = completion && completion.completionItem && !!completion.completionItem.commitCharactersSupport;
  5818. }
  5819. return this.supportsCommitCharacters;
  5820. };
  5821. return JSONCompletion;
  5822. }());
  5823. exports.JSONCompletion = JSONCompletion;
  5824. });
  5825. /*---------------------------------------------------------------------------------------------
  5826. * Copyright (c) Microsoft Corporation. All rights reserved.
  5827. * Licensed under the MIT License. See License.txt in the project root for license information.
  5828. *--------------------------------------------------------------------------------------------*/
  5829. (function (factory) {
  5830. if (typeof module === "object" && typeof module.exports === "object") {
  5831. var v = factory(require, exports);
  5832. if (v !== undefined) module.exports = v;
  5833. }
  5834. else if (typeof define === "function" && define.amd) {
  5835. define('vscode-json-languageservice/services/jsonHover',["require", "exports", "../parser/jsonParser", "../jsonLanguageTypes"], factory);
  5836. }
  5837. })(function (require, exports) {
  5838. "use strict";
  5839. Object.defineProperty(exports, "__esModule", { value: true });
  5840. var Parser = require("../parser/jsonParser");
  5841. var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
  5842. var JSONHover = /** @class */ (function () {
  5843. function JSONHover(schemaService, contributions, promiseConstructor) {
  5844. if (contributions === void 0) { contributions = []; }
  5845. this.schemaService = schemaService;
  5846. this.contributions = contributions;
  5847. this.promise = promiseConstructor || Promise;
  5848. }
  5849. JSONHover.prototype.doHover = function (document, position, doc) {
  5850. var offset = document.offsetAt(position);
  5851. var node = doc.getNodeFromOffset(offset);
  5852. if (!node || (node.type === 'object' || node.type === 'array') && offset > node.offset + 1 && offset < node.offset + node.length - 1) {
  5853. return this.promise.resolve(null);
  5854. }
  5855. var hoverRangeNode = node;
  5856. // use the property description when hovering over an object key
  5857. if (node.type === 'string') {
  5858. var parent = node.parent;
  5859. if (parent && parent.type === 'property' && parent.keyNode === node) {
  5860. node = parent.valueNode;
  5861. if (!node) {
  5862. return this.promise.resolve(null);
  5863. }
  5864. }
  5865. }
  5866. var hoverRange = jsonLanguageTypes_1.Range.create(document.positionAt(hoverRangeNode.offset), document.positionAt(hoverRangeNode.offset + hoverRangeNode.length));
  5867. var createHover = function (contents) {
  5868. var result = {
  5869. contents: contents,
  5870. range: hoverRange
  5871. };
  5872. return result;
  5873. };
  5874. var location = Parser.getNodePath(node);
  5875. for (var i = this.contributions.length - 1; i >= 0; i--) {
  5876. var contribution = this.contributions[i];
  5877. var promise = contribution.getInfoContribution(document.uri, location);
  5878. if (promise) {
  5879. return promise.then(function (htmlContent) { return createHover(htmlContent); });
  5880. }
  5881. }
  5882. return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
  5883. if (schema) {
  5884. var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset);
  5885. var title_1 = null;
  5886. var markdownDescription_1 = null;
  5887. var markdownEnumValueDescription_1 = null, enumValue_1 = null;
  5888. matchingSchemas.every(function (s) {
  5889. if (s.node === node && !s.inverted && s.schema) {
  5890. title_1 = title_1 || s.schema.title;
  5891. markdownDescription_1 = markdownDescription_1 || s.schema.markdownDescription || toMarkdown(s.schema.description);
  5892. if (s.schema.enum) {
  5893. var idx = s.schema.enum.indexOf(Parser.getNodeValue(node));
  5894. if (s.schema.markdownEnumDescriptions) {
  5895. markdownEnumValueDescription_1 = s.schema.markdownEnumDescriptions[idx];
  5896. }
  5897. else if (s.schema.enumDescriptions) {
  5898. markdownEnumValueDescription_1 = toMarkdown(s.schema.enumDescriptions[idx]);
  5899. }
  5900. if (markdownEnumValueDescription_1) {
  5901. enumValue_1 = s.schema.enum[idx];
  5902. if (typeof enumValue_1 !== 'string') {
  5903. enumValue_1 = JSON.stringify(enumValue_1);
  5904. }
  5905. }
  5906. }
  5907. }
  5908. return true;
  5909. });
  5910. var result = '';
  5911. if (title_1) {
  5912. result = toMarkdown(title_1);
  5913. }
  5914. if (markdownDescription_1) {
  5915. if (result.length > 0) {
  5916. result += "\n\n";
  5917. }
  5918. result += markdownDescription_1;
  5919. }
  5920. if (markdownEnumValueDescription_1) {
  5921. if (result.length > 0) {
  5922. result += "\n\n";
  5923. }
  5924. result += "`" + toMarkdownCodeBlock(enumValue_1) + "`: " + markdownEnumValueDescription_1;
  5925. }
  5926. return createHover([result]);
  5927. }
  5928. return null;
  5929. });
  5930. };
  5931. return JSONHover;
  5932. }());
  5933. exports.JSONHover = JSONHover;
  5934. function toMarkdown(plain) {
  5935. if (plain) {
  5936. var res = plain.replace(/([^\n\r])(\r?\n)([^\n\r])/gm, '$1\n\n$3'); // single new lines to \n\n (Markdown paragraph)
  5937. return res.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&"); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
  5938. }
  5939. return void 0;
  5940. }
  5941. function toMarkdownCodeBlock(content) {
  5942. // see https://daringfireball.net/projects/markdown/syntax#precode
  5943. if (content.indexOf('`') !== -1) {
  5944. return '`` ' + content + ' ``';
  5945. }
  5946. return content;
  5947. }
  5948. });
  5949. var __extends = (this && this.__extends) || (function () {
  5950. var extendStatics = function (d, b) {
  5951. extendStatics = Object.setPrototypeOf ||
  5952. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  5953. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  5954. return extendStatics(d, b);
  5955. };
  5956. return function (d, b) {
  5957. extendStatics(d, b);
  5958. function __() { this.constructor = d; }
  5959. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  5960. };
  5961. })();
  5962. (function (factory) {
  5963. if (typeof module === "object" && typeof module.exports === "object") {
  5964. var v = factory(require, exports);
  5965. if (v !== undefined) module.exports = v;
  5966. }
  5967. else if (typeof define === "function" && define.amd) {
  5968. define('vscode-uri/index',["require", "exports"], factory);
  5969. }
  5970. })(function (require, exports) {
  5971. /*---------------------------------------------------------------------------------------------
  5972. * Copyright (c) Microsoft Corporation. All rights reserved.
  5973. * Licensed under the MIT License. See License.txt in the project root for license information.
  5974. *--------------------------------------------------------------------------------------------*/
  5975. 'use strict';
  5976. var _a;
  5977. Object.defineProperty(exports, "__esModule", { value: true });
  5978. var isWindows;
  5979. if (typeof process === 'object') {
  5980. isWindows = process.platform === 'win32';
  5981. }
  5982. else if (typeof navigator === 'object') {
  5983. var userAgent = navigator.userAgent;
  5984. isWindows = userAgent.indexOf('Windows') >= 0;
  5985. }
  5986. function isHighSurrogate(charCode) {
  5987. return (0xD800 <= charCode && charCode <= 0xDBFF);
  5988. }
  5989. function isLowSurrogate(charCode) {
  5990. return (0xDC00 <= charCode && charCode <= 0xDFFF);
  5991. }
  5992. function isLowerAsciiHex(code) {
  5993. return code >= 97 /* a */ && code <= 102 /* f */;
  5994. }
  5995. function isLowerAsciiLetter(code) {
  5996. return code >= 97 /* a */ && code <= 122 /* z */;
  5997. }
  5998. function isUpperAsciiLetter(code) {
  5999. return code >= 65 /* A */ && code <= 90 /* Z */;
  6000. }
  6001. function isAsciiLetter(code) {
  6002. return isLowerAsciiLetter(code) || isUpperAsciiLetter(code);
  6003. }
  6004. //#endregion
  6005. var _schemePattern = /^\w[\w\d+.-]*$/;
  6006. var _singleSlashStart = /^\//;
  6007. var _doubleSlashStart = /^\/\//;
  6008. function _validateUri(ret, _strict) {
  6009. // scheme, must be set
  6010. if (!ret.scheme && _strict) {
  6011. throw new Error("[UriError]: Scheme is missing: {scheme: \"\", authority: \"" + ret.authority + "\", path: \"" + ret.path + "\", query: \"" + ret.query + "\", fragment: \"" + ret.fragment + "\"}");
  6012. }
  6013. // scheme, https://tools.ietf.org/html/rfc3986#section-3.1
  6014. // ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  6015. if (ret.scheme && !_schemePattern.test(ret.scheme)) {
  6016. throw new Error('[UriError]: Scheme contains illegal characters.');
  6017. }
  6018. // path, http://tools.ietf.org/html/rfc3986#section-3.3
  6019. // If a URI contains an authority component, then the path component
  6020. // must either be empty or begin with a slash ("/") character. If a URI
  6021. // does not contain an authority component, then the path cannot begin
  6022. // with two slash characters ("//").
  6023. if (ret.path) {
  6024. if (ret.authority) {
  6025. if (!_singleSlashStart.test(ret.path)) {
  6026. 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');
  6027. }
  6028. }
  6029. else {
  6030. if (_doubleSlashStart.test(ret.path)) {
  6031. throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")');
  6032. }
  6033. }
  6034. }
  6035. }
  6036. // for a while we allowed uris *without* schemes and this is the migration
  6037. // for them, e.g. an uri without scheme and without strict-mode warns and falls
  6038. // back to the file-scheme. that should cause the least carnage and still be a
  6039. // clear warning
  6040. function _schemeFix(scheme, _strict) {
  6041. if (!scheme && !_strict) {
  6042. return 'file';
  6043. }
  6044. return scheme;
  6045. }
  6046. // implements a bit of https://tools.ietf.org/html/rfc3986#section-5
  6047. function _referenceResolution(scheme, path) {
  6048. // the slash-character is our 'default base' as we don't
  6049. // support constructing URIs relative to other URIs. This
  6050. // also means that we alter and potentially break paths.
  6051. // see https://tools.ietf.org/html/rfc3986#section-5.1.4
  6052. switch (scheme) {
  6053. case 'https':
  6054. case 'http':
  6055. case 'file':
  6056. if (!path) {
  6057. path = _slash;
  6058. }
  6059. else if (path[0] !== _slash) {
  6060. path = _slash + path;
  6061. }
  6062. break;
  6063. }
  6064. return path;
  6065. }
  6066. var _empty = '';
  6067. var _slash = '/';
  6068. var _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
  6069. /**
  6070. * Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986.
  6071. * This class is a simple parser which creates the basic component parts
  6072. * (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation
  6073. * and encoding.
  6074. *
  6075. * foo://example.com:8042/over/there?name=ferret#nose
  6076. * \_/ \______________/\_________/ \_________/ \__/
  6077. * | | | | |
  6078. * scheme authority path query fragment
  6079. * | _____________________|__
  6080. * / \ / \
  6081. * urn:example:animal:ferret:nose
  6082. */
  6083. var URI = /** @class */ (function () {
  6084. /**
  6085. * @internal
  6086. */
  6087. function URI(schemeOrData, authority, path, query, fragment, _strict) {
  6088. if (_strict === void 0) { _strict = false; }
  6089. if (typeof schemeOrData === 'object') {
  6090. this.scheme = schemeOrData.scheme || _empty;
  6091. this.authority = schemeOrData.authority || _empty;
  6092. this.path = schemeOrData.path || _empty;
  6093. this.query = schemeOrData.query || _empty;
  6094. this.fragment = schemeOrData.fragment || _empty;
  6095. // no validation because it's this URI
  6096. // that creates uri components.
  6097. // _validateUri(this);
  6098. }
  6099. else {
  6100. this.scheme = _schemeFix(schemeOrData, _strict);
  6101. this.authority = authority || _empty;
  6102. this.path = _referenceResolution(this.scheme, path || _empty);
  6103. this.query = query || _empty;
  6104. this.fragment = fragment || _empty;
  6105. _validateUri(this, _strict);
  6106. }
  6107. }
  6108. URI.isUri = function (thing) {
  6109. if (thing instanceof URI) {
  6110. return true;
  6111. }
  6112. if (!thing) {
  6113. return false;
  6114. }
  6115. return typeof thing.authority === 'string'
  6116. && typeof thing.fragment === 'string'
  6117. && typeof thing.path === 'string'
  6118. && typeof thing.query === 'string'
  6119. && typeof thing.scheme === 'string'
  6120. && typeof thing.fsPath === 'function'
  6121. && typeof thing.with === 'function'
  6122. && typeof thing.toString === 'function';
  6123. };
  6124. Object.defineProperty(URI.prototype, "fsPath", {
  6125. // ---- filesystem path -----------------------
  6126. /**
  6127. * Returns a string representing the corresponding file system path of this URI.
  6128. * Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the
  6129. * platform specific path separator.
  6130. *
  6131. * * Will *not* validate the path for invalid characters and semantics.
  6132. * * Will *not* look at the scheme of this URI.
  6133. * * The result shall *not* be used for display purposes but for accessing a file on disk.
  6134. *
  6135. *
  6136. * The *difference* to `URI#path` is the use of the platform specific separator and the handling
  6137. * of UNC paths. See the below sample of a file-uri with an authority (UNC path).
  6138. *
  6139. * ```ts
  6140. const u = URI.parse('file://server/c$/folder/file.txt')
  6141. u.authority === 'server'
  6142. u.path === '/shares/c$/file.txt'
  6143. u.fsPath === '\\server\c$\folder\file.txt'
  6144. ```
  6145. *
  6146. * Using `URI#path` to read a file (using fs-apis) would not be enough because parts of the path,
  6147. * namely the server name, would be missing. Therefore `URI#fsPath` exists - it's sugar to ease working
  6148. * with URIs that represent files on disk (`file` scheme).
  6149. */
  6150. get: function () {
  6151. // if (this.scheme !== 'file') {
  6152. // console.warn(`[UriError] calling fsPath with scheme ${this.scheme}`);
  6153. // }
  6154. return _makeFsPath(this);
  6155. },
  6156. enumerable: true,
  6157. configurable: true
  6158. });
  6159. // ---- modify to new -------------------------
  6160. URI.prototype.with = function (change) {
  6161. if (!change) {
  6162. return this;
  6163. }
  6164. var scheme = change.scheme, authority = change.authority, path = change.path, query = change.query, fragment = change.fragment;
  6165. if (scheme === undefined) {
  6166. scheme = this.scheme;
  6167. }
  6168. else if (scheme === null) {
  6169. scheme = _empty;
  6170. }
  6171. if (authority === undefined) {
  6172. authority = this.authority;
  6173. }
  6174. else if (authority === null) {
  6175. authority = _empty;
  6176. }
  6177. if (path === undefined) {
  6178. path = this.path;
  6179. }
  6180. else if (path === null) {
  6181. path = _empty;
  6182. }
  6183. if (query === undefined) {
  6184. query = this.query;
  6185. }
  6186. else if (query === null) {
  6187. query = _empty;
  6188. }
  6189. if (fragment === undefined) {
  6190. fragment = this.fragment;
  6191. }
  6192. else if (fragment === null) {
  6193. fragment = _empty;
  6194. }
  6195. if (scheme === this.scheme
  6196. && authority === this.authority
  6197. && path === this.path
  6198. && query === this.query
  6199. && fragment === this.fragment) {
  6200. return this;
  6201. }
  6202. return new _URI(scheme, authority, path, query, fragment);
  6203. };
  6204. // ---- parse & validate ------------------------
  6205. /**
  6206. * Creates a new URI from a string, e.g. `http://www.msft.com/some/path`,
  6207. * `file:///usr/home`, or `scheme:with/path`.
  6208. *
  6209. * @param value A string which represents an URI (see `URI#toString`).
  6210. */
  6211. URI.parse = function (value, _strict) {
  6212. if (_strict === void 0) { _strict = false; }
  6213. var match = _regexp.exec(value);
  6214. if (!match) {
  6215. return new _URI(_empty, _empty, _empty, _empty, _empty);
  6216. }
  6217. return new _URI(match[2] || _empty, decodeURIComponent(match[4] || _empty), decodeURIComponent(match[5] || _empty), decodeURIComponent(match[7] || _empty), decodeURIComponent(match[9] || _empty), _strict);
  6218. };
  6219. /**
  6220. * Creates a new URI from a file system path, e.g. `c:\my\files`,
  6221. * `/usr/home`, or `\\server\share\some\path`.
  6222. *
  6223. * The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument
  6224. * as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as**
  6225. * `URI.parse('file://' + path)` because the path might contain characters that are
  6226. * interpreted (# and ?). See the following sample:
  6227. * ```ts
  6228. const good = URI.file('/coding/c#/project1');
  6229. good.scheme === 'file';
  6230. good.path === '/coding/c#/project1';
  6231. good.fragment === '';
  6232. const bad = URI.parse('file://' + '/coding/c#/project1');
  6233. bad.scheme === 'file';
  6234. bad.path === '/coding/c'; // path is now broken
  6235. bad.fragment === '/project1';
  6236. ```
  6237. *
  6238. * @param path A file system path (see `URI#fsPath`)
  6239. */
  6240. URI.file = function (path) {
  6241. var authority = _empty;
  6242. // normalize to fwd-slashes on windows,
  6243. // on other systems bwd-slashes are valid
  6244. // filename character, eg /f\oo/ba\r.txt
  6245. if (isWindows) {
  6246. path = path.replace(/\\/g, _slash);
  6247. }
  6248. // check for authority as used in UNC shares
  6249. // or use the path as given
  6250. if (path[0] === _slash && path[1] === _slash) {
  6251. var idx = path.indexOf(_slash, 2);
  6252. if (idx === -1) {
  6253. authority = path.substring(2);
  6254. path = _slash;
  6255. }
  6256. else {
  6257. authority = path.substring(2, idx);
  6258. path = path.substring(idx) || _slash;
  6259. }
  6260. }
  6261. return new _URI('file', authority, path, _empty, _empty);
  6262. };
  6263. URI.from = function (components) {
  6264. return new _URI(components.scheme, components.authority, components.path, components.query, components.fragment);
  6265. };
  6266. // ---- printing/externalize ---------------------------
  6267. /**
  6268. * Creates a string representation for this URI. It's guaranteed that calling
  6269. * `URI.parse` with the result of this function creates an URI which is equal
  6270. * to this URI.
  6271. *
  6272. * * The result shall *not* be used for display purposes but for externalization or transport.
  6273. * * The result will be encoded using the percentage encoding and encoding happens mostly
  6274. * ignore the scheme-specific encoding rules.
  6275. *
  6276. * @param skipEncoding Do not encode the result, default is `false`
  6277. */
  6278. URI.prototype.toString = function (skipEncoding) {
  6279. if (skipEncoding === void 0) { skipEncoding = false; }
  6280. return _asFormatted(this, skipEncoding);
  6281. };
  6282. URI.prototype.toJSON = function () {
  6283. return this;
  6284. };
  6285. URI.revive = function (data) {
  6286. if (!data) {
  6287. return data;
  6288. }
  6289. else if (data instanceof URI) {
  6290. return data;
  6291. }
  6292. else {
  6293. var result = new _URI(data);
  6294. result._formatted = data.external;
  6295. result._fsPath = data._sep === _pathSepMarker ? data.fsPath : null;
  6296. return result;
  6297. }
  6298. };
  6299. return URI;
  6300. }());
  6301. exports.URI = URI;
  6302. var _pathSepMarker = isWindows ? 1 : undefined;
  6303. // tslint:disable-next-line:class-name
  6304. var _URI = /** @class */ (function (_super) {
  6305. __extends(_URI, _super);
  6306. function _URI() {
  6307. var _this = _super !== null && _super.apply(this, arguments) || this;
  6308. _this._formatted = null;
  6309. _this._fsPath = null;
  6310. return _this;
  6311. }
  6312. Object.defineProperty(_URI.prototype, "fsPath", {
  6313. get: function () {
  6314. if (!this._fsPath) {
  6315. this._fsPath = _makeFsPath(this);
  6316. }
  6317. return this._fsPath;
  6318. },
  6319. enumerable: true,
  6320. configurable: true
  6321. });
  6322. _URI.prototype.toString = function (skipEncoding) {
  6323. if (skipEncoding === void 0) { skipEncoding = false; }
  6324. if (!skipEncoding) {
  6325. if (!this._formatted) {
  6326. this._formatted = _asFormatted(this, false);
  6327. }
  6328. return this._formatted;
  6329. }
  6330. else {
  6331. // we don't cache that
  6332. return _asFormatted(this, true);
  6333. }
  6334. };
  6335. _URI.prototype.toJSON = function () {
  6336. var res = {
  6337. $mid: 1
  6338. };
  6339. // cached state
  6340. if (this._fsPath) {
  6341. res.fsPath = this._fsPath;
  6342. res._sep = _pathSepMarker;
  6343. }
  6344. if (this._formatted) {
  6345. res.external = this._formatted;
  6346. }
  6347. // uri components
  6348. if (this.path) {
  6349. res.path = this.path;
  6350. }
  6351. if (this.scheme) {
  6352. res.scheme = this.scheme;
  6353. }
  6354. if (this.authority) {
  6355. res.authority = this.authority;
  6356. }
  6357. if (this.query) {
  6358. res.query = this.query;
  6359. }
  6360. if (this.fragment) {
  6361. res.fragment = this.fragment;
  6362. }
  6363. return res;
  6364. };
  6365. return _URI;
  6366. }(URI));
  6367. // reserved characters: https://tools.ietf.org/html/rfc3986#section-2.2
  6368. var encodeTable = (_a = {},
  6369. _a[58 /* Colon */] = '%3A',
  6370. _a[47 /* Slash */] = '%2F',
  6371. _a[63 /* QuestionMark */] = '%3F',
  6372. _a[35 /* Hash */] = '%23',
  6373. _a[91 /* OpenSquareBracket */] = '%5B',
  6374. _a[93 /* CloseSquareBracket */] = '%5D',
  6375. _a[64 /* AtSign */] = '%40',
  6376. _a[33 /* ExclamationMark */] = '%21',
  6377. _a[36 /* DollarSign */] = '%24',
  6378. _a[38 /* Ampersand */] = '%26',
  6379. _a[39 /* SingleQuote */] = '%27',
  6380. _a[40 /* OpenParen */] = '%28',
  6381. _a[41 /* CloseParen */] = '%29',
  6382. _a[42 /* Asterisk */] = '%2A',
  6383. _a[43 /* Plus */] = '%2B',
  6384. _a[44 /* Comma */] = '%2C',
  6385. _a[59 /* Semicolon */] = '%3B',
  6386. _a[61 /* Equals */] = '%3D',
  6387. _a[32 /* Space */] = '%20',
  6388. _a);
  6389. function encodeURIComponentFast(uriComponent, allowSlash) {
  6390. var res = undefined;
  6391. var nativeEncodePos = -1;
  6392. for (var pos = 0; pos < uriComponent.length; pos++) {
  6393. var code = uriComponent.charCodeAt(pos);
  6394. // unreserved characters: https://tools.ietf.org/html/rfc3986#section-2.3
  6395. if ((code >= 97 /* a */ && code <= 122 /* z */)
  6396. || (code >= 65 /* A */ && code <= 90 /* Z */)
  6397. || (code >= 48 /* Digit0 */ && code <= 57 /* Digit9 */)
  6398. || code === 45 /* Dash */
  6399. || code === 46 /* Period */
  6400. || code === 95 /* Underline */
  6401. || code === 126 /* Tilde */
  6402. || (allowSlash && code === 47 /* Slash */)) {
  6403. // check if we are delaying native encode
  6404. if (nativeEncodePos !== -1) {
  6405. res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
  6406. nativeEncodePos = -1;
  6407. }
  6408. // check if we write into a new string (by default we try to return the param)
  6409. if (res !== undefined) {
  6410. res += uriComponent.charAt(pos);
  6411. }
  6412. }
  6413. else {
  6414. // encoding needed, we need to allocate a new string
  6415. if (res === undefined) {
  6416. res = uriComponent.substr(0, pos);
  6417. }
  6418. // check with default table first
  6419. var escaped = encodeTable[code];
  6420. if (escaped !== undefined) {
  6421. // check if we are delaying native encode
  6422. if (nativeEncodePos !== -1) {
  6423. res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
  6424. nativeEncodePos = -1;
  6425. }
  6426. // append escaped variant to result
  6427. res += escaped;
  6428. }
  6429. else if (nativeEncodePos === -1) {
  6430. // use native encode only when needed
  6431. nativeEncodePos = pos;
  6432. }
  6433. }
  6434. }
  6435. if (nativeEncodePos !== -1) {
  6436. res += encodeURIComponent(uriComponent.substring(nativeEncodePos));
  6437. }
  6438. return res !== undefined ? res : uriComponent;
  6439. }
  6440. function encodeURIComponentMinimal(path) {
  6441. var res = undefined;
  6442. for (var pos = 0; pos < path.length; pos++) {
  6443. var code = path.charCodeAt(pos);
  6444. if (code === 35 /* Hash */ || code === 63 /* QuestionMark */) {
  6445. if (res === undefined) {
  6446. res = path.substr(0, pos);
  6447. }
  6448. res += encodeTable[code];
  6449. }
  6450. else {
  6451. if (res !== undefined) {
  6452. res += path[pos];
  6453. }
  6454. }
  6455. }
  6456. return res !== undefined ? res : path;
  6457. }
  6458. /**
  6459. * Compute `fsPath` for the given uri
  6460. */
  6461. function _makeFsPath(uri) {
  6462. var value;
  6463. if (uri.authority && uri.path.length > 1 && uri.scheme === 'file') {
  6464. // unc path: file://shares/c$/far/boo
  6465. value = "//" + uri.authority + uri.path;
  6466. }
  6467. else if (uri.path.charCodeAt(0) === 47 /* Slash */
  6468. && (uri.path.charCodeAt(1) >= 65 /* A */ && uri.path.charCodeAt(1) <= 90 /* Z */ || uri.path.charCodeAt(1) >= 97 /* a */ && uri.path.charCodeAt(1) <= 122 /* z */)
  6469. && uri.path.charCodeAt(2) === 58 /* Colon */) {
  6470. // windows drive letter: file:///c:/far/boo
  6471. value = uri.path[1].toLowerCase() + uri.path.substr(2);
  6472. }
  6473. else {
  6474. // other path
  6475. value = uri.path;
  6476. }
  6477. if (isWindows) {
  6478. value = value.replace(/\//g, '\\');
  6479. }
  6480. return value;
  6481. }
  6482. /**
  6483. * Create the external version of a uri
  6484. */
  6485. function _asFormatted(uri, skipEncoding) {
  6486. var encoder = !skipEncoding
  6487. ? encodeURIComponentFast
  6488. : encodeURIComponentMinimal;
  6489. var res = '';
  6490. var scheme = uri.scheme, authority = uri.authority, path = uri.path, query = uri.query, fragment = uri.fragment;
  6491. if (scheme) {
  6492. res += scheme;
  6493. res += ':';
  6494. }
  6495. if (authority || scheme === 'file') {
  6496. res += _slash;
  6497. res += _slash;
  6498. }
  6499. if (authority) {
  6500. var idx = authority.indexOf('@');
  6501. if (idx !== -1) {
  6502. // <user>@<auth>
  6503. var userinfo = authority.substr(0, idx);
  6504. authority = authority.substr(idx + 1);
  6505. idx = userinfo.indexOf(':');
  6506. if (idx === -1) {
  6507. res += encoder(userinfo, false);
  6508. }
  6509. else {
  6510. // <user>:<pass>@<auth>
  6511. res += encoder(userinfo.substr(0, idx), false);
  6512. res += ':';
  6513. res += encoder(userinfo.substr(idx + 1), false);
  6514. }
  6515. res += '@';
  6516. }
  6517. authority = authority.toLowerCase();
  6518. idx = authority.indexOf(':');
  6519. if (idx === -1) {
  6520. res += encoder(authority, false);
  6521. }
  6522. else {
  6523. // <auth>:<port>
  6524. res += encoder(authority.substr(0, idx), false);
  6525. res += authority.substr(idx);
  6526. }
  6527. }
  6528. if (path) {
  6529. // lower-case windows drive letters in /C:/fff or C:/fff
  6530. if (path.length >= 3 && path.charCodeAt(0) === 47 /* Slash */ && path.charCodeAt(2) === 58 /* Colon */) {
  6531. var code = path.charCodeAt(1);
  6532. if (code >= 65 /* A */ && code <= 90 /* Z */) {
  6533. path = "/" + String.fromCharCode(code + 32) + ":" + path.substr(3); // "/c:".length === 3
  6534. }
  6535. }
  6536. else if (path.length >= 2 && path.charCodeAt(1) === 58 /* Colon */) {
  6537. var code = path.charCodeAt(0);
  6538. if (code >= 65 /* A */ && code <= 90 /* Z */) {
  6539. path = String.fromCharCode(code + 32) + ":" + path.substr(2); // "/c:".length === 3
  6540. }
  6541. }
  6542. // encode the rest of the path
  6543. res += encoder(path, true);
  6544. }
  6545. if (query) {
  6546. res += '?';
  6547. res += encoder(query, false);
  6548. }
  6549. if (fragment) {
  6550. res += '#';
  6551. res += !skipEncoding ? encodeURIComponentFast(fragment, false) : fragment;
  6552. }
  6553. return res;
  6554. }
  6555. });
  6556. define('vscode-uri', ['vscode-uri/index'], function (main) { return main; });
  6557. /*---------------------------------------------------------------------------------------------
  6558. * Copyright (c) Microsoft Corporation. All rights reserved.
  6559. * Licensed under the MIT License. See License.txt in the project root for license information.
  6560. *--------------------------------------------------------------------------------------------*/
  6561. (function (factory) {
  6562. if (typeof module === "object" && typeof module.exports === "object") {
  6563. var v = factory(require, exports);
  6564. if (v !== undefined) module.exports = v;
  6565. }
  6566. else if (typeof define === "function" && define.amd) {
  6567. define('vscode-json-languageservice/services/jsonSchemaService',["require", "exports", "jsonc-parser", "vscode-uri", "../utils/strings", "../parser/jsonParser", "vscode-nls"], factory);
  6568. }
  6569. })(function (require, exports) {
  6570. "use strict";
  6571. Object.defineProperty(exports, "__esModule", { value: true });
  6572. var Json = require("jsonc-parser");
  6573. var vscode_uri_1 = require("vscode-uri");
  6574. var Strings = require("../utils/strings");
  6575. var Parser = require("../parser/jsonParser");
  6576. var nls = require("vscode-nls");
  6577. var localize = nls.loadMessageBundle();
  6578. var FilePatternAssociation = /** @class */ (function () {
  6579. function FilePatternAssociation(pattern) {
  6580. try {
  6581. this.patternRegExp = new RegExp(Strings.convertSimple2RegExpPattern(pattern) + '$');
  6582. }
  6583. catch (e) {
  6584. // invalid pattern
  6585. this.patternRegExp = null;
  6586. }
  6587. this.schemas = [];
  6588. }
  6589. FilePatternAssociation.prototype.addSchema = function (id) {
  6590. this.schemas.push(id);
  6591. };
  6592. FilePatternAssociation.prototype.matchesPattern = function (fileName) {
  6593. return this.patternRegExp && this.patternRegExp.test(fileName);
  6594. };
  6595. FilePatternAssociation.prototype.getSchemas = function () {
  6596. return this.schemas;
  6597. };
  6598. return FilePatternAssociation;
  6599. }());
  6600. var SchemaHandle = /** @class */ (function () {
  6601. function SchemaHandle(service, url, unresolvedSchemaContent) {
  6602. this.service = service;
  6603. this.url = url;
  6604. this.dependencies = {};
  6605. if (unresolvedSchemaContent) {
  6606. this.unresolvedSchema = this.service.promise.resolve(new UnresolvedSchema(unresolvedSchemaContent));
  6607. }
  6608. }
  6609. SchemaHandle.prototype.getUnresolvedSchema = function () {
  6610. if (!this.unresolvedSchema) {
  6611. this.unresolvedSchema = this.service.loadSchema(this.url);
  6612. }
  6613. return this.unresolvedSchema;
  6614. };
  6615. SchemaHandle.prototype.getResolvedSchema = function () {
  6616. var _this = this;
  6617. if (!this.resolvedSchema) {
  6618. this.resolvedSchema = this.getUnresolvedSchema().then(function (unresolved) {
  6619. return _this.service.resolveSchemaContent(unresolved, _this.url, _this.dependencies);
  6620. });
  6621. }
  6622. return this.resolvedSchema;
  6623. };
  6624. SchemaHandle.prototype.clearSchema = function () {
  6625. this.resolvedSchema = null;
  6626. this.unresolvedSchema = null;
  6627. this.dependencies = {};
  6628. };
  6629. return SchemaHandle;
  6630. }());
  6631. var UnresolvedSchema = /** @class */ (function () {
  6632. function UnresolvedSchema(schema, errors) {
  6633. if (errors === void 0) { errors = []; }
  6634. this.schema = schema;
  6635. this.errors = errors;
  6636. }
  6637. return UnresolvedSchema;
  6638. }());
  6639. exports.UnresolvedSchema = UnresolvedSchema;
  6640. var ResolvedSchema = /** @class */ (function () {
  6641. function ResolvedSchema(schema, errors) {
  6642. if (errors === void 0) { errors = []; }
  6643. this.schema = schema;
  6644. this.errors = errors;
  6645. }
  6646. ResolvedSchema.prototype.getSection = function (path) {
  6647. return Parser.asSchema(this.getSectionRecursive(path, this.schema));
  6648. };
  6649. ResolvedSchema.prototype.getSectionRecursive = function (path, schema) {
  6650. if (!schema || typeof schema === 'boolean' || path.length === 0) {
  6651. return schema;
  6652. }
  6653. var next = path.shift();
  6654. if (schema.properties && typeof schema.properties[next]) {
  6655. return this.getSectionRecursive(path, schema.properties[next]);
  6656. }
  6657. else if (schema.patternProperties) {
  6658. for (var _i = 0, _a = Object.keys(schema.patternProperties); _i < _a.length; _i++) {
  6659. var pattern = _a[_i];
  6660. var regex = new RegExp(pattern);
  6661. if (regex.test(next)) {
  6662. return this.getSectionRecursive(path, schema.patternProperties[pattern]);
  6663. }
  6664. }
  6665. }
  6666. else if (typeof schema.additionalProperties === 'object') {
  6667. return this.getSectionRecursive(path, schema.additionalProperties);
  6668. }
  6669. else if (next.match('[0-9]+')) {
  6670. if (Array.isArray(schema.items)) {
  6671. var index = parseInt(next, 10);
  6672. if (!isNaN(index) && schema.items[index]) {
  6673. return this.getSectionRecursive(path, schema.items[index]);
  6674. }
  6675. }
  6676. else if (schema.items) {
  6677. return this.getSectionRecursive(path, schema.items);
  6678. }
  6679. }
  6680. return null;
  6681. };
  6682. return ResolvedSchema;
  6683. }());
  6684. exports.ResolvedSchema = ResolvedSchema;
  6685. var JSONSchemaService = /** @class */ (function () {
  6686. function JSONSchemaService(requestService, contextService, promiseConstructor) {
  6687. this.contextService = contextService;
  6688. this.requestService = requestService;
  6689. this.promiseConstructor = promiseConstructor || Promise;
  6690. this.callOnDispose = [];
  6691. this.contributionSchemas = {};
  6692. this.contributionAssociations = {};
  6693. this.schemasById = {};
  6694. this.filePatternAssociations = [];
  6695. this.filePatternAssociationById = {};
  6696. this.registeredSchemasIds = {};
  6697. }
  6698. JSONSchemaService.prototype.getRegisteredSchemaIds = function (filter) {
  6699. return Object.keys(this.registeredSchemasIds).filter(function (id) {
  6700. var scheme = vscode_uri_1.URI.parse(id).scheme;
  6701. return scheme !== 'schemaservice' && (!filter || filter(scheme));
  6702. });
  6703. };
  6704. Object.defineProperty(JSONSchemaService.prototype, "promise", {
  6705. get: function () {
  6706. return this.promiseConstructor;
  6707. },
  6708. enumerable: true,
  6709. configurable: true
  6710. });
  6711. JSONSchemaService.prototype.dispose = function () {
  6712. while (this.callOnDispose.length > 0) {
  6713. this.callOnDispose.pop()();
  6714. }
  6715. };
  6716. JSONSchemaService.prototype.onResourceChange = function (uri) {
  6717. var _this = this;
  6718. var hasChanges = false;
  6719. uri = this.normalizeId(uri);
  6720. var toWalk = [uri];
  6721. var all = Object.keys(this.schemasById).map(function (key) { return _this.schemasById[key]; });
  6722. while (toWalk.length) {
  6723. var curr = toWalk.pop();
  6724. for (var i = 0; i < all.length; i++) {
  6725. var handle = all[i];
  6726. if (handle && (handle.url === curr || handle.dependencies[curr])) {
  6727. if (handle.url !== curr) {
  6728. toWalk.push(handle.url);
  6729. }
  6730. handle.clearSchema();
  6731. all[i] = undefined;
  6732. hasChanges = true;
  6733. }
  6734. }
  6735. }
  6736. return hasChanges;
  6737. };
  6738. JSONSchemaService.prototype.normalizeId = function (id) {
  6739. // remove trailing '#', normalize drive capitalization
  6740. try {
  6741. return vscode_uri_1.URI.parse(id).toString();
  6742. }
  6743. catch (e) {
  6744. return id;
  6745. }
  6746. };
  6747. JSONSchemaService.prototype.setSchemaContributions = function (schemaContributions) {
  6748. if (schemaContributions.schemas) {
  6749. var schemas = schemaContributions.schemas;
  6750. for (var id in schemas) {
  6751. var normalizedId = this.normalizeId(id);
  6752. this.contributionSchemas[normalizedId] = this.addSchemaHandle(normalizedId, schemas[id]);
  6753. }
  6754. }
  6755. if (schemaContributions.schemaAssociations) {
  6756. var schemaAssociations = schemaContributions.schemaAssociations;
  6757. for (var pattern in schemaAssociations) {
  6758. var associations = schemaAssociations[pattern];
  6759. this.contributionAssociations[pattern] = associations;
  6760. var fpa = this.getOrAddFilePatternAssociation(pattern);
  6761. for (var _i = 0, associations_1 = associations; _i < associations_1.length; _i++) {
  6762. var schemaId = associations_1[_i];
  6763. var id = this.normalizeId(schemaId);
  6764. fpa.addSchema(id);
  6765. }
  6766. }
  6767. }
  6768. };
  6769. JSONSchemaService.prototype.addSchemaHandle = function (id, unresolvedSchemaContent) {
  6770. var schemaHandle = new SchemaHandle(this, id, unresolvedSchemaContent);
  6771. this.schemasById[id] = schemaHandle;
  6772. return schemaHandle;
  6773. };
  6774. JSONSchemaService.prototype.getOrAddSchemaHandle = function (id, unresolvedSchemaContent) {
  6775. return this.schemasById[id] || this.addSchemaHandle(id, unresolvedSchemaContent);
  6776. };
  6777. JSONSchemaService.prototype.getOrAddFilePatternAssociation = function (pattern) {
  6778. var fpa = this.filePatternAssociationById[pattern];
  6779. if (!fpa) {
  6780. fpa = new FilePatternAssociation(pattern);
  6781. this.filePatternAssociationById[pattern] = fpa;
  6782. this.filePatternAssociations.push(fpa);
  6783. }
  6784. return fpa;
  6785. };
  6786. JSONSchemaService.prototype.registerExternalSchema = function (uri, filePatterns, unresolvedSchemaContent) {
  6787. if (filePatterns === void 0) { filePatterns = null; }
  6788. var id = this.normalizeId(uri);
  6789. this.registeredSchemasIds[id] = true;
  6790. if (filePatterns) {
  6791. for (var _i = 0, filePatterns_1 = filePatterns; _i < filePatterns_1.length; _i++) {
  6792. var pattern = filePatterns_1[_i];
  6793. this.getOrAddFilePatternAssociation(pattern).addSchema(id);
  6794. }
  6795. }
  6796. return unresolvedSchemaContent ? this.addSchemaHandle(id, unresolvedSchemaContent) : this.getOrAddSchemaHandle(id);
  6797. };
  6798. JSONSchemaService.prototype.clearExternalSchemas = function () {
  6799. this.schemasById = {};
  6800. this.filePatternAssociations = [];
  6801. this.filePatternAssociationById = {};
  6802. this.registeredSchemasIds = {};
  6803. for (var id in this.contributionSchemas) {
  6804. this.schemasById[id] = this.contributionSchemas[id];
  6805. this.registeredSchemasIds[id] = true;
  6806. }
  6807. for (var pattern in this.contributionAssociations) {
  6808. var fpa = this.getOrAddFilePatternAssociation(pattern);
  6809. for (var _i = 0, _a = this.contributionAssociations[pattern]; _i < _a.length; _i++) {
  6810. var schemaId = _a[_i];
  6811. var id = this.normalizeId(schemaId);
  6812. fpa.addSchema(id);
  6813. }
  6814. }
  6815. };
  6816. JSONSchemaService.prototype.getResolvedSchema = function (schemaId) {
  6817. var id = this.normalizeId(schemaId);
  6818. var schemaHandle = this.schemasById[id];
  6819. if (schemaHandle) {
  6820. return schemaHandle.getResolvedSchema();
  6821. }
  6822. return this.promise.resolve(null);
  6823. };
  6824. JSONSchemaService.prototype.loadSchema = function (url) {
  6825. if (!this.requestService) {
  6826. var errorMessage = localize('json.schema.norequestservice', 'Unable to load schema from \'{0}\'. No schema request service available', toDisplayString(url));
  6827. return this.promise.resolve(new UnresolvedSchema({}, [errorMessage]));
  6828. }
  6829. return this.requestService(url).then(function (content) {
  6830. if (!content) {
  6831. var errorMessage = localize('json.schema.nocontent', 'Unable to load schema from \'{0}\': No content.', toDisplayString(url));
  6832. return new UnresolvedSchema({}, [errorMessage]);
  6833. }
  6834. var schemaContent = {};
  6835. var jsonErrors = [];
  6836. schemaContent = Json.parse(content, jsonErrors);
  6837. var errors = jsonErrors.length ? [localize('json.schema.invalidFormat', 'Unable to parse content from \'{0}\': Parse error at offset {1}.', toDisplayString(url), jsonErrors[0].offset)] : [];
  6838. return new UnresolvedSchema(schemaContent, errors);
  6839. }, function (error) {
  6840. var errorMessage = error.toString();
  6841. var errorSplit = error.toString().split('Error: ');
  6842. if (errorSplit.length > 1) {
  6843. // more concise error message, URL and context are attached by caller anyways
  6844. errorMessage = errorSplit[1];
  6845. }
  6846. if (Strings.endsWith(errorMessage, '.')) {
  6847. errorMessage = errorMessage.substr(0, errorMessage.length - 1);
  6848. }
  6849. return new UnresolvedSchema({}, [localize('json.schema.nocontent', 'Unable to load schema from \'{0}\': {1}.', toDisplayString(url), errorMessage)]);
  6850. });
  6851. };
  6852. JSONSchemaService.prototype.resolveSchemaContent = function (schemaToResolve, schemaURL, dependencies) {
  6853. var _this = this;
  6854. var resolveErrors = schemaToResolve.errors.slice(0);
  6855. var schema = schemaToResolve.schema;
  6856. if (schema.$schema) {
  6857. var id = this.normalizeId(schema.$schema);
  6858. if (id === 'http://json-schema.org/draft-03/schema') {
  6859. return this.promise.resolve(new ResolvedSchema({}, [localize('json.schema.draft03.notsupported', "Draft-03 schemas are not supported.")]));
  6860. }
  6861. else if (id === 'https://json-schema.org/draft/2019-09/schema') {
  6862. schemaToResolve.errors.push(localize('json.schema.draft201909.notsupported', "Draft 2019-09 schemas are not yet fully supported."));
  6863. }
  6864. }
  6865. var contextService = this.contextService;
  6866. var findSection = function (schema, path) {
  6867. if (!path) {
  6868. return schema;
  6869. }
  6870. var current = schema;
  6871. if (path[0] === '/') {
  6872. path = path.substr(1);
  6873. }
  6874. path.split('/').some(function (part) {
  6875. current = current[part];
  6876. return !current;
  6877. });
  6878. return current;
  6879. };
  6880. var merge = function (target, sourceRoot, sourceURI, path) {
  6881. var section = findSection(sourceRoot, path);
  6882. if (section) {
  6883. for (var key in section) {
  6884. if (section.hasOwnProperty(key) && !target.hasOwnProperty(key)) {
  6885. target[key] = section[key];
  6886. }
  6887. }
  6888. }
  6889. else {
  6890. resolveErrors.push(localize('json.schema.invalidref', '$ref \'{0}\' in \'{1}\' can not be resolved.', path, sourceURI));
  6891. }
  6892. };
  6893. var resolveExternalLink = function (node, uri, linkPath, parentSchemaURL, parentSchemaDependencies) {
  6894. if (contextService && !/^\w+:\/\/.*/.test(uri)) {
  6895. uri = contextService.resolveRelativePath(uri, parentSchemaURL);
  6896. }
  6897. uri = _this.normalizeId(uri);
  6898. var referencedHandle = _this.getOrAddSchemaHandle(uri);
  6899. return referencedHandle.getUnresolvedSchema().then(function (unresolvedSchema) {
  6900. parentSchemaDependencies[uri] = true;
  6901. if (unresolvedSchema.errors.length) {
  6902. var loc = linkPath ? uri + '#' + linkPath : uri;
  6903. resolveErrors.push(localize('json.schema.problemloadingref', 'Problems loading reference \'{0}\': {1}', loc, unresolvedSchema.errors[0]));
  6904. }
  6905. merge(node, unresolvedSchema.schema, uri, linkPath);
  6906. return resolveRefs(node, unresolvedSchema.schema, uri, referencedHandle.dependencies);
  6907. });
  6908. };
  6909. var resolveRefs = function (node, parentSchema, parentSchemaURL, parentSchemaDependencies) {
  6910. if (!node || typeof node !== 'object') {
  6911. return Promise.resolve(null);
  6912. }
  6913. var toWalk = [node];
  6914. var seen = [];
  6915. var openPromises = [];
  6916. var collectEntries = function () {
  6917. var entries = [];
  6918. for (var _i = 0; _i < arguments.length; _i++) {
  6919. entries[_i] = arguments[_i];
  6920. }
  6921. for (var _a = 0, entries_1 = entries; _a < entries_1.length; _a++) {
  6922. var entry = entries_1[_a];
  6923. if (typeof entry === 'object') {
  6924. toWalk.push(entry);
  6925. }
  6926. }
  6927. };
  6928. var collectMapEntries = function () {
  6929. var maps = [];
  6930. for (var _i = 0; _i < arguments.length; _i++) {
  6931. maps[_i] = arguments[_i];
  6932. }
  6933. for (var _a = 0, maps_1 = maps; _a < maps_1.length; _a++) {
  6934. var map = maps_1[_a];
  6935. if (typeof map === 'object') {
  6936. for (var key in map) {
  6937. var entry = map[key];
  6938. if (typeof entry === 'object') {
  6939. toWalk.push(entry);
  6940. }
  6941. }
  6942. }
  6943. }
  6944. };
  6945. var collectArrayEntries = function () {
  6946. var arrays = [];
  6947. for (var _i = 0; _i < arguments.length; _i++) {
  6948. arrays[_i] = arguments[_i];
  6949. }
  6950. for (var _a = 0, arrays_1 = arrays; _a < arrays_1.length; _a++) {
  6951. var array = arrays_1[_a];
  6952. if (Array.isArray(array)) {
  6953. for (var _b = 0, array_1 = array; _b < array_1.length; _b++) {
  6954. var entry = array_1[_b];
  6955. if (typeof entry === 'object') {
  6956. toWalk.push(entry);
  6957. }
  6958. }
  6959. }
  6960. }
  6961. };
  6962. var handleRef = function (next) {
  6963. var seenRefs = [];
  6964. while (next.$ref) {
  6965. var ref = next.$ref;
  6966. var segments = ref.split('#', 2);
  6967. delete next.$ref;
  6968. if (segments[0].length > 0) {
  6969. openPromises.push(resolveExternalLink(next, segments[0], segments[1], parentSchemaURL, parentSchemaDependencies));
  6970. return;
  6971. }
  6972. else {
  6973. if (seenRefs.indexOf(ref) === -1) {
  6974. merge(next, parentSchema, parentSchemaURL, segments[1]); // can set next.$ref again, use seenRefs to avoid circle
  6975. seenRefs.push(ref);
  6976. }
  6977. }
  6978. }
  6979. collectEntries(next.items, next.additionalProperties, next.not, next.contains, next.propertyNames, next.if, next.then, next.else);
  6980. collectMapEntries(next.definitions, next.properties, next.patternProperties, next.dependencies);
  6981. collectArrayEntries(next.anyOf, next.allOf, next.oneOf, next.items);
  6982. };
  6983. while (toWalk.length) {
  6984. var next = toWalk.pop();
  6985. if (seen.indexOf(next) >= 0) {
  6986. continue;
  6987. }
  6988. seen.push(next);
  6989. handleRef(next);
  6990. }
  6991. return _this.promise.all(openPromises);
  6992. };
  6993. return resolveRefs(schema, schema, schemaURL, dependencies).then(function (_) { return new ResolvedSchema(schema, resolveErrors); });
  6994. };
  6995. JSONSchemaService.prototype.getSchemaForResource = function (resource, document) {
  6996. // first use $schema if present
  6997. if (document && document.root && document.root.type === 'object') {
  6998. var schemaProperties = document.root.properties.filter(function (p) { return (p.keyNode.value === '$schema') && p.valueNode && p.valueNode.type === 'string'; });
  6999. if (schemaProperties.length > 0) {
  7000. var schemeId = Parser.getNodeValue(schemaProperties[0].valueNode);
  7001. if (schemeId && Strings.startsWith(schemeId, '.') && this.contextService) {
  7002. schemeId = this.contextService.resolveRelativePath(schemeId, resource);
  7003. }
  7004. if (schemeId) {
  7005. var id = this.normalizeId(schemeId);
  7006. return this.getOrAddSchemaHandle(id).getResolvedSchema();
  7007. }
  7008. }
  7009. }
  7010. var seen = Object.create(null);
  7011. var schemas = [];
  7012. for (var _i = 0, _a = this.filePatternAssociations; _i < _a.length; _i++) {
  7013. var entry = _a[_i];
  7014. if (entry.matchesPattern(resource)) {
  7015. for (var _b = 0, _c = entry.getSchemas(); _b < _c.length; _b++) {
  7016. var schemaId = _c[_b];
  7017. if (!seen[schemaId]) {
  7018. schemas.push(schemaId);
  7019. seen[schemaId] = true;
  7020. }
  7021. }
  7022. }
  7023. }
  7024. if (schemas.length > 0) {
  7025. return this.createCombinedSchema(resource, schemas).getResolvedSchema();
  7026. }
  7027. return this.promise.resolve(null);
  7028. };
  7029. JSONSchemaService.prototype.createCombinedSchema = function (resource, schemaIds) {
  7030. if (schemaIds.length === 1) {
  7031. return this.getOrAddSchemaHandle(schemaIds[0]);
  7032. }
  7033. else {
  7034. var combinedSchemaId = 'schemaservice://combinedSchema/' + encodeURIComponent(resource);
  7035. var combinedSchema = {
  7036. allOf: schemaIds.map(function (schemaId) { return ({ $ref: schemaId }); })
  7037. };
  7038. return this.addSchemaHandle(combinedSchemaId, combinedSchema);
  7039. }
  7040. };
  7041. return JSONSchemaService;
  7042. }());
  7043. exports.JSONSchemaService = JSONSchemaService;
  7044. function toDisplayString(url) {
  7045. try {
  7046. var uri = vscode_uri_1.URI.parse(url);
  7047. if (uri.scheme === 'file') {
  7048. return uri.fsPath;
  7049. }
  7050. }
  7051. catch (e) {
  7052. // ignore
  7053. }
  7054. return url;
  7055. }
  7056. });
  7057. /*---------------------------------------------------------------------------------------------
  7058. * Copyright (c) Microsoft Corporation. All rights reserved.
  7059. * Licensed under the MIT License. See License.txt in the project root for license information.
  7060. *--------------------------------------------------------------------------------------------*/
  7061. (function (factory) {
  7062. if (typeof module === "object" && typeof module.exports === "object") {
  7063. var v = factory(require, exports);
  7064. if (v !== undefined) module.exports = v;
  7065. }
  7066. else if (typeof define === "function" && define.amd) {
  7067. define('vscode-json-languageservice/services/jsonValidation',["require", "exports", "./jsonSchemaService", "../jsonLanguageTypes", "vscode-nls", "../utils/objects"], factory);
  7068. }
  7069. })(function (require, exports) {
  7070. "use strict";
  7071. Object.defineProperty(exports, "__esModule", { value: true });
  7072. var jsonSchemaService_1 = require("./jsonSchemaService");
  7073. var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
  7074. var nls = require("vscode-nls");
  7075. var objects_1 = require("../utils/objects");
  7076. var localize = nls.loadMessageBundle();
  7077. var JSONValidation = /** @class */ (function () {
  7078. function JSONValidation(jsonSchemaService, promiseConstructor) {
  7079. this.jsonSchemaService = jsonSchemaService;
  7080. this.promise = promiseConstructor;
  7081. this.validationEnabled = true;
  7082. }
  7083. JSONValidation.prototype.configure = function (raw) {
  7084. if (raw) {
  7085. this.validationEnabled = raw.validate;
  7086. this.commentSeverity = raw.allowComments ? void 0 : jsonLanguageTypes_1.DiagnosticSeverity.Error;
  7087. }
  7088. };
  7089. JSONValidation.prototype.doValidation = function (textDocument, jsonDocument, documentSettings, schema) {
  7090. var _this = this;
  7091. if (!this.validationEnabled) {
  7092. return this.promise.resolve([]);
  7093. }
  7094. var diagnostics = [];
  7095. var added = {};
  7096. var addProblem = function (problem) {
  7097. // remove duplicated messages
  7098. var signature = problem.range.start.line + ' ' + problem.range.start.character + ' ' + problem.message;
  7099. if (!added[signature]) {
  7100. added[signature] = true;
  7101. diagnostics.push(problem);
  7102. }
  7103. };
  7104. var getDiagnostics = function (schema) {
  7105. var trailingCommaSeverity = documentSettings ? toDiagnosticSeverity(documentSettings.trailingCommas) : jsonLanguageTypes_1.DiagnosticSeverity.Error;
  7106. var commentSeverity = documentSettings ? toDiagnosticSeverity(documentSettings.comments) : _this.commentSeverity;
  7107. if (schema) {
  7108. if (schema.errors.length && jsonDocument.root) {
  7109. var astRoot = jsonDocument.root;
  7110. var property = astRoot.type === 'object' ? astRoot.properties[0] : null;
  7111. if (property && property.keyNode.value === '$schema') {
  7112. var node = property.valueNode || property;
  7113. var range = jsonLanguageTypes_1.Range.create(textDocument.positionAt(node.offset), textDocument.positionAt(node.offset + node.length));
  7114. addProblem(jsonLanguageTypes_1.Diagnostic.create(range, schema.errors[0], jsonLanguageTypes_1.DiagnosticSeverity.Warning, jsonLanguageTypes_1.ErrorCode.SchemaResolveError));
  7115. }
  7116. else {
  7117. var range = jsonLanguageTypes_1.Range.create(textDocument.positionAt(astRoot.offset), textDocument.positionAt(astRoot.offset + 1));
  7118. addProblem(jsonLanguageTypes_1.Diagnostic.create(range, schema.errors[0], jsonLanguageTypes_1.DiagnosticSeverity.Warning, jsonLanguageTypes_1.ErrorCode.SchemaResolveError));
  7119. }
  7120. }
  7121. else {
  7122. var semanticErrors = jsonDocument.validate(textDocument, schema.schema);
  7123. if (semanticErrors) {
  7124. semanticErrors.forEach(addProblem);
  7125. }
  7126. }
  7127. if (schemaAllowsComments(schema.schema)) {
  7128. commentSeverity = void 0;
  7129. }
  7130. if (schemaAllowsTrailingCommas(schema.schema)) {
  7131. trailingCommaSeverity = void 0;
  7132. }
  7133. }
  7134. for (var _i = 0, _a = jsonDocument.syntaxErrors; _i < _a.length; _i++) {
  7135. var p = _a[_i];
  7136. if (p.code === jsonLanguageTypes_1.ErrorCode.TrailingComma) {
  7137. if (typeof trailingCommaSeverity !== 'number') {
  7138. continue;
  7139. }
  7140. p.severity = trailingCommaSeverity;
  7141. }
  7142. addProblem(p);
  7143. }
  7144. if (typeof commentSeverity === 'number') {
  7145. var message_1 = localize('InvalidCommentToken', 'Comments are not permitted in JSON.');
  7146. jsonDocument.comments.forEach(function (c) {
  7147. addProblem(jsonLanguageTypes_1.Diagnostic.create(c, message_1, commentSeverity, jsonLanguageTypes_1.ErrorCode.CommentNotPermitted));
  7148. });
  7149. }
  7150. return diagnostics;
  7151. };
  7152. if (schema) {
  7153. var id = schema.id || ('schemaservice://untitled/' + idCounter++);
  7154. return this.jsonSchemaService.resolveSchemaContent(new jsonSchemaService_1.UnresolvedSchema(schema), id, {}).then(function (resolvedSchema) {
  7155. return getDiagnostics(resolvedSchema);
  7156. });
  7157. }
  7158. return this.jsonSchemaService.getSchemaForResource(textDocument.uri, jsonDocument).then(function (schema) {
  7159. return getDiagnostics(schema);
  7160. });
  7161. };
  7162. return JSONValidation;
  7163. }());
  7164. exports.JSONValidation = JSONValidation;
  7165. var idCounter = 0;
  7166. function schemaAllowsComments(schemaRef) {
  7167. if (schemaRef && typeof schemaRef === 'object') {
  7168. if (objects_1.isBoolean(schemaRef.allowComments)) {
  7169. return schemaRef.allowComments;
  7170. }
  7171. if (schemaRef.allOf) {
  7172. for (var _i = 0, _a = schemaRef.allOf; _i < _a.length; _i++) {
  7173. var schema = _a[_i];
  7174. var allow = schemaAllowsComments(schema);
  7175. if (objects_1.isBoolean(allow)) {
  7176. return allow;
  7177. }
  7178. }
  7179. }
  7180. }
  7181. return undefined;
  7182. }
  7183. function schemaAllowsTrailingCommas(schemaRef) {
  7184. if (schemaRef && typeof schemaRef === 'object') {
  7185. if (objects_1.isBoolean(schemaRef.allowTrailingCommas)) {
  7186. return schemaRef.allowTrailingCommas;
  7187. }
  7188. if (objects_1.isBoolean(schemaRef['allowsTrailingCommas'])) { // deprecated
  7189. return schemaRef['allowsTrailingCommas'];
  7190. }
  7191. if (schemaRef.allOf) {
  7192. for (var _i = 0, _a = schemaRef.allOf; _i < _a.length; _i++) {
  7193. var schema = _a[_i];
  7194. var allow = schemaAllowsTrailingCommas(schema);
  7195. if (objects_1.isBoolean(allow)) {
  7196. return allow;
  7197. }
  7198. }
  7199. }
  7200. }
  7201. return undefined;
  7202. }
  7203. function toDiagnosticSeverity(severityLevel) {
  7204. switch (severityLevel) {
  7205. case 'error': return jsonLanguageTypes_1.DiagnosticSeverity.Error;
  7206. case 'warning': return jsonLanguageTypes_1.DiagnosticSeverity.Warning;
  7207. case 'ignore': return void 0;
  7208. }
  7209. return void 0;
  7210. }
  7211. });
  7212. /*---------------------------------------------------------------------------------------------
  7213. * Copyright (c) Microsoft Corporation. All rights reserved.
  7214. * Licensed under the MIT License. See License.txt in the project root for license information.
  7215. *--------------------------------------------------------------------------------------------*/
  7216. (function (factory) {
  7217. if (typeof module === "object" && typeof module.exports === "object") {
  7218. var v = factory(require, exports);
  7219. if (v !== undefined) module.exports = v;
  7220. }
  7221. else if (typeof define === "function" && define.amd) {
  7222. define('vscode-json-languageservice/utils/colors',["require", "exports"], factory);
  7223. }
  7224. })(function (require, exports) {
  7225. "use strict";
  7226. Object.defineProperty(exports, "__esModule", { value: true });
  7227. var Digit0 = 48;
  7228. var Digit9 = 57;
  7229. var A = 65;
  7230. var a = 97;
  7231. var f = 102;
  7232. function hexDigit(charCode) {
  7233. if (charCode < Digit0) {
  7234. return 0;
  7235. }
  7236. if (charCode <= Digit9) {
  7237. return charCode - Digit0;
  7238. }
  7239. if (charCode < a) {
  7240. charCode += (a - A);
  7241. }
  7242. if (charCode >= a && charCode <= f) {
  7243. return charCode - a + 10;
  7244. }
  7245. return 0;
  7246. }
  7247. exports.hexDigit = hexDigit;
  7248. function colorFromHex(text) {
  7249. if (text[0] !== '#') {
  7250. return null;
  7251. }
  7252. switch (text.length) {
  7253. case 4:
  7254. return {
  7255. red: (hexDigit(text.charCodeAt(1)) * 0x11) / 255.0,
  7256. green: (hexDigit(text.charCodeAt(2)) * 0x11) / 255.0,
  7257. blue: (hexDigit(text.charCodeAt(3)) * 0x11) / 255.0,
  7258. alpha: 1
  7259. };
  7260. case 5:
  7261. return {
  7262. red: (hexDigit(text.charCodeAt(1)) * 0x11) / 255.0,
  7263. green: (hexDigit(text.charCodeAt(2)) * 0x11) / 255.0,
  7264. blue: (hexDigit(text.charCodeAt(3)) * 0x11) / 255.0,
  7265. alpha: (hexDigit(text.charCodeAt(4)) * 0x11) / 255.0,
  7266. };
  7267. case 7:
  7268. return {
  7269. red: (hexDigit(text.charCodeAt(1)) * 0x10 + hexDigit(text.charCodeAt(2))) / 255.0,
  7270. green: (hexDigit(text.charCodeAt(3)) * 0x10 + hexDigit(text.charCodeAt(4))) / 255.0,
  7271. blue: (hexDigit(text.charCodeAt(5)) * 0x10 + hexDigit(text.charCodeAt(6))) / 255.0,
  7272. alpha: 1
  7273. };
  7274. case 9:
  7275. return {
  7276. red: (hexDigit(text.charCodeAt(1)) * 0x10 + hexDigit(text.charCodeAt(2))) / 255.0,
  7277. green: (hexDigit(text.charCodeAt(3)) * 0x10 + hexDigit(text.charCodeAt(4))) / 255.0,
  7278. blue: (hexDigit(text.charCodeAt(5)) * 0x10 + hexDigit(text.charCodeAt(6))) / 255.0,
  7279. alpha: (hexDigit(text.charCodeAt(7)) * 0x10 + hexDigit(text.charCodeAt(8))) / 255.0
  7280. };
  7281. }
  7282. return null;
  7283. }
  7284. exports.colorFromHex = colorFromHex;
  7285. function colorFrom256RGB(red, green, blue, alpha) {
  7286. if (alpha === void 0) { alpha = 1.0; }
  7287. return {
  7288. red: red / 255.0,
  7289. green: green / 255.0,
  7290. blue: blue / 255.0,
  7291. alpha: alpha
  7292. };
  7293. }
  7294. exports.colorFrom256RGB = colorFrom256RGB;
  7295. });
  7296. /*---------------------------------------------------------------------------------------------
  7297. * Copyright (c) Microsoft Corporation. All rights reserved.
  7298. * Licensed under the MIT License. See License.txt in the project root for license information.
  7299. *--------------------------------------------------------------------------------------------*/
  7300. (function (factory) {
  7301. if (typeof module === "object" && typeof module.exports === "object") {
  7302. var v = factory(require, exports);
  7303. if (v !== undefined) module.exports = v;
  7304. }
  7305. else if (typeof define === "function" && define.amd) {
  7306. define('vscode-json-languageservice/services/jsonDocumentSymbols',["require", "exports", "../parser/jsonParser", "../utils/strings", "../utils/colors", "../jsonLanguageTypes"], factory);
  7307. }
  7308. })(function (require, exports) {
  7309. "use strict";
  7310. Object.defineProperty(exports, "__esModule", { value: true });
  7311. var Parser = require("../parser/jsonParser");
  7312. var Strings = require("../utils/strings");
  7313. var colors_1 = require("../utils/colors");
  7314. var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
  7315. var JSONDocumentSymbols = /** @class */ (function () {
  7316. function JSONDocumentSymbols(schemaService) {
  7317. this.schemaService = schemaService;
  7318. }
  7319. JSONDocumentSymbols.prototype.findDocumentSymbols = function (document, doc, context) {
  7320. var _this = this;
  7321. if (context === void 0) { context = { resultLimit: Number.MAX_VALUE }; }
  7322. var root = doc.root;
  7323. if (!root) {
  7324. return null;
  7325. }
  7326. var limit = context.resultLimit;
  7327. // special handling for key bindings
  7328. var resourceString = document.uri;
  7329. if ((resourceString === 'vscode://defaultsettings/keybindings.json') || Strings.endsWith(resourceString.toLowerCase(), '/user/keybindings.json')) {
  7330. if (root.type === 'array') {
  7331. var result_1 = [];
  7332. for (var _i = 0, _a = root.items; _i < _a.length; _i++) {
  7333. var item = _a[_i];
  7334. if (item.type === 'object') {
  7335. for (var _b = 0, _c = item.properties; _b < _c.length; _b++) {
  7336. var property = _c[_b];
  7337. if (property.keyNode.value === 'key' && property.valueNode) {
  7338. var location = jsonLanguageTypes_1.Location.create(document.uri, getRange(document, item));
  7339. result_1.push({ name: Parser.getNodeValue(property.valueNode), kind: jsonLanguageTypes_1.SymbolKind.Function, location: location });
  7340. limit--;
  7341. if (limit <= 0) {
  7342. if (context && context.onResultLimitExceeded) {
  7343. context.onResultLimitExceeded(resourceString);
  7344. }
  7345. return result_1;
  7346. }
  7347. }
  7348. }
  7349. }
  7350. }
  7351. return result_1;
  7352. }
  7353. }
  7354. var toVisit = [
  7355. { node: root, containerName: '' }
  7356. ];
  7357. var nextToVisit = 0;
  7358. var limitExceeded = false;
  7359. var result = [];
  7360. var collectOutlineEntries = function (node, containerName) {
  7361. if (node.type === 'array') {
  7362. node.items.forEach(function (node) {
  7363. if (node) {
  7364. toVisit.push({ node: node, containerName: containerName });
  7365. }
  7366. });
  7367. }
  7368. else if (node.type === 'object') {
  7369. node.properties.forEach(function (property) {
  7370. var valueNode = property.valueNode;
  7371. if (valueNode) {
  7372. if (limit > 0) {
  7373. limit--;
  7374. var location = jsonLanguageTypes_1.Location.create(document.uri, getRange(document, property));
  7375. var childContainerName = containerName ? containerName + '.' + property.keyNode.value : property.keyNode.value;
  7376. result.push({ name: _this.getKeyLabel(property), kind: _this.getSymbolKind(valueNode.type), location: location, containerName: containerName });
  7377. toVisit.push({ node: valueNode, containerName: childContainerName });
  7378. }
  7379. else {
  7380. limitExceeded = true;
  7381. }
  7382. }
  7383. });
  7384. }
  7385. };
  7386. // breath first traversal
  7387. while (nextToVisit < toVisit.length) {
  7388. var next = toVisit[nextToVisit++];
  7389. collectOutlineEntries(next.node, next.containerName);
  7390. }
  7391. if (limitExceeded && context && context.onResultLimitExceeded) {
  7392. context.onResultLimitExceeded(resourceString);
  7393. }
  7394. return result;
  7395. };
  7396. JSONDocumentSymbols.prototype.findDocumentSymbols2 = function (document, doc, context) {
  7397. var _this = this;
  7398. if (context === void 0) { context = { resultLimit: Number.MAX_VALUE }; }
  7399. var root = doc.root;
  7400. if (!root) {
  7401. return null;
  7402. }
  7403. var limit = context.resultLimit;
  7404. // special handling for key bindings
  7405. var resourceString = document.uri;
  7406. if ((resourceString === 'vscode://defaultsettings/keybindings.json') || Strings.endsWith(resourceString.toLowerCase(), '/user/keybindings.json')) {
  7407. if (root.type === 'array') {
  7408. var result_2 = [];
  7409. for (var _i = 0, _a = root.items; _i < _a.length; _i++) {
  7410. var item = _a[_i];
  7411. if (item.type === 'object') {
  7412. for (var _b = 0, _c = item.properties; _b < _c.length; _b++) {
  7413. var property = _c[_b];
  7414. if (property.keyNode.value === 'key' && property.valueNode) {
  7415. var range = getRange(document, item);
  7416. var selectionRange = getRange(document, property.keyNode);
  7417. result_2.push({ name: Parser.getNodeValue(property.valueNode), kind: jsonLanguageTypes_1.SymbolKind.Function, range: range, selectionRange: selectionRange });
  7418. limit--;
  7419. if (limit <= 0) {
  7420. if (context && context.onResultLimitExceeded) {
  7421. context.onResultLimitExceeded(resourceString);
  7422. }
  7423. return result_2;
  7424. }
  7425. }
  7426. }
  7427. }
  7428. }
  7429. return result_2;
  7430. }
  7431. }
  7432. var result = [];
  7433. var toVisit = [
  7434. { node: root, result: result }
  7435. ];
  7436. var nextToVisit = 0;
  7437. var limitExceeded = false;
  7438. var collectOutlineEntries = function (node, result) {
  7439. if (node.type === 'array') {
  7440. node.items.forEach(function (node, index) {
  7441. if (node) {
  7442. if (limit > 0) {
  7443. limit--;
  7444. var range = getRange(document, node);
  7445. var selectionRange = range;
  7446. var name = String(index);
  7447. var symbol = { name: name, kind: _this.getSymbolKind(node.type), range: range, selectionRange: selectionRange, children: [] };
  7448. result.push(symbol);
  7449. toVisit.push({ result: symbol.children, node: node });
  7450. }
  7451. else {
  7452. limitExceeded = true;
  7453. }
  7454. }
  7455. });
  7456. }
  7457. else if (node.type === 'object') {
  7458. node.properties.forEach(function (property) {
  7459. var valueNode = property.valueNode;
  7460. if (valueNode) {
  7461. if (limit > 0) {
  7462. limit--;
  7463. var range = getRange(document, property);
  7464. var selectionRange = getRange(document, property.keyNode);
  7465. var symbol = { name: _this.getKeyLabel(property), kind: _this.getSymbolKind(valueNode.type), range: range, selectionRange: selectionRange, children: [] };
  7466. result.push(symbol);
  7467. toVisit.push({ result: symbol.children, node: valueNode });
  7468. }
  7469. else {
  7470. limitExceeded = true;
  7471. }
  7472. }
  7473. });
  7474. }
  7475. };
  7476. // breath first traversal
  7477. while (nextToVisit < toVisit.length) {
  7478. var next = toVisit[nextToVisit++];
  7479. collectOutlineEntries(next.node, next.result);
  7480. }
  7481. if (limitExceeded && context && context.onResultLimitExceeded) {
  7482. context.onResultLimitExceeded(resourceString);
  7483. }
  7484. return result;
  7485. };
  7486. JSONDocumentSymbols.prototype.getSymbolKind = function (nodeType) {
  7487. switch (nodeType) {
  7488. case 'object':
  7489. return jsonLanguageTypes_1.SymbolKind.Module;
  7490. case 'string':
  7491. return jsonLanguageTypes_1.SymbolKind.String;
  7492. case 'number':
  7493. return jsonLanguageTypes_1.SymbolKind.Number;
  7494. case 'array':
  7495. return jsonLanguageTypes_1.SymbolKind.Array;
  7496. case 'boolean':
  7497. return jsonLanguageTypes_1.SymbolKind.Boolean;
  7498. default: // 'null'
  7499. return jsonLanguageTypes_1.SymbolKind.Variable;
  7500. }
  7501. };
  7502. JSONDocumentSymbols.prototype.getKeyLabel = function (property) {
  7503. var name = property.keyNode.value;
  7504. if (name) {
  7505. name = name.replace(/[\n]/g, '↵');
  7506. }
  7507. if (name && name.trim()) {
  7508. return name;
  7509. }
  7510. return "\"" + name + "\"";
  7511. };
  7512. JSONDocumentSymbols.prototype.findDocumentColors = function (document, doc, context) {
  7513. return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
  7514. var result = [];
  7515. if (schema) {
  7516. var limit = context && typeof context.resultLimit === 'number' ? context.resultLimit : Number.MAX_VALUE;
  7517. var matchingSchemas = doc.getMatchingSchemas(schema.schema);
  7518. var visitedNode = {};
  7519. for (var _i = 0, matchingSchemas_1 = matchingSchemas; _i < matchingSchemas_1.length; _i++) {
  7520. var s = matchingSchemas_1[_i];
  7521. if (!s.inverted && s.schema && (s.schema.format === 'color' || s.schema.format === 'color-hex') && s.node && s.node.type === 'string') {
  7522. var nodeId = String(s.node.offset);
  7523. if (!visitedNode[nodeId]) {
  7524. var color = colors_1.colorFromHex(Parser.getNodeValue(s.node));
  7525. if (color) {
  7526. var range = getRange(document, s.node);
  7527. result.push({ color: color, range: range });
  7528. }
  7529. visitedNode[nodeId] = true;
  7530. limit--;
  7531. if (limit <= 0) {
  7532. if (context && context.onResultLimitExceeded) {
  7533. context.onResultLimitExceeded(document.uri);
  7534. }
  7535. return result;
  7536. }
  7537. }
  7538. }
  7539. }
  7540. }
  7541. return result;
  7542. });
  7543. };
  7544. JSONDocumentSymbols.prototype.getColorPresentations = function (document, doc, color, range) {
  7545. var result = [];
  7546. var red256 = Math.round(color.red * 255), green256 = Math.round(color.green * 255), blue256 = Math.round(color.blue * 255);
  7547. function toTwoDigitHex(n) {
  7548. var r = n.toString(16);
  7549. return r.length !== 2 ? '0' + r : r;
  7550. }
  7551. var label;
  7552. if (color.alpha === 1) {
  7553. label = "#" + toTwoDigitHex(red256) + toTwoDigitHex(green256) + toTwoDigitHex(blue256);
  7554. }
  7555. else {
  7556. label = "#" + toTwoDigitHex(red256) + toTwoDigitHex(green256) + toTwoDigitHex(blue256) + toTwoDigitHex(Math.round(color.alpha * 255));
  7557. }
  7558. result.push({ label: label, textEdit: jsonLanguageTypes_1.TextEdit.replace(range, JSON.stringify(label)) });
  7559. return result;
  7560. };
  7561. return JSONDocumentSymbols;
  7562. }());
  7563. exports.JSONDocumentSymbols = JSONDocumentSymbols;
  7564. function getRange(document, node) {
  7565. return jsonLanguageTypes_1.Range.create(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
  7566. }
  7567. });
  7568. /*---------------------------------------------------------------------------------------------
  7569. * Copyright (c) Microsoft Corporation. All rights reserved.
  7570. * Licensed under the MIT License. See License.txt in the project root for license information.
  7571. *--------------------------------------------------------------------------------------------*/
  7572. (function (factory) {
  7573. if (typeof module === "object" && typeof module.exports === "object") {
  7574. var v = factory(require, exports);
  7575. if (v !== undefined) module.exports = v;
  7576. }
  7577. else if (typeof define === "function" && define.amd) {
  7578. define('vscode-json-languageservice/services/configuration',["require", "exports", "vscode-nls"], factory);
  7579. }
  7580. })(function (require, exports) {
  7581. "use strict";
  7582. Object.defineProperty(exports, "__esModule", { value: true });
  7583. var nls = require("vscode-nls");
  7584. var localize = nls.loadMessageBundle();
  7585. exports.schemaContributions = {
  7586. schemaAssociations: {},
  7587. schemas: {
  7588. // bundle the schema-schema to include (localized) descriptions
  7589. 'http://json-schema.org/draft-04/schema#': {
  7590. 'title': localize('schema.json', 'Describes a JSON file using a schema. See json-schema.org for more info.'),
  7591. '$schema': 'http://json-schema.org/draft-04/schema#',
  7592. 'definitions': {
  7593. 'schemaArray': {
  7594. 'type': 'array',
  7595. 'minItems': 1,
  7596. 'items': {
  7597. '$ref': '#'
  7598. }
  7599. },
  7600. 'positiveInteger': {
  7601. 'type': 'integer',
  7602. 'minimum': 0
  7603. },
  7604. 'positiveIntegerDefault0': {
  7605. 'allOf': [
  7606. {
  7607. '$ref': '#/definitions/positiveInteger'
  7608. },
  7609. {
  7610. 'default': 0
  7611. }
  7612. ]
  7613. },
  7614. 'simpleTypes': {
  7615. 'type': 'string',
  7616. 'enum': [
  7617. 'array',
  7618. 'boolean',
  7619. 'integer',
  7620. 'null',
  7621. 'number',
  7622. 'object',
  7623. 'string'
  7624. ]
  7625. },
  7626. 'stringArray': {
  7627. 'type': 'array',
  7628. 'items': {
  7629. 'type': 'string'
  7630. },
  7631. 'minItems': 1,
  7632. 'uniqueItems': true
  7633. }
  7634. },
  7635. 'type': 'object',
  7636. 'properties': {
  7637. 'id': {
  7638. 'type': 'string',
  7639. 'format': 'uri'
  7640. },
  7641. '$schema': {
  7642. 'type': 'string',
  7643. 'format': 'uri'
  7644. },
  7645. 'title': {
  7646. 'type': 'string'
  7647. },
  7648. 'description': {
  7649. 'type': 'string'
  7650. },
  7651. 'default': {},
  7652. 'multipleOf': {
  7653. 'type': 'number',
  7654. 'minimum': 0,
  7655. 'exclusiveMinimum': true
  7656. },
  7657. 'maximum': {
  7658. 'type': 'number'
  7659. },
  7660. 'exclusiveMaximum': {
  7661. 'type': 'boolean',
  7662. 'default': false
  7663. },
  7664. 'minimum': {
  7665. 'type': 'number'
  7666. },
  7667. 'exclusiveMinimum': {
  7668. 'type': 'boolean',
  7669. 'default': false
  7670. },
  7671. 'maxLength': {
  7672. 'allOf': [
  7673. {
  7674. '$ref': '#/definitions/positiveInteger'
  7675. }
  7676. ]
  7677. },
  7678. 'minLength': {
  7679. 'allOf': [
  7680. {
  7681. '$ref': '#/definitions/positiveIntegerDefault0'
  7682. }
  7683. ]
  7684. },
  7685. 'pattern': {
  7686. 'type': 'string',
  7687. 'format': 'regex'
  7688. },
  7689. 'additionalItems': {
  7690. 'anyOf': [
  7691. {
  7692. 'type': 'boolean'
  7693. },
  7694. {
  7695. '$ref': '#'
  7696. }
  7697. ],
  7698. 'default': {}
  7699. },
  7700. 'items': {
  7701. 'anyOf': [
  7702. {
  7703. '$ref': '#'
  7704. },
  7705. {
  7706. '$ref': '#/definitions/schemaArray'
  7707. }
  7708. ],
  7709. 'default': {}
  7710. },
  7711. 'maxItems': {
  7712. 'allOf': [
  7713. {
  7714. '$ref': '#/definitions/positiveInteger'
  7715. }
  7716. ]
  7717. },
  7718. 'minItems': {
  7719. 'allOf': [
  7720. {
  7721. '$ref': '#/definitions/positiveIntegerDefault0'
  7722. }
  7723. ]
  7724. },
  7725. 'uniqueItems': {
  7726. 'type': 'boolean',
  7727. 'default': false
  7728. },
  7729. 'maxProperties': {
  7730. 'allOf': [
  7731. {
  7732. '$ref': '#/definitions/positiveInteger'
  7733. }
  7734. ]
  7735. },
  7736. 'minProperties': {
  7737. 'allOf': [
  7738. {
  7739. '$ref': '#/definitions/positiveIntegerDefault0'
  7740. }
  7741. ]
  7742. },
  7743. 'required': {
  7744. 'allOf': [
  7745. {
  7746. '$ref': '#/definitions/stringArray'
  7747. }
  7748. ]
  7749. },
  7750. 'additionalProperties': {
  7751. 'anyOf': [
  7752. {
  7753. 'type': 'boolean'
  7754. },
  7755. {
  7756. '$ref': '#'
  7757. }
  7758. ],
  7759. 'default': {}
  7760. },
  7761. 'definitions': {
  7762. 'type': 'object',
  7763. 'additionalProperties': {
  7764. '$ref': '#'
  7765. },
  7766. 'default': {}
  7767. },
  7768. 'properties': {
  7769. 'type': 'object',
  7770. 'additionalProperties': {
  7771. '$ref': '#'
  7772. },
  7773. 'default': {}
  7774. },
  7775. 'patternProperties': {
  7776. 'type': 'object',
  7777. 'additionalProperties': {
  7778. '$ref': '#'
  7779. },
  7780. 'default': {}
  7781. },
  7782. 'dependencies': {
  7783. 'type': 'object',
  7784. 'additionalProperties': {
  7785. 'anyOf': [
  7786. {
  7787. '$ref': '#'
  7788. },
  7789. {
  7790. '$ref': '#/definitions/stringArray'
  7791. }
  7792. ]
  7793. }
  7794. },
  7795. 'enum': {
  7796. 'type': 'array',
  7797. 'minItems': 1,
  7798. 'uniqueItems': true
  7799. },
  7800. 'type': {
  7801. 'anyOf': [
  7802. {
  7803. '$ref': '#/definitions/simpleTypes'
  7804. },
  7805. {
  7806. 'type': 'array',
  7807. 'items': {
  7808. '$ref': '#/definitions/simpleTypes'
  7809. },
  7810. 'minItems': 1,
  7811. 'uniqueItems': true
  7812. }
  7813. ]
  7814. },
  7815. 'format': {
  7816. 'anyOf': [
  7817. {
  7818. 'type': 'string',
  7819. 'enum': [
  7820. 'date-time',
  7821. 'uri',
  7822. 'email',
  7823. 'hostname',
  7824. 'ipv4',
  7825. 'ipv6',
  7826. 'regex'
  7827. ]
  7828. },
  7829. {
  7830. 'type': 'string'
  7831. }
  7832. ]
  7833. },
  7834. 'allOf': {
  7835. 'allOf': [
  7836. {
  7837. '$ref': '#/definitions/schemaArray'
  7838. }
  7839. ]
  7840. },
  7841. 'anyOf': {
  7842. 'allOf': [
  7843. {
  7844. '$ref': '#/definitions/schemaArray'
  7845. }
  7846. ]
  7847. },
  7848. 'oneOf': {
  7849. 'allOf': [
  7850. {
  7851. '$ref': '#/definitions/schemaArray'
  7852. }
  7853. ]
  7854. },
  7855. 'not': {
  7856. 'allOf': [
  7857. {
  7858. '$ref': '#'
  7859. }
  7860. ]
  7861. }
  7862. },
  7863. 'dependencies': {
  7864. 'exclusiveMaximum': [
  7865. 'maximum'
  7866. ],
  7867. 'exclusiveMinimum': [
  7868. 'minimum'
  7869. ]
  7870. },
  7871. 'default': {}
  7872. },
  7873. 'http://json-schema.org/draft-07/schema#': {
  7874. 'title': localize('schema.json', 'Describes a JSON file using a schema. See json-schema.org for more info.'),
  7875. 'definitions': {
  7876. 'schemaArray': {
  7877. 'type': 'array',
  7878. 'minItems': 1,
  7879. 'items': { '$ref': '#' }
  7880. },
  7881. 'nonNegativeInteger': {
  7882. 'type': 'integer',
  7883. 'minimum': 0
  7884. },
  7885. 'nonNegativeIntegerDefault0': {
  7886. 'allOf': [
  7887. { '$ref': '#/definitions/nonNegativeInteger' },
  7888. { 'default': 0 }
  7889. ]
  7890. },
  7891. 'simpleTypes': {
  7892. 'enum': [
  7893. 'array',
  7894. 'boolean',
  7895. 'integer',
  7896. 'null',
  7897. 'number',
  7898. 'object',
  7899. 'string'
  7900. ]
  7901. },
  7902. 'stringArray': {
  7903. 'type': 'array',
  7904. 'items': { 'type': 'string' },
  7905. 'uniqueItems': true,
  7906. 'default': []
  7907. }
  7908. },
  7909. 'type': ['object', 'boolean'],
  7910. 'properties': {
  7911. '$id': {
  7912. 'type': 'string',
  7913. 'format': 'uri-reference'
  7914. },
  7915. '$schema': {
  7916. 'type': 'string',
  7917. 'format': 'uri'
  7918. },
  7919. '$ref': {
  7920. 'type': 'string',
  7921. 'format': 'uri-reference'
  7922. },
  7923. '$comment': {
  7924. 'type': 'string'
  7925. },
  7926. 'title': {
  7927. 'type': 'string'
  7928. },
  7929. 'description': {
  7930. 'type': 'string'
  7931. },
  7932. 'default': true,
  7933. 'readOnly': {
  7934. 'type': 'boolean',
  7935. 'default': false
  7936. },
  7937. 'examples': {
  7938. 'type': 'array',
  7939. 'items': true
  7940. },
  7941. 'multipleOf': {
  7942. 'type': 'number',
  7943. 'exclusiveMinimum': 0
  7944. },
  7945. 'maximum': {
  7946. 'type': 'number'
  7947. },
  7948. 'exclusiveMaximum': {
  7949. 'type': 'number'
  7950. },
  7951. 'minimum': {
  7952. 'type': 'number'
  7953. },
  7954. 'exclusiveMinimum': {
  7955. 'type': 'number'
  7956. },
  7957. 'maxLength': { '$ref': '#/definitions/nonNegativeInteger' },
  7958. 'minLength': { '$ref': '#/definitions/nonNegativeIntegerDefault0' },
  7959. 'pattern': {
  7960. 'type': 'string',
  7961. 'format': 'regex'
  7962. },
  7963. 'additionalItems': { '$ref': '#' },
  7964. 'items': {
  7965. 'anyOf': [
  7966. { '$ref': '#' },
  7967. { '$ref': '#/definitions/schemaArray' }
  7968. ],
  7969. 'default': true
  7970. },
  7971. 'maxItems': { '$ref': '#/definitions/nonNegativeInteger' },
  7972. 'minItems': { '$ref': '#/definitions/nonNegativeIntegerDefault0' },
  7973. 'uniqueItems': {
  7974. 'type': 'boolean',
  7975. 'default': false
  7976. },
  7977. 'contains': { '$ref': '#' },
  7978. 'maxProperties': { '$ref': '#/definitions/nonNegativeInteger' },
  7979. 'minProperties': { '$ref': '#/definitions/nonNegativeIntegerDefault0' },
  7980. 'required': { '$ref': '#/definitions/stringArray' },
  7981. 'additionalProperties': { '$ref': '#' },
  7982. 'definitions': {
  7983. 'type': 'object',
  7984. 'additionalProperties': { '$ref': '#' },
  7985. 'default': {}
  7986. },
  7987. 'properties': {
  7988. 'type': 'object',
  7989. 'additionalProperties': { '$ref': '#' },
  7990. 'default': {}
  7991. },
  7992. 'patternProperties': {
  7993. 'type': 'object',
  7994. 'additionalProperties': { '$ref': '#' },
  7995. 'propertyNames': { 'format': 'regex' },
  7996. 'default': {}
  7997. },
  7998. 'dependencies': {
  7999. 'type': 'object',
  8000. 'additionalProperties': {
  8001. 'anyOf': [
  8002. { '$ref': '#' },
  8003. { '$ref': '#/definitions/stringArray' }
  8004. ]
  8005. }
  8006. },
  8007. 'propertyNames': { '$ref': '#' },
  8008. 'const': true,
  8009. 'enum': {
  8010. 'type': 'array',
  8011. 'items': true,
  8012. 'minItems': 1,
  8013. 'uniqueItems': true
  8014. },
  8015. 'type': {
  8016. 'anyOf': [
  8017. { '$ref': '#/definitions/simpleTypes' },
  8018. {
  8019. 'type': 'array',
  8020. 'items': { '$ref': '#/definitions/simpleTypes' },
  8021. 'minItems': 1,
  8022. 'uniqueItems': true
  8023. }
  8024. ]
  8025. },
  8026. 'format': { 'type': 'string' },
  8027. 'contentMediaType': { 'type': 'string' },
  8028. 'contentEncoding': { 'type': 'string' },
  8029. 'if': { '$ref': '#' },
  8030. 'then': { '$ref': '#' },
  8031. 'else': { '$ref': '#' },
  8032. 'allOf': { '$ref': '#/definitions/schemaArray' },
  8033. 'anyOf': { '$ref': '#/definitions/schemaArray' },
  8034. 'oneOf': { '$ref': '#/definitions/schemaArray' },
  8035. 'not': { '$ref': '#' }
  8036. },
  8037. 'default': true
  8038. }
  8039. }
  8040. };
  8041. var descriptions = {
  8042. id: localize('schema.json.id', "A unique identifier for the schema."),
  8043. $schema: localize('schema.json.$schema', "The schema to verify this document against."),
  8044. title: localize('schema.json.title', "A descriptive title of the element."),
  8045. description: localize('schema.json.description', "A long description of the element. Used in hover menus and suggestions."),
  8046. default: localize('schema.json.default', "A default value. Used by suggestions."),
  8047. multipleOf: localize('schema.json.multipleOf', "A number that should cleanly divide the current value (i.e. have no remainder)."),
  8048. maximum: localize('schema.json.maximum', "The maximum numerical value, inclusive by default."),
  8049. exclusiveMaximum: localize('schema.json.exclusiveMaximum', "Makes the maximum property exclusive."),
  8050. minimum: localize('schema.json.minimum', "The minimum numerical value, inclusive by default."),
  8051. exclusiveMinimum: localize('schema.json.exclusiveMininum', "Makes the minimum property exclusive."),
  8052. maxLength: localize('schema.json.maxLength', "The maximum length of a string."),
  8053. minLength: localize('schema.json.minLength', "The minimum length of a string."),
  8054. pattern: localize('schema.json.pattern', "A regular expression to match the string against. It is not implicitly anchored."),
  8055. 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."),
  8056. 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."),
  8057. maxItems: localize('schema.json.maxItems', "The maximum number of items that can be inside an array. Inclusive."),
  8058. minItems: localize('schema.json.minItems', "The minimum number of items that can be inside an array. Inclusive."),
  8059. uniqueItems: localize('schema.json.uniqueItems', "If all of the items in the array must be unique. Defaults to false."),
  8060. maxProperties: localize('schema.json.maxProperties', "The maximum number of properties an object can have. Inclusive."),
  8061. minProperties: localize('schema.json.minProperties', "The minimum number of properties an object can have. Inclusive."),
  8062. required: localize('schema.json.required', "An array of strings that lists the names of all properties required on this object."),
  8063. 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."),
  8064. definitions: localize('schema.json.definitions', "Not used for validation. Place subschemas here that you wish to reference inline with $ref."),
  8065. properties: localize('schema.json.properties', "A map of property names to schemas for each property."),
  8066. patternProperties: localize('schema.json.patternProperties', "A map of regular expressions on property names to schemas for matching properties."),
  8067. 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."),
  8068. enum: localize('schema.json.enum', "The set of literal values that are valid."),
  8069. 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."),
  8070. format: localize('schema.json.format', "Describes the format expected for the value."),
  8071. allOf: localize('schema.json.allOf', "An array of schemas, all of which must match."),
  8072. anyOf: localize('schema.json.anyOf', "An array of schemas, where at least one must match."),
  8073. oneOf: localize('schema.json.oneOf', "An array of schemas, exactly one of which must match."),
  8074. not: localize('schema.json.not', "A schema which must not match."),
  8075. $id: localize('schema.json.$id', "A unique identifier for the schema."),
  8076. $ref: localize('schema.json.$ref', "Reference a definition hosted on any location."),
  8077. $comment: localize('schema.json.$comment', "Comments from schema authors to readers or maintainers of the schema."),
  8078. readOnly: localize('schema.json.readOnly', "Indicates that the value of the instance is managed exclusively by the owning authority."),
  8079. examples: localize('schema.json.examples', "Sample JSON values associated with a particular schema, for the purpose of illustrating usage."),
  8080. 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."),
  8081. 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."),
  8082. const: localize('schema.json.const', "An instance validates successfully against this keyword if its value is equal to the value of the keyword."),
  8083. contentMediaType: localize('schema.json.contentMediaType', "Describes the media type of a string property."),
  8084. contentEncoding: localize('schema.json.contentEncoding', "Describes the content encoding of a string property."),
  8085. if: localize('schema.json.if', "The validation outcome of the \"if\" subschema controls which of the \"then\" or \"else\" keywords are evaluated."),
  8086. then: localize('schema.json.then', "The \"if\" subschema is used for validation when the \"if\" subschema succeeds."),
  8087. else: localize('schema.json.else', "The \"else\" subschema is used for validation when the \"if\" subschema fails.")
  8088. };
  8089. for (var schemaName in exports.schemaContributions.schemas) {
  8090. var schema = exports.schemaContributions.schemas[schemaName];
  8091. for (var property in schema.properties) {
  8092. var propertyObject = schema.properties[property];
  8093. if (propertyObject === true) {
  8094. propertyObject = schema.properties[property] = {};
  8095. }
  8096. var description = descriptions[property];
  8097. if (description) {
  8098. propertyObject['description'] = description;
  8099. }
  8100. else {
  8101. console.log(property + ": localize('schema.json." + property + "', \"\")");
  8102. }
  8103. }
  8104. }
  8105. });
  8106. /*---------------------------------------------------------------------------------------------
  8107. * Copyright (c) Microsoft Corporation. All rights reserved.
  8108. * Licensed under the MIT License. See License.txt in the project root for license information.
  8109. *--------------------------------------------------------------------------------------------*/
  8110. (function (factory) {
  8111. if (typeof module === "object" && typeof module.exports === "object") {
  8112. var v = factory(require, exports);
  8113. if (v !== undefined) module.exports = v;
  8114. }
  8115. else if (typeof define === "function" && define.amd) {
  8116. define('vscode-json-languageservice/services/jsonFolding',["require", "exports", "jsonc-parser", "../jsonLanguageTypes"], factory);
  8117. }
  8118. })(function (require, exports) {
  8119. "use strict";
  8120. Object.defineProperty(exports, "__esModule", { value: true });
  8121. var jsonc_parser_1 = require("jsonc-parser");
  8122. var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
  8123. function getFoldingRanges(document, context) {
  8124. var ranges = [];
  8125. var nestingLevels = [];
  8126. var stack = [];
  8127. var prevStart = -1;
  8128. var scanner = jsonc_parser_1.createScanner(document.getText(), false);
  8129. var token = scanner.scan();
  8130. function addRange(range) {
  8131. ranges.push(range);
  8132. nestingLevels.push(stack.length);
  8133. }
  8134. while (token !== 17 /* EOF */) {
  8135. switch (token) {
  8136. case 1 /* OpenBraceToken */:
  8137. case 3 /* OpenBracketToken */: {
  8138. var startLine = document.positionAt(scanner.getTokenOffset()).line;
  8139. var range = { startLine: startLine, endLine: startLine, kind: token === 1 /* OpenBraceToken */ ? 'object' : 'array' };
  8140. stack.push(range);
  8141. break;
  8142. }
  8143. case 2 /* CloseBraceToken */:
  8144. case 4 /* CloseBracketToken */: {
  8145. var kind = token === 2 /* CloseBraceToken */ ? 'object' : 'array';
  8146. if (stack.length > 0 && stack[stack.length - 1].kind === kind) {
  8147. var range = stack.pop();
  8148. var line = document.positionAt(scanner.getTokenOffset()).line;
  8149. if (range && line > range.startLine + 1 && prevStart !== range.startLine) {
  8150. range.endLine = line - 1;
  8151. addRange(range);
  8152. prevStart = range.startLine;
  8153. }
  8154. }
  8155. break;
  8156. }
  8157. case 13 /* BlockCommentTrivia */: {
  8158. var startLine = document.positionAt(scanner.getTokenOffset()).line;
  8159. var endLine = document.positionAt(scanner.getTokenOffset() + scanner.getTokenLength()).line;
  8160. if (scanner.getTokenError() === 1 /* UnexpectedEndOfComment */ && startLine + 1 < document.lineCount) {
  8161. scanner.setPosition(document.offsetAt(jsonLanguageTypes_1.Position.create(startLine + 1, 0)));
  8162. }
  8163. else {
  8164. if (startLine < endLine) {
  8165. addRange({ startLine: startLine, endLine: endLine, kind: jsonLanguageTypes_1.FoldingRangeKind.Comment });
  8166. prevStart = startLine;
  8167. }
  8168. }
  8169. break;
  8170. }
  8171. case 12 /* LineCommentTrivia */: {
  8172. var text = document.getText().substr(scanner.getTokenOffset(), scanner.getTokenLength());
  8173. var m = text.match(/^\/\/\s*#(region\b)|(endregion\b)/);
  8174. if (m) {
  8175. var line = document.positionAt(scanner.getTokenOffset()).line;
  8176. if (m[1]) { // start pattern match
  8177. var range = { startLine: line, endLine: line, kind: jsonLanguageTypes_1.FoldingRangeKind.Region };
  8178. stack.push(range);
  8179. }
  8180. else {
  8181. var i = stack.length - 1;
  8182. while (i >= 0 && stack[i].kind !== jsonLanguageTypes_1.FoldingRangeKind.Region) {
  8183. i--;
  8184. }
  8185. if (i >= 0) {
  8186. var range = stack[i];
  8187. stack.length = i;
  8188. if (line > range.startLine && prevStart !== range.startLine) {
  8189. range.endLine = line;
  8190. addRange(range);
  8191. prevStart = range.startLine;
  8192. }
  8193. }
  8194. }
  8195. }
  8196. break;
  8197. }
  8198. }
  8199. token = scanner.scan();
  8200. }
  8201. var rangeLimit = context && context.rangeLimit;
  8202. if (typeof rangeLimit !== 'number' || ranges.length <= rangeLimit) {
  8203. return ranges;
  8204. }
  8205. if (context && context.onRangeLimitExceeded) {
  8206. context.onRangeLimitExceeded(document.uri);
  8207. }
  8208. var counts = [];
  8209. for (var _i = 0, nestingLevels_1 = nestingLevels; _i < nestingLevels_1.length; _i++) {
  8210. var level = nestingLevels_1[_i];
  8211. if (level < 30) {
  8212. counts[level] = (counts[level] || 0) + 1;
  8213. }
  8214. }
  8215. var entries = 0;
  8216. var maxLevel = 0;
  8217. for (var i = 0; i < counts.length; i++) {
  8218. var n = counts[i];
  8219. if (n) {
  8220. if (n + entries > rangeLimit) {
  8221. maxLevel = i;
  8222. break;
  8223. }
  8224. entries += n;
  8225. }
  8226. }
  8227. var result = [];
  8228. for (var i = 0; i < ranges.length; i++) {
  8229. var level = nestingLevels[i];
  8230. if (typeof level === 'number') {
  8231. if (level < maxLevel || (level === maxLevel && entries++ < rangeLimit)) {
  8232. result.push(ranges[i]);
  8233. }
  8234. }
  8235. }
  8236. return result;
  8237. }
  8238. exports.getFoldingRanges = getFoldingRanges;
  8239. });
  8240. /*---------------------------------------------------------------------------------------------
  8241. * Copyright (c) Microsoft Corporation. All rights reserved.
  8242. * Licensed under the MIT License. See License.txt in the project root for license information.
  8243. *--------------------------------------------------------------------------------------------*/
  8244. (function (factory) {
  8245. if (typeof module === "object" && typeof module.exports === "object") {
  8246. var v = factory(require, exports);
  8247. if (v !== undefined) module.exports = v;
  8248. }
  8249. else if (typeof define === "function" && define.amd) {
  8250. define('vscode-json-languageservice/services/jsonSelectionRanges',["require", "exports", "../jsonLanguageTypes", "jsonc-parser"], factory);
  8251. }
  8252. })(function (require, exports) {
  8253. "use strict";
  8254. Object.defineProperty(exports, "__esModule", { value: true });
  8255. var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
  8256. var jsonc_parser_1 = require("jsonc-parser");
  8257. function getSelectionRanges(document, positions, doc) {
  8258. function getSelectionRange(position) {
  8259. var offset = document.offsetAt(position);
  8260. var node = doc.getNodeFromOffset(offset, true);
  8261. var result = [];
  8262. while (node) {
  8263. switch (node.type) {
  8264. case 'string':
  8265. case 'object':
  8266. case 'array':
  8267. // range without ", [ or {
  8268. var cStart = node.offset + 1, cEnd = node.offset + node.length - 1;
  8269. if (cStart < cEnd && offset >= cStart && offset <= cEnd) {
  8270. result.push(newRange(cStart, cEnd));
  8271. }
  8272. result.push(newRange(node.offset, node.offset + node.length));
  8273. break;
  8274. case 'number':
  8275. case 'boolean':
  8276. case 'null':
  8277. case 'property':
  8278. result.push(newRange(node.offset, node.offset + node.length));
  8279. break;
  8280. }
  8281. if (node.type === 'property' || node.parent && node.parent.type === 'array') {
  8282. var afterCommaOffset = getOffsetAfterNextToken(node.offset + node.length, 5 /* CommaToken */);
  8283. if (afterCommaOffset !== -1) {
  8284. result.push(newRange(node.offset, afterCommaOffset));
  8285. }
  8286. }
  8287. node = node.parent;
  8288. }
  8289. var current = undefined;
  8290. for (var index = result.length - 1; index >= 0; index--) {
  8291. current = jsonLanguageTypes_1.SelectionRange.create(result[index], current);
  8292. }
  8293. if (!current) {
  8294. current = jsonLanguageTypes_1.SelectionRange.create(jsonLanguageTypes_1.Range.create(position, position));
  8295. }
  8296. return current;
  8297. }
  8298. function newRange(start, end) {
  8299. return jsonLanguageTypes_1.Range.create(document.positionAt(start), document.positionAt(end));
  8300. }
  8301. var scanner = jsonc_parser_1.createScanner(document.getText(), true);
  8302. function getOffsetAfterNextToken(offset, expectedToken) {
  8303. scanner.setPosition(offset);
  8304. var token = scanner.scan();
  8305. if (token === expectedToken) {
  8306. return scanner.getTokenOffset() + scanner.getTokenLength();
  8307. }
  8308. return -1;
  8309. }
  8310. return positions.map(getSelectionRange);
  8311. }
  8312. exports.getSelectionRanges = getSelectionRanges;
  8313. });
  8314. /*---------------------------------------------------------------------------------------------
  8315. * Copyright (c) Microsoft Corporation. All rights reserved.
  8316. * Licensed under the MIT License. See License.txt in the project root for license information.
  8317. *--------------------------------------------------------------------------------------------*/
  8318. (function (factory) {
  8319. if (typeof module === "object" && typeof module.exports === "object") {
  8320. var v = factory(require, exports);
  8321. if (v !== undefined) module.exports = v;
  8322. }
  8323. else if (typeof define === "function" && define.amd) {
  8324. 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", "./jsonLanguageTypes"], factory);
  8325. }
  8326. })(function (require, exports) {
  8327. "use strict";
  8328. function __export(m) {
  8329. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  8330. }
  8331. Object.defineProperty(exports, "__esModule", { value: true });
  8332. var jsonCompletion_1 = require("./services/jsonCompletion");
  8333. var jsonHover_1 = require("./services/jsonHover");
  8334. var jsonValidation_1 = require("./services/jsonValidation");
  8335. var jsonDocumentSymbols_1 = require("./services/jsonDocumentSymbols");
  8336. var jsonParser_1 = require("./parser/jsonParser");
  8337. var configuration_1 = require("./services/configuration");
  8338. var jsonSchemaService_1 = require("./services/jsonSchemaService");
  8339. var jsonFolding_1 = require("./services/jsonFolding");
  8340. var jsonSelectionRanges_1 = require("./services/jsonSelectionRanges");
  8341. var jsonc_parser_1 = require("jsonc-parser");
  8342. var jsonLanguageTypes_1 = require("./jsonLanguageTypes");
  8343. __export(require("./jsonLanguageTypes"));
  8344. function getLanguageService(params) {
  8345. var promise = params.promiseConstructor || Promise;
  8346. var jsonSchemaService = new jsonSchemaService_1.JSONSchemaService(params.schemaRequestService, params.workspaceContext, promise);
  8347. jsonSchemaService.setSchemaContributions(configuration_1.schemaContributions);
  8348. var jsonCompletion = new jsonCompletion_1.JSONCompletion(jsonSchemaService, params.contributions, promise, params.clientCapabilities);
  8349. var jsonHover = new jsonHover_1.JSONHover(jsonSchemaService, params.contributions, promise);
  8350. var jsonDocumentSymbols = new jsonDocumentSymbols_1.JSONDocumentSymbols(jsonSchemaService);
  8351. var jsonValidation = new jsonValidation_1.JSONValidation(jsonSchemaService, promise);
  8352. return {
  8353. configure: function (settings) {
  8354. jsonSchemaService.clearExternalSchemas();
  8355. if (settings.schemas) {
  8356. settings.schemas.forEach(function (settings) {
  8357. jsonSchemaService.registerExternalSchema(settings.uri, settings.fileMatch, settings.schema);
  8358. });
  8359. }
  8360. jsonValidation.configure(settings);
  8361. },
  8362. resetSchema: function (uri) { return jsonSchemaService.onResourceChange(uri); },
  8363. doValidation: jsonValidation.doValidation.bind(jsonValidation),
  8364. parseJSONDocument: function (document) { return jsonParser_1.parse(document, { collectComments: true }); },
  8365. newJSONDocument: function (root, diagnostics) { return jsonParser_1.newJSONDocument(root, diagnostics); },
  8366. doResolve: jsonCompletion.doResolve.bind(jsonCompletion),
  8367. doComplete: jsonCompletion.doComplete.bind(jsonCompletion),
  8368. findDocumentSymbols: jsonDocumentSymbols.findDocumentSymbols.bind(jsonDocumentSymbols),
  8369. findDocumentSymbols2: jsonDocumentSymbols.findDocumentSymbols2.bind(jsonDocumentSymbols),
  8370. findColorSymbols: function (d, s) { return jsonDocumentSymbols.findDocumentColors(d, s).then(function (s) { return s.map(function (s) { return s.range; }); }); },
  8371. findDocumentColors: jsonDocumentSymbols.findDocumentColors.bind(jsonDocumentSymbols),
  8372. getColorPresentations: jsonDocumentSymbols.getColorPresentations.bind(jsonDocumentSymbols),
  8373. doHover: jsonHover.doHover.bind(jsonHover),
  8374. getFoldingRanges: jsonFolding_1.getFoldingRanges,
  8375. getSelectionRanges: jsonSelectionRanges_1.getSelectionRanges,
  8376. format: function (d, r, o) {
  8377. var range = void 0;
  8378. if (r) {
  8379. var offset = d.offsetAt(r.start);
  8380. var length = d.offsetAt(r.end) - offset;
  8381. range = { offset: offset, length: length };
  8382. }
  8383. var options = { tabSize: o ? o.tabSize : 4, insertSpaces: o ? o.insertSpaces : true, eol: '\n' };
  8384. return jsonc_parser_1.format(d.getText(), range, options).map(function (e) {
  8385. return jsonLanguageTypes_1.TextEdit.replace(jsonLanguageTypes_1.Range.create(d.positionAt(e.offset), d.positionAt(e.offset + e.length)), e.content);
  8386. });
  8387. }
  8388. };
  8389. }
  8390. exports.getLanguageService = getLanguageService;
  8391. });
  8392. define('vscode-json-languageservice', ['vscode-json-languageservice/jsonLanguageService'], function (main) { return main; });
  8393. define('vs/language/json/languageFeatures',["require", "exports", "vscode-json-languageservice"], function (require, exports, jsonService) {
  8394. /*---------------------------------------------------------------------------------------------
  8395. * Copyright (c) Microsoft Corporation. All rights reserved.
  8396. * Licensed under the MIT License. See License.txt in the project root for license information.
  8397. *--------------------------------------------------------------------------------------------*/
  8398. 'use strict';
  8399. Object.defineProperty(exports, "__esModule", { value: true });
  8400. var Uri = monaco.Uri;
  8401. var Range = monaco.Range;
  8402. // --- diagnostics --- ---
  8403. var DiagnosticsAdapter = /** @class */ (function () {
  8404. function DiagnosticsAdapter(_languageId, _worker, defaults) {
  8405. var _this = this;
  8406. this._languageId = _languageId;
  8407. this._worker = _worker;
  8408. this._disposables = [];
  8409. this._listener = Object.create(null);
  8410. var onModelAdd = function (model) {
  8411. var modeId = model.getModeId();
  8412. if (modeId !== _this._languageId) {
  8413. return;
  8414. }
  8415. var handle;
  8416. _this._listener[model.uri.toString()] = model.onDidChangeContent(function () {
  8417. clearTimeout(handle);
  8418. handle = setTimeout(function () { return _this._doValidate(model.uri, modeId); }, 500);
  8419. });
  8420. _this._doValidate(model.uri, modeId);
  8421. };
  8422. var onModelRemoved = function (model) {
  8423. monaco.editor.setModelMarkers(model, _this._languageId, []);
  8424. var uriStr = model.uri.toString();
  8425. var listener = _this._listener[uriStr];
  8426. if (listener) {
  8427. listener.dispose();
  8428. delete _this._listener[uriStr];
  8429. }
  8430. };
  8431. this._disposables.push(monaco.editor.onDidCreateModel(onModelAdd));
  8432. this._disposables.push(monaco.editor.onWillDisposeModel(function (model) {
  8433. onModelRemoved(model);
  8434. _this._resetSchema(model.uri);
  8435. }));
  8436. this._disposables.push(monaco.editor.onDidChangeModelLanguage(function (event) {
  8437. onModelRemoved(event.model);
  8438. onModelAdd(event.model);
  8439. _this._resetSchema(event.model.uri);
  8440. }));
  8441. this._disposables.push(defaults.onDidChange(function (_) {
  8442. monaco.editor.getModels().forEach(function (model) {
  8443. if (model.getModeId() === _this._languageId) {
  8444. onModelRemoved(model);
  8445. onModelAdd(model);
  8446. }
  8447. });
  8448. }));
  8449. this._disposables.push({
  8450. dispose: function () {
  8451. monaco.editor.getModels().forEach(onModelRemoved);
  8452. for (var key in _this._listener) {
  8453. _this._listener[key].dispose();
  8454. }
  8455. }
  8456. });
  8457. monaco.editor.getModels().forEach(onModelAdd);
  8458. }
  8459. DiagnosticsAdapter.prototype.dispose = function () {
  8460. this._disposables.forEach(function (d) { return d && d.dispose(); });
  8461. this._disposables = [];
  8462. };
  8463. DiagnosticsAdapter.prototype._resetSchema = function (resource) {
  8464. this._worker().then(function (worker) {
  8465. worker.resetSchema(resource.toString());
  8466. });
  8467. };
  8468. DiagnosticsAdapter.prototype._doValidate = function (resource, languageId) {
  8469. this._worker(resource).then(function (worker) {
  8470. return worker.doValidation(resource.toString()).then(function (diagnostics) {
  8471. var markers = diagnostics.map(function (d) { return toDiagnostics(resource, d); });
  8472. var model = monaco.editor.getModel(resource);
  8473. if (model && model.getModeId() === languageId) {
  8474. monaco.editor.setModelMarkers(model, languageId, markers);
  8475. }
  8476. });
  8477. }).then(undefined, function (err) {
  8478. console.error(err);
  8479. });
  8480. };
  8481. return DiagnosticsAdapter;
  8482. }());
  8483. exports.DiagnosticsAdapter = DiagnosticsAdapter;
  8484. function toSeverity(lsSeverity) {
  8485. switch (lsSeverity) {
  8486. case jsonService.DiagnosticSeverity.Error: return monaco.MarkerSeverity.Error;
  8487. case jsonService.DiagnosticSeverity.Warning: return monaco.MarkerSeverity.Warning;
  8488. case jsonService.DiagnosticSeverity.Information: return monaco.MarkerSeverity.Info;
  8489. case jsonService.DiagnosticSeverity.Hint: return monaco.MarkerSeverity.Hint;
  8490. default:
  8491. return monaco.MarkerSeverity.Info;
  8492. }
  8493. }
  8494. function toDiagnostics(resource, diag) {
  8495. var code = typeof diag.code === 'number' ? String(diag.code) : diag.code;
  8496. return {
  8497. severity: toSeverity(diag.severity),
  8498. startLineNumber: diag.range.start.line + 1,
  8499. startColumn: diag.range.start.character + 1,
  8500. endLineNumber: diag.range.end.line + 1,
  8501. endColumn: diag.range.end.character + 1,
  8502. message: diag.message,
  8503. code: code,
  8504. source: diag.source
  8505. };
  8506. }
  8507. // --- completion ------
  8508. function fromPosition(position) {
  8509. if (!position) {
  8510. return void 0;
  8511. }
  8512. return { character: position.column - 1, line: position.lineNumber - 1 };
  8513. }
  8514. function fromRange(range) {
  8515. if (!range) {
  8516. return void 0;
  8517. }
  8518. return { start: { line: range.startLineNumber - 1, character: range.startColumn - 1 }, end: { line: range.endLineNumber - 1, character: range.endColumn - 1 } };
  8519. }
  8520. function toRange(range) {
  8521. if (!range) {
  8522. return void 0;
  8523. }
  8524. return new Range(range.start.line + 1, range.start.character + 1, range.end.line + 1, range.end.character + 1);
  8525. }
  8526. function toCompletionItemKind(kind) {
  8527. var mItemKind = monaco.languages.CompletionItemKind;
  8528. switch (kind) {
  8529. case jsonService.CompletionItemKind.Text: return mItemKind.Text;
  8530. case jsonService.CompletionItemKind.Method: return mItemKind.Method;
  8531. case jsonService.CompletionItemKind.Function: return mItemKind.Function;
  8532. case jsonService.CompletionItemKind.Constructor: return mItemKind.Constructor;
  8533. case jsonService.CompletionItemKind.Field: return mItemKind.Field;
  8534. case jsonService.CompletionItemKind.Variable: return mItemKind.Variable;
  8535. case jsonService.CompletionItemKind.Class: return mItemKind.Class;
  8536. case jsonService.CompletionItemKind.Interface: return mItemKind.Interface;
  8537. case jsonService.CompletionItemKind.Module: return mItemKind.Module;
  8538. case jsonService.CompletionItemKind.Property: return mItemKind.Property;
  8539. case jsonService.CompletionItemKind.Unit: return mItemKind.Unit;
  8540. case jsonService.CompletionItemKind.Value: return mItemKind.Value;
  8541. case jsonService.CompletionItemKind.Enum: return mItemKind.Enum;
  8542. case jsonService.CompletionItemKind.Keyword: return mItemKind.Keyword;
  8543. case jsonService.CompletionItemKind.Snippet: return mItemKind.Snippet;
  8544. case jsonService.CompletionItemKind.Color: return mItemKind.Color;
  8545. case jsonService.CompletionItemKind.File: return mItemKind.File;
  8546. case jsonService.CompletionItemKind.Reference: return mItemKind.Reference;
  8547. }
  8548. return mItemKind.Property;
  8549. }
  8550. function fromCompletionItemKind(kind) {
  8551. var mItemKind = monaco.languages.CompletionItemKind;
  8552. switch (kind) {
  8553. case mItemKind.Text: return jsonService.CompletionItemKind.Text;
  8554. case mItemKind.Method: return jsonService.CompletionItemKind.Method;
  8555. case mItemKind.Function: return jsonService.CompletionItemKind.Function;
  8556. case mItemKind.Constructor: return jsonService.CompletionItemKind.Constructor;
  8557. case mItemKind.Field: return jsonService.CompletionItemKind.Field;
  8558. case mItemKind.Variable: return jsonService.CompletionItemKind.Variable;
  8559. case mItemKind.Class: return jsonService.CompletionItemKind.Class;
  8560. case mItemKind.Interface: return jsonService.CompletionItemKind.Interface;
  8561. case mItemKind.Module: return jsonService.CompletionItemKind.Module;
  8562. case mItemKind.Property: return jsonService.CompletionItemKind.Property;
  8563. case mItemKind.Unit: return jsonService.CompletionItemKind.Unit;
  8564. case mItemKind.Value: return jsonService.CompletionItemKind.Value;
  8565. case mItemKind.Enum: return jsonService.CompletionItemKind.Enum;
  8566. case mItemKind.Keyword: return jsonService.CompletionItemKind.Keyword;
  8567. case mItemKind.Snippet: return jsonService.CompletionItemKind.Snippet;
  8568. case mItemKind.Color: return jsonService.CompletionItemKind.Color;
  8569. case mItemKind.File: return jsonService.CompletionItemKind.File;
  8570. case mItemKind.Reference: return jsonService.CompletionItemKind.Reference;
  8571. }
  8572. return jsonService.CompletionItemKind.Property;
  8573. }
  8574. function toTextEdit(textEdit) {
  8575. if (!textEdit) {
  8576. return void 0;
  8577. }
  8578. return {
  8579. range: toRange(textEdit.range),
  8580. text: textEdit.newText
  8581. };
  8582. }
  8583. var CompletionAdapter = /** @class */ (function () {
  8584. function CompletionAdapter(_worker) {
  8585. this._worker = _worker;
  8586. }
  8587. Object.defineProperty(CompletionAdapter.prototype, "triggerCharacters", {
  8588. get: function () {
  8589. return [' ', ':'];
  8590. },
  8591. enumerable: true,
  8592. configurable: true
  8593. });
  8594. CompletionAdapter.prototype.provideCompletionItems = function (model, position, context, token) {
  8595. var resource = model.uri;
  8596. return this._worker(resource).then(function (worker) {
  8597. return worker.doComplete(resource.toString(), fromPosition(position));
  8598. }).then(function (info) {
  8599. if (!info) {
  8600. return;
  8601. }
  8602. var wordInfo = model.getWordUntilPosition(position);
  8603. var wordRange = new Range(position.lineNumber, wordInfo.startColumn, position.lineNumber, wordInfo.endColumn);
  8604. var items = info.items.map(function (entry) {
  8605. var item = {
  8606. label: entry.label,
  8607. insertText: entry.insertText || entry.label,
  8608. sortText: entry.sortText,
  8609. filterText: entry.filterText,
  8610. documentation: entry.documentation,
  8611. detail: entry.detail,
  8612. range: wordRange,
  8613. kind: toCompletionItemKind(entry.kind),
  8614. };
  8615. if (entry.textEdit) {
  8616. item.range = toRange(entry.textEdit.range);
  8617. item.insertText = entry.textEdit.newText;
  8618. }
  8619. if (entry.additionalTextEdits) {
  8620. item.additionalTextEdits = entry.additionalTextEdits.map(toTextEdit);
  8621. }
  8622. if (entry.insertTextFormat === jsonService.InsertTextFormat.Snippet) {
  8623. item.insertTextRules = monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet;
  8624. }
  8625. return item;
  8626. });
  8627. return {
  8628. isIncomplete: info.isIncomplete,
  8629. suggestions: items
  8630. };
  8631. });
  8632. };
  8633. return CompletionAdapter;
  8634. }());
  8635. exports.CompletionAdapter = CompletionAdapter;
  8636. function isMarkupContent(thing) {
  8637. return thing && typeof thing === 'object' && typeof thing.kind === 'string';
  8638. }
  8639. function toMarkdownString(entry) {
  8640. if (typeof entry === 'string') {
  8641. return {
  8642. value: entry
  8643. };
  8644. }
  8645. if (isMarkupContent(entry)) {
  8646. if (entry.kind === 'plaintext') {
  8647. return {
  8648. value: entry.value.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&')
  8649. };
  8650. }
  8651. return {
  8652. value: entry.value
  8653. };
  8654. }
  8655. return { value: '```' + entry.language + '\n' + entry.value + '\n```\n' };
  8656. }
  8657. function toMarkedStringArray(contents) {
  8658. if (!contents) {
  8659. return void 0;
  8660. }
  8661. if (Array.isArray(contents)) {
  8662. return contents.map(toMarkdownString);
  8663. }
  8664. return [toMarkdownString(contents)];
  8665. }
  8666. // --- hover ------
  8667. var HoverAdapter = /** @class */ (function () {
  8668. function HoverAdapter(_worker) {
  8669. this._worker = _worker;
  8670. }
  8671. HoverAdapter.prototype.provideHover = function (model, position, token) {
  8672. var resource = model.uri;
  8673. return this._worker(resource).then(function (worker) {
  8674. return worker.doHover(resource.toString(), fromPosition(position));
  8675. }).then(function (info) {
  8676. if (!info) {
  8677. return;
  8678. }
  8679. return {
  8680. range: toRange(info.range),
  8681. contents: toMarkedStringArray(info.contents)
  8682. };
  8683. });
  8684. };
  8685. return HoverAdapter;
  8686. }());
  8687. exports.HoverAdapter = HoverAdapter;
  8688. // --- definition ------
  8689. function toLocation(location) {
  8690. return {
  8691. uri: Uri.parse(location.uri),
  8692. range: toRange(location.range)
  8693. };
  8694. }
  8695. // --- document symbols ------
  8696. function toSymbolKind(kind) {
  8697. var mKind = monaco.languages.SymbolKind;
  8698. switch (kind) {
  8699. case jsonService.SymbolKind.File: return mKind.Array;
  8700. case jsonService.SymbolKind.Module: return mKind.Module;
  8701. case jsonService.SymbolKind.Namespace: return mKind.Namespace;
  8702. case jsonService.SymbolKind.Package: return mKind.Package;
  8703. case jsonService.SymbolKind.Class: return mKind.Class;
  8704. case jsonService.SymbolKind.Method: return mKind.Method;
  8705. case jsonService.SymbolKind.Property: return mKind.Property;
  8706. case jsonService.SymbolKind.Field: return mKind.Field;
  8707. case jsonService.SymbolKind.Constructor: return mKind.Constructor;
  8708. case jsonService.SymbolKind.Enum: return mKind.Enum;
  8709. case jsonService.SymbolKind.Interface: return mKind.Interface;
  8710. case jsonService.SymbolKind.Function: return mKind.Function;
  8711. case jsonService.SymbolKind.Variable: return mKind.Variable;
  8712. case jsonService.SymbolKind.Constant: return mKind.Constant;
  8713. case jsonService.SymbolKind.String: return mKind.String;
  8714. case jsonService.SymbolKind.Number: return mKind.Number;
  8715. case jsonService.SymbolKind.Boolean: return mKind.Boolean;
  8716. case jsonService.SymbolKind.Array: return mKind.Array;
  8717. }
  8718. return mKind.Function;
  8719. }
  8720. var DocumentSymbolAdapter = /** @class */ (function () {
  8721. function DocumentSymbolAdapter(_worker) {
  8722. this._worker = _worker;
  8723. }
  8724. DocumentSymbolAdapter.prototype.provideDocumentSymbols = function (model, token) {
  8725. var resource = model.uri;
  8726. return this._worker(resource).then(function (worker) { return worker.findDocumentSymbols(resource.toString()); }).then(function (items) {
  8727. if (!items) {
  8728. return;
  8729. }
  8730. return items.map(function (item) { return ({
  8731. name: item.name,
  8732. detail: '',
  8733. containerName: item.containerName,
  8734. kind: toSymbolKind(item.kind),
  8735. range: toRange(item.location.range),
  8736. selectionRange: toRange(item.location.range),
  8737. tags: []
  8738. }); });
  8739. });
  8740. };
  8741. return DocumentSymbolAdapter;
  8742. }());
  8743. exports.DocumentSymbolAdapter = DocumentSymbolAdapter;
  8744. function fromFormattingOptions(options) {
  8745. return {
  8746. tabSize: options.tabSize,
  8747. insertSpaces: options.insertSpaces
  8748. };
  8749. }
  8750. var DocumentFormattingEditProvider = /** @class */ (function () {
  8751. function DocumentFormattingEditProvider(_worker) {
  8752. this._worker = _worker;
  8753. }
  8754. DocumentFormattingEditProvider.prototype.provideDocumentFormattingEdits = function (model, options, token) {
  8755. var resource = model.uri;
  8756. return this._worker(resource).then(function (worker) {
  8757. return worker.format(resource.toString(), null, fromFormattingOptions(options)).then(function (edits) {
  8758. if (!edits || edits.length === 0) {
  8759. return;
  8760. }
  8761. return edits.map(toTextEdit);
  8762. });
  8763. });
  8764. };
  8765. return DocumentFormattingEditProvider;
  8766. }());
  8767. exports.DocumentFormattingEditProvider = DocumentFormattingEditProvider;
  8768. var DocumentRangeFormattingEditProvider = /** @class */ (function () {
  8769. function DocumentRangeFormattingEditProvider(_worker) {
  8770. this._worker = _worker;
  8771. }
  8772. DocumentRangeFormattingEditProvider.prototype.provideDocumentRangeFormattingEdits = function (model, range, options, token) {
  8773. var resource = model.uri;
  8774. return this._worker(resource).then(function (worker) {
  8775. return worker.format(resource.toString(), fromRange(range), fromFormattingOptions(options)).then(function (edits) {
  8776. if (!edits || edits.length === 0) {
  8777. return;
  8778. }
  8779. return edits.map(toTextEdit);
  8780. });
  8781. });
  8782. };
  8783. return DocumentRangeFormattingEditProvider;
  8784. }());
  8785. exports.DocumentRangeFormattingEditProvider = DocumentRangeFormattingEditProvider;
  8786. var DocumentColorAdapter = /** @class */ (function () {
  8787. function DocumentColorAdapter(_worker) {
  8788. this._worker = _worker;
  8789. }
  8790. DocumentColorAdapter.prototype.provideDocumentColors = function (model, token) {
  8791. var resource = model.uri;
  8792. return this._worker(resource).then(function (worker) { return worker.findDocumentColors(resource.toString()); }).then(function (infos) {
  8793. if (!infos) {
  8794. return;
  8795. }
  8796. return infos.map(function (item) { return ({
  8797. color: item.color,
  8798. range: toRange(item.range)
  8799. }); });
  8800. });
  8801. };
  8802. DocumentColorAdapter.prototype.provideColorPresentations = function (model, info, token) {
  8803. var resource = model.uri;
  8804. return this._worker(resource).then(function (worker) { return worker.getColorPresentations(resource.toString(), info.color, fromRange(info.range)); }).then(function (presentations) {
  8805. if (!presentations) {
  8806. return;
  8807. }
  8808. return presentations.map(function (presentation) {
  8809. var item = {
  8810. label: presentation.label,
  8811. };
  8812. if (presentation.textEdit) {
  8813. item.textEdit = toTextEdit(presentation.textEdit);
  8814. }
  8815. if (presentation.additionalTextEdits) {
  8816. item.additionalTextEdits = presentation.additionalTextEdits.map(toTextEdit);
  8817. }
  8818. return item;
  8819. });
  8820. });
  8821. };
  8822. return DocumentColorAdapter;
  8823. }());
  8824. exports.DocumentColorAdapter = DocumentColorAdapter;
  8825. var FoldingRangeAdapter = /** @class */ (function () {
  8826. function FoldingRangeAdapter(_worker) {
  8827. this._worker = _worker;
  8828. }
  8829. FoldingRangeAdapter.prototype.provideFoldingRanges = function (model, context, token) {
  8830. var resource = model.uri;
  8831. return this._worker(resource).then(function (worker) { return worker.getFoldingRanges(resource.toString(), context); }).then(function (ranges) {
  8832. if (!ranges) {
  8833. return;
  8834. }
  8835. return ranges.map(function (range) {
  8836. var result = {
  8837. start: range.startLine + 1,
  8838. end: range.endLine + 1
  8839. };
  8840. if (typeof range.kind !== 'undefined') {
  8841. result.kind = toFoldingRangeKind(range.kind);
  8842. }
  8843. return result;
  8844. });
  8845. });
  8846. };
  8847. return FoldingRangeAdapter;
  8848. }());
  8849. exports.FoldingRangeAdapter = FoldingRangeAdapter;
  8850. function toFoldingRangeKind(kind) {
  8851. switch (kind) {
  8852. case jsonService.FoldingRangeKind.Comment: return monaco.languages.FoldingRangeKind.Comment;
  8853. case jsonService.FoldingRangeKind.Imports: return monaco.languages.FoldingRangeKind.Imports;
  8854. case jsonService.FoldingRangeKind.Region: return monaco.languages.FoldingRangeKind.Region;
  8855. }
  8856. return void 0;
  8857. }
  8858. var SelectionRangeAdapter = /** @class */ (function () {
  8859. function SelectionRangeAdapter(_worker) {
  8860. this._worker = _worker;
  8861. }
  8862. SelectionRangeAdapter.prototype.provideSelectionRanges = function (model, positions, token) {
  8863. var resource = model.uri;
  8864. return this._worker(resource).then(function (worker) { return worker.getSelectionRanges(resource.toString(), positions.map(fromPosition)); }).then(function (selectionRanges) {
  8865. if (!selectionRanges) {
  8866. return;
  8867. }
  8868. return selectionRanges.map(function (selectionRange) {
  8869. var result = [];
  8870. while (selectionRange) {
  8871. result.push({ range: toRange(selectionRange.range) });
  8872. selectionRange = selectionRange.parent;
  8873. }
  8874. return result;
  8875. });
  8876. });
  8877. };
  8878. return SelectionRangeAdapter;
  8879. }());
  8880. exports.SelectionRangeAdapter = SelectionRangeAdapter;
  8881. });
  8882. define('vs/language/json/tokenization',["require", "exports", "jsonc-parser"], function (require, exports, json) {
  8883. /*---------------------------------------------------------------------------------------------
  8884. * Copyright (c) Microsoft Corporation. All rights reserved.
  8885. * Licensed under the MIT License. See License.txt in the project root for license information.
  8886. *--------------------------------------------------------------------------------------------*/
  8887. 'use strict';
  8888. Object.defineProperty(exports, "__esModule", { value: true });
  8889. function createTokenizationSupport(supportComments) {
  8890. return {
  8891. getInitialState: function () { return new JSONState(null, null, false); },
  8892. tokenize: function (line, state, offsetDelta, stopAtOffset) { return tokenize(supportComments, line, state, offsetDelta, stopAtOffset); }
  8893. };
  8894. }
  8895. exports.createTokenizationSupport = createTokenizationSupport;
  8896. exports.TOKEN_DELIM_OBJECT = 'delimiter.bracket.json';
  8897. exports.TOKEN_DELIM_ARRAY = 'delimiter.array.json';
  8898. exports.TOKEN_DELIM_COLON = 'delimiter.colon.json';
  8899. exports.TOKEN_DELIM_COMMA = 'delimiter.comma.json';
  8900. exports.TOKEN_VALUE_BOOLEAN = 'keyword.json';
  8901. exports.TOKEN_VALUE_NULL = 'keyword.json';
  8902. exports.TOKEN_VALUE_STRING = 'string.value.json';
  8903. exports.TOKEN_VALUE_NUMBER = 'number.json';
  8904. exports.TOKEN_PROPERTY_NAME = 'string.key.json';
  8905. exports.TOKEN_COMMENT_BLOCK = 'comment.block.json';
  8906. exports.TOKEN_COMMENT_LINE = 'comment.line.json';
  8907. var JSONState = /** @class */ (function () {
  8908. function JSONState(state, scanError, lastWasColon) {
  8909. this._state = state;
  8910. this.scanError = scanError;
  8911. this.lastWasColon = lastWasColon;
  8912. }
  8913. JSONState.prototype.clone = function () {
  8914. return new JSONState(this._state, this.scanError, this.lastWasColon);
  8915. };
  8916. JSONState.prototype.equals = function (other) {
  8917. if (other === this) {
  8918. return true;
  8919. }
  8920. if (!other || !(other instanceof JSONState)) {
  8921. return false;
  8922. }
  8923. return this.scanError === other.scanError &&
  8924. this.lastWasColon === other.lastWasColon;
  8925. };
  8926. JSONState.prototype.getStateData = function () {
  8927. return this._state;
  8928. };
  8929. JSONState.prototype.setStateData = function (state) {
  8930. this._state = state;
  8931. };
  8932. return JSONState;
  8933. }());
  8934. function tokenize(comments, line, state, offsetDelta, stopAtOffset) {
  8935. if (offsetDelta === void 0) { offsetDelta = 0; }
  8936. // handle multiline strings and block comments
  8937. var numberOfInsertedCharacters = 0, adjustOffset = false;
  8938. switch (state.scanError) {
  8939. case 2 /* UnexpectedEndOfString */:
  8940. line = '"' + line;
  8941. numberOfInsertedCharacters = 1;
  8942. break;
  8943. case 1 /* UnexpectedEndOfComment */:
  8944. line = '/*' + line;
  8945. numberOfInsertedCharacters = 2;
  8946. break;
  8947. }
  8948. var scanner = json.createScanner(line), kind, ret, lastWasColon = state.lastWasColon;
  8949. ret = {
  8950. tokens: [],
  8951. endState: state.clone()
  8952. };
  8953. while (true) {
  8954. var offset = offsetDelta + scanner.getPosition(), type = '';
  8955. kind = scanner.scan();
  8956. if (kind === 17 /* EOF */) {
  8957. break;
  8958. }
  8959. // Check that the scanner has advanced
  8960. if (offset === offsetDelta + scanner.getPosition()) {
  8961. throw new Error('Scanner did not advance, next 3 characters are: ' + line.substr(scanner.getPosition(), 3));
  8962. }
  8963. // In case we inserted /* or " character, we need to
  8964. // adjust the offset of all tokens (except the first)
  8965. if (adjustOffset) {
  8966. offset -= numberOfInsertedCharacters;
  8967. }
  8968. adjustOffset = numberOfInsertedCharacters > 0;
  8969. // brackets and type
  8970. switch (kind) {
  8971. case 1 /* OpenBraceToken */:
  8972. type = exports.TOKEN_DELIM_OBJECT;
  8973. lastWasColon = false;
  8974. break;
  8975. case 2 /* CloseBraceToken */:
  8976. type = exports.TOKEN_DELIM_OBJECT;
  8977. lastWasColon = false;
  8978. break;
  8979. case 3 /* OpenBracketToken */:
  8980. type = exports.TOKEN_DELIM_ARRAY;
  8981. lastWasColon = false;
  8982. break;
  8983. case 4 /* CloseBracketToken */:
  8984. type = exports.TOKEN_DELIM_ARRAY;
  8985. lastWasColon = false;
  8986. break;
  8987. case 6 /* ColonToken */:
  8988. type = exports.TOKEN_DELIM_COLON;
  8989. lastWasColon = true;
  8990. break;
  8991. case 5 /* CommaToken */:
  8992. type = exports.TOKEN_DELIM_COMMA;
  8993. lastWasColon = false;
  8994. break;
  8995. case 8 /* TrueKeyword */:
  8996. case 9 /* FalseKeyword */:
  8997. type = exports.TOKEN_VALUE_BOOLEAN;
  8998. lastWasColon = false;
  8999. break;
  9000. case 7 /* NullKeyword */:
  9001. type = exports.TOKEN_VALUE_NULL;
  9002. lastWasColon = false;
  9003. break;
  9004. case 10 /* StringLiteral */:
  9005. type = lastWasColon ? exports.TOKEN_VALUE_STRING : exports.TOKEN_PROPERTY_NAME;
  9006. lastWasColon = false;
  9007. break;
  9008. case 11 /* NumericLiteral */:
  9009. type = exports.TOKEN_VALUE_NUMBER;
  9010. lastWasColon = false;
  9011. break;
  9012. }
  9013. // comments, iff enabled
  9014. if (comments) {
  9015. switch (kind) {
  9016. case 12 /* LineCommentTrivia */:
  9017. type = exports.TOKEN_COMMENT_LINE;
  9018. break;
  9019. case 13 /* BlockCommentTrivia */:
  9020. type = exports.TOKEN_COMMENT_BLOCK;
  9021. break;
  9022. }
  9023. }
  9024. ret.endState = new JSONState(state.getStateData(), scanner.getTokenError(), lastWasColon);
  9025. ret.tokens.push({
  9026. startIndex: offset,
  9027. scopes: type
  9028. });
  9029. }
  9030. return ret;
  9031. }
  9032. });
  9033. define('vs/language/json/jsonMode',["require", "exports", "./workerManager", "./languageFeatures", "./tokenization"], function (require, exports, workerManager_1, languageFeatures, tokenization_1) {
  9034. /*---------------------------------------------------------------------------------------------
  9035. * Copyright (c) Microsoft Corporation. All rights reserved.
  9036. * Licensed under the MIT License. See License.txt in the project root for license information.
  9037. *--------------------------------------------------------------------------------------------*/
  9038. 'use strict';
  9039. Object.defineProperty(exports, "__esModule", { value: true });
  9040. function setupMode(defaults) {
  9041. var disposables = [];
  9042. var providers = [];
  9043. var client = new workerManager_1.WorkerManager(defaults);
  9044. disposables.push(client);
  9045. var worker = function () {
  9046. var uris = [];
  9047. for (var _i = 0; _i < arguments.length; _i++) {
  9048. uris[_i] = arguments[_i];
  9049. }
  9050. return client.getLanguageServiceWorker.apply(client, uris);
  9051. };
  9052. function registerProviders() {
  9053. var languageId = defaults.languageId, modeConfiguration = defaults.modeConfiguration;
  9054. disposeAll(providers);
  9055. if (modeConfiguration.documentFormattingEdits) {
  9056. providers.push(monaco.languages.registerDocumentFormattingEditProvider(languageId, new languageFeatures.DocumentFormattingEditProvider(worker)));
  9057. }
  9058. if (modeConfiguration.documentRangeFormattingEdits) {
  9059. providers.push(monaco.languages.registerDocumentRangeFormattingEditProvider(languageId, new languageFeatures.DocumentRangeFormattingEditProvider(worker)));
  9060. }
  9061. if (modeConfiguration.completionItems) {
  9062. providers.push(monaco.languages.registerCompletionItemProvider(languageId, new languageFeatures.CompletionAdapter(worker)));
  9063. }
  9064. if (modeConfiguration.hovers) {
  9065. providers.push(monaco.languages.registerHoverProvider(languageId, new languageFeatures.HoverAdapter(worker)));
  9066. }
  9067. if (modeConfiguration.documentSymbols) {
  9068. providers.push(monaco.languages.registerDocumentSymbolProvider(languageId, new languageFeatures.DocumentSymbolAdapter(worker)));
  9069. }
  9070. if (modeConfiguration.tokens) {
  9071. providers.push(monaco.languages.setTokensProvider(languageId, tokenization_1.createTokenizationSupport(true)));
  9072. }
  9073. if (modeConfiguration.colors) {
  9074. providers.push(monaco.languages.registerColorProvider(languageId, new languageFeatures.DocumentColorAdapter(worker)));
  9075. }
  9076. if (modeConfiguration.foldingRanges) {
  9077. providers.push(monaco.languages.registerFoldingRangeProvider(languageId, new languageFeatures.FoldingRangeAdapter(worker)));
  9078. }
  9079. if (modeConfiguration.diagnostics) {
  9080. providers.push(new languageFeatures.DiagnosticsAdapter(languageId, worker, defaults));
  9081. }
  9082. if (modeConfiguration.selectionRanges) {
  9083. providers.push(monaco.languages.registerSelectionRangeProvider(languageId, new languageFeatures.SelectionRangeAdapter(worker)));
  9084. }
  9085. }
  9086. registerProviders();
  9087. disposables.push(monaco.languages.setLanguageConfiguration(defaults.languageId, richEditConfiguration));
  9088. var modeConfiguration = defaults.modeConfiguration;
  9089. defaults.onDidChange(function (newDefaults) {
  9090. if (newDefaults.modeConfiguration !== modeConfiguration) {
  9091. modeConfiguration = newDefaults.modeConfiguration;
  9092. registerProviders();
  9093. }
  9094. });
  9095. disposables.push(asDisposable(providers));
  9096. return asDisposable(disposables);
  9097. }
  9098. exports.setupMode = setupMode;
  9099. function asDisposable(disposables) {
  9100. return { dispose: function () { return disposeAll(disposables); } };
  9101. }
  9102. function disposeAll(disposables) {
  9103. while (disposables.length) {
  9104. disposables.pop().dispose();
  9105. }
  9106. }
  9107. var richEditConfiguration = {
  9108. wordPattern: /(-?\d*\.\d\w*)|([^\[\{\]\}\:\"\,\s]+)/g,
  9109. comments: {
  9110. lineComment: '//',
  9111. blockComment: ['/*', '*/']
  9112. },
  9113. brackets: [
  9114. ['{', '}'],
  9115. ['[', ']']
  9116. ],
  9117. autoClosingPairs: [
  9118. { open: '{', close: '}', notIn: ['string'] },
  9119. { open: '[', close: ']', notIn: ['string'] },
  9120. { open: '"', close: '"', notIn: ['string'] }
  9121. ]
  9122. };
  9123. });