Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

vscode-json-languageservice

Package Overview
Dependencies
Maintainers
5
Versions
161
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

vscode-json-languageservice - npm Package Compare versions

Comparing version 4.2.1 to 5.0.0

SECURITY.md

8

CHANGELOG.md

@@ -0,4 +1,10 @@

5.0.0 / 2022-05-17
================
* Update to `vscode-languageserver-types@3.16`
* Add more schema support
* Schema 2019-09: unevaluatedProperties, unevaluatedItems, minContains, maxContains, deprecated, dependentRequired, dependentSchemas, $defs, $anchor
* Schema 2020-12: prefixItem
4.2.0 /
4.2.0 / 2022-01-25
================

@@ -5,0 +11,0 @@ * new API `LanguageService.getLanguageStatus`

@@ -0,0 +0,0 @@ import { Thenable, MarkedString, CompletionItem } from './jsonLanguageService';

@@ -0,0 +0,0 @@ import { Thenable, ASTNode, Color, ColorInformation, ColorPresentation, LanguageServiceParams, LanguageSettings, DocumentLanguageSettings, FoldingRange, JSONSchema, SelectionRange, FoldingRangesContext, DocumentSymbolsContext, ColorInformationContext as DocumentColorsContext, TextDocument, Position, CompletionItem, CompletionList, Hover, Range, SymbolInformation, Diagnostic, TextEdit, FormattingOptions, DocumentSymbol, DefinitionLink, MatchingSchema, JSONLanguageStatus } from './jsonLanguageTypes';

44

lib/esm/jsonLanguageService.js

@@ -19,14 +19,14 @@ /*---------------------------------------------------------------------------------------------

export function getLanguageService(params) {
var promise = params.promiseConstructor || Promise;
var jsonSchemaService = new JSONSchemaService(params.schemaRequestService, params.workspaceContext, promise);
const promise = params.promiseConstructor || Promise;
const jsonSchemaService = new JSONSchemaService(params.schemaRequestService, params.workspaceContext, promise);
jsonSchemaService.setSchemaContributions(schemaContributions);
var jsonCompletion = new JSONCompletion(jsonSchemaService, params.contributions, promise, params.clientCapabilities);
var jsonHover = new JSONHover(jsonSchemaService, params.contributions, promise);
var jsonDocumentSymbols = new JSONDocumentSymbols(jsonSchemaService);
var jsonValidation = new JSONValidation(jsonSchemaService, promise);
const jsonCompletion = new JSONCompletion(jsonSchemaService, params.contributions, promise, params.clientCapabilities);
const jsonHover = new JSONHover(jsonSchemaService, params.contributions, promise);
const jsonDocumentSymbols = new JSONDocumentSymbols(jsonSchemaService);
const jsonValidation = new JSONValidation(jsonSchemaService, promise);
return {
configure: function (settings) {
configure: (settings) => {
jsonSchemaService.clearExternalSchemas();
if (settings.schemas) {
settings.schemas.forEach(function (settings) {
settings.schemas.forEach(settings => {
jsonSchemaService.registerExternalSchema(settings.uri, settings.fileMatch, settings.schema);

@@ -37,7 +37,7 @@ });

},
resetSchema: function (uri) { return jsonSchemaService.onResourceChange(uri); },
resetSchema: (uri) => jsonSchemaService.onResourceChange(uri),
doValidation: jsonValidation.doValidation.bind(jsonValidation),
getLanguageStatus: jsonValidation.getLanguageStatus.bind(jsonValidation),
parseJSONDocument: function (document) { return parseJSON(document, { collectComments: true }); },
newJSONDocument: function (root, diagnostics) { return newJSONDocument(root, diagnostics); },
parseJSONDocument: (document) => parseJSON(document, { collectComments: true }),
newJSONDocument: (root, diagnostics) => newJSONDocument(root, diagnostics),
getMatchingSchemas: jsonSchemaService.getMatchingSchemas.bind(jsonSchemaService),

@@ -51,15 +51,15 @@ doResolve: jsonCompletion.doResolve.bind(jsonCompletion),

doHover: jsonHover.doHover.bind(jsonHover),
getFoldingRanges: getFoldingRanges,
getSelectionRanges: getSelectionRanges,
findDefinition: function () { return Promise.resolve([]); },
findLinks: findLinks,
format: function (d, r, o) {
var range = undefined;
getFoldingRanges,
getSelectionRanges,
findDefinition: () => Promise.resolve([]),
findLinks,
format: (d, r, o) => {
let range = undefined;
if (r) {
var offset = d.offsetAt(r.start);
var length = d.offsetAt(r.end) - offset;
range = { offset: offset, length: length };
const offset = d.offsetAt(r.start);
const length = d.offsetAt(r.end) - offset;
range = { offset, length };
}
var options = { tabSize: o ? o.tabSize : 4, insertSpaces: (o === null || o === void 0 ? void 0 : o.insertSpaces) === true, insertFinalNewline: (o === null || o === void 0 ? void 0 : o.insertFinalNewline) === true, eol: '\n' };
return formatJSON(d.getText(), range, options).map(function (e) {
const options = { tabSize: o ? o.tabSize : 4, insertSpaces: o?.insertSpaces === true, insertFinalNewline: o?.insertFinalNewline === true, eol: '\n' };
return formatJSON(d.getText(), range, options).map(e => {
return TextEdit.replace(Range.create(d.positionAt(e.offset), d.positionAt(e.offset + e.length)), e.content);

@@ -66,0 +66,0 @@ });

@@ -28,3 +28,4 @@ import { JSONWorkerContribution, JSONPath, Segment, CompletionsCollector } from './jsonContributions';

CommentNotPermitted = 521,
SchemaResolveError = 768
SchemaResolveError = 768,
SchemaUnsupportedFeature = 769
}

@@ -31,0 +32,0 @@ export declare type ASTNode = ObjectASTNode | PropertyASTNode | ArrayASTNode | StringASTNode | NumberASTNode | BooleanASTNode | NullASTNode;

@@ -32,2 +32,3 @@ /*---------------------------------------------------------------------------------------------

ErrorCode[ErrorCode["SchemaResolveError"] = 768] = "SchemaResolveError";
ErrorCode[ErrorCode["SchemaUnsupportedFeature"] = 769] = "SchemaUnsupportedFeature";
})(ErrorCode || (ErrorCode = {}));

@@ -34,0 +35,0 @@ export var ClientCapabilities;

@@ -15,3 +15,3 @@ export declare type JSONSchemaRef = JSONSchema | boolean;

patternProperties?: JSONSchemaMap;
additionalProperties?: boolean | JSONSchemaRef;
additionalProperties?: JSONSchemaRef;
minProperties?: number;

@@ -26,3 +26,3 @@ maxProperties?: number;

uniqueItems?: boolean;
additionalItems?: boolean | JSONSchemaRef;
additionalItems?: JSONSchemaRef;
pattern?: string;

@@ -52,2 +52,21 @@ minLength?: number;

else?: JSONSchemaRef;
unevaluatedProperties?: boolean | JSONSchemaRef;
unevaluatedItems?: boolean | JSONSchemaRef;
minContains?: number;
maxContains?: number;
deprecated?: boolean;
dependentRequired?: {
[prop: string]: string[];
};
dependentSchemas?: JSONSchemaMap;
$defs?: {
[name: string]: JSONSchema;
};
$anchor?: string;
$recursiveRef?: string;
$recursiveAnchor?: string;
$vocabulary?: any;
prefixItems?: JSONSchemaRef[];
$dynamicRef?: string;
$dynamicAnchor?: string;
defaultSnippets?: {

@@ -54,0 +73,0 @@ label?: string;

@@ -5,24 +5,9 @@ /*---------------------------------------------------------------------------------------------

*--------------------------------------------------------------------------------------------*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
import * as Json from 'jsonc-parser';
import { isNumber, equals, isBoolean, isString, isDefined } from '../utils/objects';
import { isNumber, equals, isBoolean, isString, isDefined, isObject } from '../utils/objects';
import { extendedRegExp } from '../utils/strings';
import { ErrorCode, Diagnostic, DiagnosticSeverity, Range } from '../jsonLanguageTypes';
import * as nls from 'vscode-nls';
var localize = nls.loadMessageBundle();
var formats = {
const localize = nls.loadMessageBundle();
const formats = {
'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})$/ },

@@ -37,5 +22,4 @@ '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 },

};
var ASTNodeImpl = /** @class */ (function () {
function ASTNodeImpl(parent, offset, length) {
if (length === void 0) { length = 0; }
export class ASTNodeImpl {
constructor(parent, offset, length = 0) {
this.offset = offset;

@@ -45,115 +29,69 @@ this.length = length;

}
Object.defineProperty(ASTNodeImpl.prototype, "children", {
get: function () {
return [];
},
enumerable: false,
configurable: true
});
ASTNodeImpl.prototype.toString = function () {
get children() {
return [];
}
toString() {
return 'type: ' + this.type + ' (' + this.offset + '/' + this.length + ')' + (this.parent ? ' parent: {' + this.parent.toString() + '}' : '');
};
return ASTNodeImpl;
}());
export { ASTNodeImpl };
var NullASTNodeImpl = /** @class */ (function (_super) {
__extends(NullASTNodeImpl, _super);
function NullASTNodeImpl(parent, offset) {
var _this = _super.call(this, parent, offset) || this;
_this.type = 'null';
_this.value = null;
return _this;
}
return NullASTNodeImpl;
}(ASTNodeImpl));
export { NullASTNodeImpl };
var BooleanASTNodeImpl = /** @class */ (function (_super) {
__extends(BooleanASTNodeImpl, _super);
function BooleanASTNodeImpl(parent, boolValue, offset) {
var _this = _super.call(this, parent, offset) || this;
_this.type = 'boolean';
_this.value = boolValue;
return _this;
}
export class NullASTNodeImpl extends ASTNodeImpl {
constructor(parent, offset) {
super(parent, offset);
this.type = 'null';
this.value = null;
}
return BooleanASTNodeImpl;
}(ASTNodeImpl));
export { BooleanASTNodeImpl };
var ArrayASTNodeImpl = /** @class */ (function (_super) {
__extends(ArrayASTNodeImpl, _super);
function ArrayASTNodeImpl(parent, offset) {
var _this = _super.call(this, parent, offset) || this;
_this.type = 'array';
_this.items = [];
return _this;
}
export class BooleanASTNodeImpl extends ASTNodeImpl {
constructor(parent, boolValue, offset) {
super(parent, offset);
this.type = 'boolean';
this.value = boolValue;
}
Object.defineProperty(ArrayASTNodeImpl.prototype, "children", {
get: function () {
return this.items;
},
enumerable: false,
configurable: true
});
return ArrayASTNodeImpl;
}(ASTNodeImpl));
export { ArrayASTNodeImpl };
var NumberASTNodeImpl = /** @class */ (function (_super) {
__extends(NumberASTNodeImpl, _super);
function NumberASTNodeImpl(parent, offset) {
var _this = _super.call(this, parent, offset) || this;
_this.type = 'number';
_this.isInteger = true;
_this.value = Number.NaN;
return _this;
}
export class ArrayASTNodeImpl extends ASTNodeImpl {
constructor(parent, offset) {
super(parent, offset);
this.type = 'array';
this.items = [];
}
return NumberASTNodeImpl;
}(ASTNodeImpl));
export { NumberASTNodeImpl };
var StringASTNodeImpl = /** @class */ (function (_super) {
__extends(StringASTNodeImpl, _super);
function StringASTNodeImpl(parent, offset, length) {
var _this = _super.call(this, parent, offset, length) || this;
_this.type = 'string';
_this.value = '';
return _this;
get children() {
return this.items;
}
return StringASTNodeImpl;
}(ASTNodeImpl));
export { StringASTNodeImpl };
var PropertyASTNodeImpl = /** @class */ (function (_super) {
__extends(PropertyASTNodeImpl, _super);
function PropertyASTNodeImpl(parent, offset, keyNode) {
var _this = _super.call(this, parent, offset) || this;
_this.type = 'property';
_this.colonOffset = -1;
_this.keyNode = keyNode;
return _this;
}
export class NumberASTNodeImpl extends ASTNodeImpl {
constructor(parent, offset) {
super(parent, offset);
this.type = 'number';
this.isInteger = true;
this.value = Number.NaN;
}
Object.defineProperty(PropertyASTNodeImpl.prototype, "children", {
get: function () {
return this.valueNode ? [this.keyNode, this.valueNode] : [this.keyNode];
},
enumerable: false,
configurable: true
});
return PropertyASTNodeImpl;
}(ASTNodeImpl));
export { PropertyASTNodeImpl };
var ObjectASTNodeImpl = /** @class */ (function (_super) {
__extends(ObjectASTNodeImpl, _super);
function ObjectASTNodeImpl(parent, offset) {
var _this = _super.call(this, parent, offset) || this;
_this.type = 'object';
_this.properties = [];
return _this;
}
export class StringASTNodeImpl extends ASTNodeImpl {
constructor(parent, offset, length) {
super(parent, offset, length);
this.type = 'string';
this.value = '';
}
Object.defineProperty(ObjectASTNodeImpl.prototype, "children", {
get: function () {
return this.properties;
},
enumerable: false,
configurable: true
});
return ObjectASTNodeImpl;
}(ASTNodeImpl));
export { ObjectASTNodeImpl };
}
export class PropertyASTNodeImpl extends ASTNodeImpl {
constructor(parent, offset, keyNode) {
super(parent, offset);
this.type = 'property';
this.colonOffset = -1;
this.keyNode = keyNode;
}
get children() {
return this.valueNode ? [this.keyNode, this.valueNode] : [this.keyNode];
}
}
export class ObjectASTNodeImpl extends ASTNodeImpl {
constructor(parent, offset) {
super(parent, offset);
this.type = 'object';
this.properties = [];
}
get children() {
return this.properties;
}
}
export function asSchema(schema) {

@@ -170,5 +108,4 @@ if (isBoolean(schema)) {

})(EnumMatch || (EnumMatch = {}));
var SchemaCollector = /** @class */ (function () {
function SchemaCollector(focusOffset, exclude) {
if (focusOffset === void 0) { focusOffset = -1; }
class SchemaCollector {
constructor(focusOffset = -1, exclude) {
this.focusOffset = focusOffset;

@@ -178,35 +115,29 @@ this.exclude = exclude;

}
SchemaCollector.prototype.add = function (schema) {
add(schema) {
this.schemas.push(schema);
};
SchemaCollector.prototype.merge = function (other) {
}
merge(other) {
Array.prototype.push.apply(this.schemas, other.schemas);
};
SchemaCollector.prototype.include = function (node) {
}
include(node) {
return (this.focusOffset === -1 || contains(node, this.focusOffset)) && (node !== this.exclude);
};
SchemaCollector.prototype.newSub = function () {
}
newSub() {
return new SchemaCollector(-1, this.exclude);
};
return SchemaCollector;
}());
var NoOpSchemaCollector = /** @class */ (function () {
function NoOpSchemaCollector() {
}
Object.defineProperty(NoOpSchemaCollector.prototype, "schemas", {
get: function () { return []; },
enumerable: false,
configurable: true
});
NoOpSchemaCollector.prototype.add = function (schema) { };
NoOpSchemaCollector.prototype.merge = function (other) { };
NoOpSchemaCollector.prototype.include = function (node) { return true; };
NoOpSchemaCollector.prototype.newSub = function () { return this; };
NoOpSchemaCollector.instance = new NoOpSchemaCollector();
return NoOpSchemaCollector;
}());
var ValidationResult = /** @class */ (function () {
function ValidationResult() {
}
class NoOpSchemaCollector {
constructor() { }
get schemas() { return []; }
add(schema) { }
merge(other) { }
include(node) { return true; }
newSub() { return this; }
}
NoOpSchemaCollector.instance = new NoOpSchemaCollector();
export class ValidationResult {
constructor() {
this.problems = [];
this.propertiesMatches = 0;
this.processedProperties = new Set();
this.propertiesValueMatches = 0;

@@ -217,26 +148,24 @@ this.primaryValueMatches = 0;

}
ValidationResult.prototype.hasProblems = function () {
hasProblems() {
return !!this.problems.length;
};
ValidationResult.prototype.mergeAll = function (validationResults) {
for (var _i = 0, validationResults_1 = validationResults; _i < validationResults_1.length; _i++) {
var validationResult = validationResults_1[_i];
}
mergeAll(validationResults) {
for (const validationResult of validationResults) {
this.merge(validationResult);
}
};
ValidationResult.prototype.merge = function (validationResult) {
}
merge(validationResult) {
this.problems = this.problems.concat(validationResult.problems);
};
ValidationResult.prototype.mergeEnumValues = function (validationResult) {
}
mergeEnumValues(validationResult) {
if (!this.enumValueMatch && !validationResult.enumValueMatch && this.enumValues && validationResult.enumValues) {
this.enumValues = this.enumValues.concat(validationResult.enumValues);
for (var _i = 0, _a = this.problems; _i < _a.length; _i++) {
var error = _a[_i];
for (const error of this.problems) {
if (error.code === ErrorCode.EnumValueMismatch) {
error.message = localize('enumWarning', 'Value is not accepted. Valid values: {0}.', this.enumValues.map(function (v) { return JSON.stringify(v); }).join(', '));
error.message = localize('enumWarning', 'Value is not accepted. Valid values: {0}.', this.enumValues.map(v => JSON.stringify(v)).join(', '));
}
}
}
};
ValidationResult.prototype.mergePropertyMatch = function (propertyValidationResult) {
}
mergePropertyMatch(propertyValidationResult) {
this.merge(propertyValidationResult);

@@ -250,5 +179,8 @@ this.propertiesMatches++;

}
};
ValidationResult.prototype.compare = function (other) {
var hasProblems = this.hasProblems();
}
mergeProcessedProperties(validationResult) {
validationResult.processedProperties.forEach(p => this.processedProperties.add(p));
}
compare(other) {
const hasProblems = this.hasProblems();
if (hasProblems !== other.hasProblems()) {

@@ -267,8 +199,5 @@ return hasProblems ? -1 : 1;

return this.propertiesMatches - other.propertiesMatches;
};
return ValidationResult;
}());
export { ValidationResult };
export function newJSONDocument(root, diagnostics) {
if (diagnostics === void 0) { diagnostics = []; }
}
}
export function newJSONDocument(root, diagnostics = []) {
return new JSONDocument(root, diagnostics, []);

@@ -282,10 +211,7 @@ }

}
export function contains(node, offset, includeRightBound) {
if (includeRightBound === void 0) { includeRightBound = false; }
export function contains(node, offset, includeRightBound = false) {
return offset >= node.offset && offset < (node.offset + node.length) || includeRightBound && offset === (node.offset + node.length);
}
var JSONDocument = /** @class */ (function () {
function JSONDocument(root, syntaxErrors, comments) {
if (syntaxErrors === void 0) { syntaxErrors = []; }
if (comments === void 0) { comments = []; }
export class JSONDocument {
constructor(root, syntaxErrors = [], comments = []) {
this.root = root;

@@ -295,4 +221,3 @@ this.syntaxErrors = syntaxErrors;

}
JSONDocument.prototype.getNodeFromOffset = function (offset, includeRightBound) {
if (includeRightBound === void 0) { includeRightBound = false; }
getNodeFromOffset(offset, includeRightBound = false) {
if (this.root) {

@@ -302,11 +227,11 @@ return Json.findNodeAtOffset(this.root, offset, includeRightBound);

return undefined;
};
JSONDocument.prototype.visit = function (visitor) {
}
visit(visitor) {
if (this.root) {
var doVisit_1 = function (node) {
var ctn = visitor(node);
var children = node.children;
const doVisit = (node) => {
let ctn = visitor(node);
const children = node.children;
if (Array.isArray(children)) {
for (var i = 0; i < children.length && ctn; i++) {
ctn = doVisit_1(children[i]);
for (let i = 0; i < children.length && ctn; i++) {
ctn = doVisit(children[i]);
}

@@ -316,21 +241,18 @@ }

};
doVisit_1(this.root);
doVisit(this.root);
}
};
JSONDocument.prototype.validate = function (textDocument, schema, severity) {
if (severity === void 0) { severity = DiagnosticSeverity.Warning; }
}
validate(textDocument, schema, severity = DiagnosticSeverity.Warning) {
if (this.root && schema) {
var validationResult = new ValidationResult();
const validationResult = new ValidationResult();
validate(this.root, schema, validationResult, NoOpSchemaCollector.instance);
return validationResult.problems.map(function (p) {
var _a;
var range = Range.create(textDocument.positionAt(p.location.offset), textDocument.positionAt(p.location.offset + p.location.length));
return Diagnostic.create(range, p.message, (_a = p.severity) !== null && _a !== void 0 ? _a : severity, p.code);
return validationResult.problems.map(p => {
const range = Range.create(textDocument.positionAt(p.location.offset), textDocument.positionAt(p.location.offset + p.location.length));
return Diagnostic.create(range, p.message, p.severity ?? severity, p.code);
});
}
return undefined;
};
JSONDocument.prototype.getMatchingSchemas = function (schema, focusOffset, exclude) {
if (focusOffset === void 0) { focusOffset = -1; }
var matchingSchemas = new SchemaCollector(focusOffset, exclude);
}
getMatchingSchemas(schema, focusOffset = -1, exclude) {
const matchingSchemas = new SchemaCollector(focusOffset, exclude);
if (this.root && schema) {

@@ -340,6 +262,4 @@ validate(this.root, schema, new ValidationResult(), matchingSchemas);

return matchingSchemas.schemas;
};
return JSONDocument;
}());
export { JSONDocument };
}
}
function validate(n, schema, validationResult, matchingSchemas) {

@@ -349,20 +269,21 @@ if (!n || !matchingSchemas.include(n)) {

}
var node = n;
if (n.type === 'property') {
return validate(n.valueNode, schema, validationResult, matchingSchemas);
}
const node = n;
_validateNode();
switch (node.type) {
case 'object':
_validateObjectNode(node, schema, validationResult, matchingSchemas);
_validateObjectNode(node);
break;
case 'array':
_validateArrayNode(node, schema, validationResult, matchingSchemas);
_validateArrayNode(node);
break;
case 'string':
_validateStringNode(node, schema, validationResult, matchingSchemas);
_validateStringNode(node);
break;
case 'number':
_validateNumberNode(node, schema, validationResult, matchingSchemas);
_validateNumberNode(node);
break;
case 'property':
return validate(node.valueNode, schema, validationResult, matchingSchemas);
}
_validateNode();
matchingSchemas.add({ node: node, schema: schema });

@@ -390,11 +311,10 @@ function _validateNode() {

if (Array.isArray(schema.allOf)) {
for (var _i = 0, _a = schema.allOf; _i < _a.length; _i++) {
var subSchemaRef = _a[_i];
for (const subSchemaRef of schema.allOf) {
validate(node, asSchema(subSchemaRef), validationResult, matchingSchemas);
}
}
var notSchema = asSchema(schema.not);
const notSchema = asSchema(schema.not);
if (notSchema) {
var subValidationResult = new ValidationResult();
var subMatchingSchemas = matchingSchemas.newSub();
const subValidationResult = new ValidationResult();
const subMatchingSchemas = matchingSchemas.newSub();
validate(node, notSchema, subValidationResult, subMatchingSchemas);

@@ -407,4 +327,3 @@ if (!subValidationResult.hasProblems()) {

}
for (var _b = 0, _c = subMatchingSchemas.schemas; _b < _c.length; _b++) {
var ms = _c[_b];
for (const ms of subMatchingSchemas.schemas) {
ms.inverted = !ms.inverted;

@@ -414,11 +333,10 @@ matchingSchemas.add(ms);

}
var testAlternatives = function (alternatives, maxOneMatch) {
var matches = [];
const testAlternatives = (alternatives, maxOneMatch) => {
const matches = [];
// remember the best match that is used for error messages
var bestMatch = undefined;
for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) {
var subSchemaRef = alternatives_1[_i];
var subSchema = asSchema(subSchemaRef);
var subValidationResult = new ValidationResult();
var subMatchingSchemas = matchingSchemas.newSub();
let bestMatch = undefined;
for (const subSchemaRef of alternatives) {
const subSchema = asSchema(subSchemaRef);
const subValidationResult = new ValidationResult();
const subMatchingSchemas = matchingSchemas.newSub();
validate(node, subSchema, subValidationResult, subMatchingSchemas);

@@ -437,5 +355,6 @@ if (!subValidationResult.hasProblems()) {

bestMatch.validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches;
bestMatch.validationResult.mergeProcessedProperties(subValidationResult);
}
else {
var compareResult = subValidationResult.compare(bestMatch.validationResult);
const compareResult = subValidationResult.compare(bestMatch.validationResult);
if (compareResult > 0) {

@@ -463,2 +382,3 @@ // our node is the best matching so far

validationResult.propertiesValueMatches += bestMatch.validationResult.propertiesValueMatches;
validationResult.mergeProcessedProperties(bestMatch.validationResult);
matchingSchemas.merge(bestMatch.matchingSchemas);

@@ -474,5 +394,5 @@ }

}
var testBranch = function (schema) {
var subValidationResult = new ValidationResult();
var subMatchingSchemas = matchingSchemas.newSub();
const testBranch = (schema) => {
const subValidationResult = new ValidationResult();
const subMatchingSchemas = matchingSchemas.newSub();
validate(node, asSchema(schema), subValidationResult, subMatchingSchemas);

@@ -482,10 +402,12 @@ validationResult.merge(subValidationResult);

validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches;
validationResult.mergeProcessedProperties(subValidationResult);
matchingSchemas.merge(subMatchingSchemas);
};
var testCondition = function (ifSchema, thenSchema, elseSchema) {
var subSchema = asSchema(ifSchema);
var subValidationResult = new ValidationResult();
var subMatchingSchemas = matchingSchemas.newSub();
const testCondition = (ifSchema, thenSchema, elseSchema) => {
const subSchema = asSchema(ifSchema);
const subValidationResult = new ValidationResult();
const subMatchingSchemas = matchingSchemas.newSub();
validate(node, subSchema, subValidationResult, subMatchingSchemas);
matchingSchemas.merge(subMatchingSchemas);
validationResult.mergeProcessedProperties(subValidationResult);
if (!subValidationResult.hasProblems()) {

@@ -500,3 +422,3 @@ if (thenSchema) {

};
var ifSchema = asSchema(schema.if);
const ifSchema = asSchema(schema.if);
if (ifSchema) {

@@ -506,6 +428,5 @@ testCondition(ifSchema, asSchema(schema.then), asSchema(schema.else));

if (Array.isArray(schema.enum)) {
var val = getNodeValue(node);
var enumValueMatch = false;
for (var _d = 0, _e = schema.enum; _d < _e.length; _d++) {
var e = _e[_d];
const val = getNodeValue(node);
let enumValueMatch = false;
for (const e of schema.enum) {
if (equals(val, e)) {

@@ -522,3 +443,3 @@ enumValueMatch = true;

code: ErrorCode.EnumValueMismatch,
message: schema.errorMessage || localize('enumWarning', 'Value is not accepted. Valid values: {0}.', schema.enum.map(function (v) { return JSON.stringify(v); }).join(', '))
message: schema.errorMessage || localize('enumWarning', 'Value is not accepted. Valid values: {0}.', schema.enum.map(v => JSON.stringify(v)).join(', '))
});

@@ -528,3 +449,3 @@ }

if (isDefined(schema.const)) {
var val = getNodeValue(node);
const val = getNodeValue(node);
if (!equals(val, schema.const)) {

@@ -543,7 +464,9 @@ validationResult.problems.push({

}
if (schema.deprecationMessage && node.parent) {
let deprecationMessage = schema.deprecationMessage;
if ((deprecationMessage || schema.deprecated) && node.parent) {
deprecationMessage = deprecationMessage || localize('deprecated', 'Value is deprecated');
validationResult.problems.push({
location: { offset: node.parent.offset, length: node.parent.length },
severity: DiagnosticSeverity.Warning,
message: schema.deprecationMessage,
message: deprecationMessage,
code: ErrorCode.Deprecated

@@ -553,10 +476,9 @@ });

}
function _validateNumberNode(node, schema, validationResult, matchingSchemas) {
var val = node.value;
function _validateNumberNode(node) {
const val = node.value;
function normalizeFloats(float) {
var _a;
var parts = /^(-?\d+)(?:\.(\d+))?(?:e([-+]\d+))?$/.exec(float.toString());
const parts = /^(-?\d+)(?:\.(\d+))?(?:e([-+]\d+))?$/.exec(float.toString());
return parts && {
value: Number(parts[1] + (parts[2] || '')),
multiplier: (((_a = parts[2]) === null || _a === void 0 ? void 0 : _a.length) || 0) - (parseInt(parts[3]) || 0)
multiplier: (parts[2]?.length || 0) - (parseInt(parts[3]) || 0)
};

@@ -566,3 +488,3 @@ }

if (isNumber(schema.multipleOf)) {
var remainder = -1;
let remainder = -1;
if (Number.isInteger(schema.multipleOf)) {

@@ -572,6 +494,6 @@ remainder = val % schema.multipleOf;

else {
var normMultipleOf = normalizeFloats(schema.multipleOf);
var normValue = normalizeFloats(val);
let normMultipleOf = normalizeFloats(schema.multipleOf);
let normValue = normalizeFloats(val);
if (normMultipleOf && normValue) {
var multiplier = Math.pow(10, Math.abs(normValue.multiplier - normMultipleOf.multiplier));
const multiplier = 10 ** Math.abs(normValue.multiplier - normMultipleOf.multiplier);
if (normValue.multiplier < normMultipleOf.multiplier) {

@@ -608,3 +530,3 @@ normValue.value *= multiplier;

}
var exclusiveMinimum = getExclusiveLimit(schema.minimum, schema.exclusiveMinimum);
const exclusiveMinimum = getExclusiveLimit(schema.minimum, schema.exclusiveMinimum);
if (isNumber(exclusiveMinimum) && val <= exclusiveMinimum) {

@@ -616,3 +538,3 @@ validationResult.problems.push({

}
var exclusiveMaximum = getExclusiveLimit(schema.maximum, schema.exclusiveMaximum);
const exclusiveMaximum = getExclusiveLimit(schema.maximum, schema.exclusiveMaximum);
if (isNumber(exclusiveMaximum) && val >= exclusiveMaximum) {

@@ -624,3 +546,3 @@ validationResult.problems.push({

}
var minimum = getLimit(schema.minimum, schema.exclusiveMinimum);
const minimum = getLimit(schema.minimum, schema.exclusiveMinimum);
if (isNumber(minimum) && val < minimum) {

@@ -632,3 +554,3 @@ validationResult.problems.push({

}
var maximum = getLimit(schema.maximum, schema.exclusiveMaximum);
const maximum = getLimit(schema.maximum, schema.exclusiveMaximum);
if (isNumber(maximum) && val > maximum) {

@@ -641,3 +563,3 @@ validationResult.problems.push({

}
function _validateStringNode(node, schema, validationResult, matchingSchemas) {
function _validateStringNode(node) {
if (isNumber(schema.minLength) && node.value.length < schema.minLength) {

@@ -656,4 +578,4 @@ validationResult.problems.push({

if (isString(schema.pattern)) {
var regex = extendedRegExp(schema.pattern);
if (!(regex === null || regex === void 0 ? void 0 : regex.test(node.value))) {
const regex = extendedRegExp(schema.pattern);
if (!(regex?.test(node.value))) {
validationResult.problems.push({

@@ -670,3 +592,3 @@ location: { offset: node.offset, length: node.length },

{
var errorMessage = void 0;
let errorMessage;
if (!node.value) {

@@ -676,3 +598,3 @@ errorMessage = localize('uriEmpty', 'URI expected.');

else {
var match = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/.exec(node.value);
const match = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/.exec(node.value);
if (!match) {

@@ -701,3 +623,3 @@ errorMessage = localize('uriMissing', 'URI is expected.');

case 'ipv6':
var format = formats[schema.format];
const format = formats[schema.format];
if (!node.value || !format.pattern.exec(node.value)) {

@@ -713,10 +635,22 @@ validationResult.problems.push({

}
function _validateArrayNode(node, schema, validationResult, matchingSchemas) {
if (Array.isArray(schema.items)) {
var subSchemas = schema.items;
for (var index = 0; index < subSchemas.length; index++) {
var subSchemaRef = subSchemas[index];
var subSchema = asSchema(subSchemaRef);
var itemValidationResult = new ValidationResult();
var item = node.items[index];
function _validateArrayNode(node) {
let prefixItemsSchemas;
let additionalItemSchema;
let isSchema_2020_12 = Array.isArray(schema.prefixItems) || (schema.items !== undefined && !Array.isArray(schema.items) && schema.additionalItems === undefined);
if (isSchema_2020_12) {
prefixItemsSchemas = schema.prefixItems;
additionalItemSchema = !Array.isArray(schema.items) ? schema.items : undefined;
}
else {
prefixItemsSchemas = Array.isArray(schema.items) ? schema.items : undefined;
additionalItemSchema = !Array.isArray(schema.items) ? schema.items : schema.additionalItems;
}
let index = 0;
if (prefixItemsSchemas !== undefined) {
const max = Math.min(prefixItemsSchemas.length, node.items.length);
for (; index < max; index++) {
const subSchemaRef = prefixItemsSchemas[index];
const subSchema = asSchema(subSchemaRef);
const itemValidationResult = new ValidationResult();
const item = node.items[index];
if (item) {

@@ -726,41 +660,42 @@ validate(item, subSchema, itemValidationResult, matchingSchemas);

}
else if (node.items.length >= subSchemas.length) {
validationResult.propertiesValueMatches++;
}
validationResult.processedProperties.add(String(index));
}
if (node.items.length > subSchemas.length) {
if (typeof schema.additionalItems === 'object') {
for (var i = subSchemas.length; i < node.items.length; i++) {
var itemValidationResult = new ValidationResult();
validate(node.items[i], schema.additionalItems, itemValidationResult, matchingSchemas);
validationResult.mergePropertyMatch(itemValidationResult);
}
}
else if (schema.additionalItems === false) {
}
if (additionalItemSchema !== undefined && index < node.items.length) {
if (typeof additionalItemSchema === 'boolean') {
if (additionalItemSchema === false) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: localize('additionalItemsWarning', 'Array has too many items according to schema. Expected {0} or fewer.', subSchemas.length)
message: localize('additionalItemsWarning', 'Array has too many items according to schema. Expected {0} or fewer.', index)
});
}
for (; index < node.items.length; index++) {
validationResult.processedProperties.add(String(index));
validationResult.propertiesValueMatches++;
}
}
}
else {
var itemSchema = asSchema(schema.items);
if (itemSchema) {
for (var _i = 0, _a = node.items; _i < _a.length; _i++) {
var item = _a[_i];
var itemValidationResult = new ValidationResult();
validate(item, itemSchema, itemValidationResult, matchingSchemas);
else {
for (; index < node.items.length; index++) {
const itemValidationResult = new ValidationResult();
validate(node.items[index], additionalItemSchema, itemValidationResult, matchingSchemas);
validationResult.mergePropertyMatch(itemValidationResult);
validationResult.processedProperties.add(String(index));
}
}
}
var containsSchema = asSchema(schema.contains);
const containsSchema = asSchema(schema.contains);
if (containsSchema) {
var doesContain = node.items.some(function (item) {
var itemValidationResult = new ValidationResult();
let containsCount = 0;
for (let index = 0; index < node.items.length; index++) {
const item = node.items[index];
const itemValidationResult = new ValidationResult();
validate(item, containsSchema, itemValidationResult, NoOpSchemaCollector.instance);
return !itemValidationResult.hasProblems();
});
if (!doesContain) {
if (!itemValidationResult.hasProblems()) {
containsCount++;
if (isSchema_2020_12) {
validationResult.processedProperties.add(String(index));
}
}
}
if (containsCount === 0 && !isNumber(schema.minContains)) {
validationResult.problems.push({

@@ -771,3 +706,35 @@ location: { offset: node.offset, length: node.length },

}
if (isNumber(schema.minContains) && containsCount < schema.minContains) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: localize('minContainsWarning', 'Array has too few items that match the contains contraint. Expected {0} or more.', schema.minContains)
});
}
if (isNumber(schema.maxContains) && containsCount > schema.maxContains) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: localize('maxContainsWarning', 'Array has too many items that match the contains contraint. Expected {0} or less.', schema.maxContains)
});
}
}
const unevaluatedItems = schema.unevaluatedItems;
if (unevaluatedItems !== undefined) {
for (let i = 0; i < node.items.length; i++) {
if (!validationResult.processedProperties.has(String(i))) {
if (unevaluatedItems === false) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: localize('unevaluatedItemsWarning', 'Item does not match any validation rule from the array.')
});
}
else {
const itemValidationResult = new ValidationResult();
validate(node.items[i], schema.additionalItems, itemValidationResult, matchingSchemas);
validationResult.mergePropertyMatch(itemValidationResult);
}
}
validationResult.processedProperties.add(String(i));
validationResult.propertiesValueMatches++;
}
}
if (isNumber(schema.minItems) && node.items.length < schema.minItems) {

@@ -786,5 +753,5 @@ validationResult.problems.push({

if (schema.uniqueItems === true) {
var values_1 = getNodeValue(node);
var duplicates = values_1.some(function (value, index) {
return index !== values_1.lastIndexOf(value);
const values = getNodeValue(node);
const duplicates = values.some((value, index) => {
return index !== values.lastIndexOf(value);
});

@@ -799,17 +766,15 @@ if (duplicates) {

}
function _validateObjectNode(node, schema, validationResult, matchingSchemas) {
var seenKeys = Object.create(null);
var unprocessedProperties = [];
for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
var propertyNode = _a[_i];
var key = propertyNode.keyNode.value;
function _validateObjectNode(node) {
const seenKeys = Object.create(null);
const unprocessedProperties = new Set();
for (const propertyNode of node.properties) {
const key = propertyNode.keyNode.value;
seenKeys[key] = propertyNode.valueNode;
unprocessedProperties.push(key);
unprocessedProperties.add(key);
}
if (Array.isArray(schema.required)) {
for (var _b = 0, _c = schema.required; _b < _c.length; _b++) {
var propertyName = _c[_b];
for (const propertyName of schema.required) {
if (!seenKeys[propertyName]) {
var keyNode = node.parent && node.parent.type === 'property' && node.parent.keyNode;
var location = keyNode ? { offset: keyNode.offset, length: keyNode.length } : { offset: node.offset, length: 1 };
const keyNode = node.parent && node.parent.type === 'property' && node.parent.keyNode;
const location = keyNode ? { offset: keyNode.offset, length: keyNode.length } : { offset: node.offset, length: 1 };
validationResult.problems.push({

@@ -822,19 +787,15 @@ location: location,

}
var propertyProcessed = function (prop) {
var index = unprocessedProperties.indexOf(prop);
while (index >= 0) {
unprocessedProperties.splice(index, 1);
index = unprocessedProperties.indexOf(prop);
}
const propertyProcessed = (prop) => {
unprocessedProperties.delete(prop);
validationResult.processedProperties.add(prop);
};
if (schema.properties) {
for (var _d = 0, _e = Object.keys(schema.properties); _d < _e.length; _d++) {
var propertyName = _e[_d];
for (const propertyName of Object.keys(schema.properties)) {
propertyProcessed(propertyName);
var propertySchema = schema.properties[propertyName];
var child = seenKeys[propertyName];
const propertySchema = schema.properties[propertyName];
const child = seenKeys[propertyName];
if (child) {
if (isBoolean(propertySchema)) {
if (!propertySchema) {
var propertyNode = child.parent;
const propertyNode = child.parent;
validationResult.problems.push({

@@ -851,3 +812,3 @@ location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },

else {
var propertyValidationResult = new ValidationResult();
const propertyValidationResult = new ValidationResult();
validate(child, propertySchema, propertyValidationResult, matchingSchemas);

@@ -860,53 +821,45 @@ validationResult.mergePropertyMatch(propertyValidationResult);

if (schema.patternProperties) {
for (var _f = 0, _g = Object.keys(schema.patternProperties); _f < _g.length; _f++) {
var propertyPattern = _g[_f];
var regex = extendedRegExp(propertyPattern);
for (var _h = 0, _j = unprocessedProperties.slice(0); _h < _j.length; _h++) {
var propertyName = _j[_h];
if (regex === null || regex === void 0 ? void 0 : regex.test(propertyName)) {
propertyProcessed(propertyName);
var child = seenKeys[propertyName];
if (child) {
var propertySchema = schema.patternProperties[propertyPattern];
if (isBoolean(propertySchema)) {
if (!propertySchema) {
var propertyNode = child.parent;
validationResult.problems.push({
location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
});
for (const propertyPattern of Object.keys(schema.patternProperties)) {
const regex = extendedRegExp(propertyPattern);
if (regex) {
const processed = [];
for (const propertyName of unprocessedProperties) {
if (regex.test(propertyName)) {
processed.push(propertyName);
const child = seenKeys[propertyName];
if (child) {
const propertySchema = schema.patternProperties[propertyPattern];
if (isBoolean(propertySchema)) {
if (!propertySchema) {
const propertyNode = child.parent;
validationResult.problems.push({
location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
});
}
else {
validationResult.propertiesMatches++;
validationResult.propertiesValueMatches++;
}
}
else {
validationResult.propertiesMatches++;
validationResult.propertiesValueMatches++;
const propertyValidationResult = new ValidationResult();
validate(child, propertySchema, propertyValidationResult, matchingSchemas);
validationResult.mergePropertyMatch(propertyValidationResult);
}
}
else {
var propertyValidationResult = new ValidationResult();
validate(child, propertySchema, propertyValidationResult, matchingSchemas);
validationResult.mergePropertyMatch(propertyValidationResult);
}
}
}
processed.forEach(propertyProcessed);
}
}
}
if (typeof schema.additionalProperties === 'object') {
for (var _k = 0, unprocessedProperties_1 = unprocessedProperties; _k < unprocessedProperties_1.length; _k++) {
var propertyName = unprocessedProperties_1[_k];
var child = seenKeys[propertyName];
const additionalProperties = schema.additionalProperties;
if (additionalProperties !== undefined && additionalProperties !== true) {
for (const propertyName of unprocessedProperties) {
propertyProcessed(propertyName);
const child = seenKeys[propertyName];
if (child) {
var propertyValidationResult = new ValidationResult();
validate(child, schema.additionalProperties, propertyValidationResult, matchingSchemas);
validationResult.mergePropertyMatch(propertyValidationResult);
}
}
}
else if (schema.additionalProperties === false) {
if (unprocessedProperties.length > 0) {
for (var _l = 0, unprocessedProperties_2 = unprocessedProperties; _l < unprocessedProperties_2.length; _l++) {
var propertyName = unprocessedProperties_2[_l];
var child = seenKeys[propertyName];
if (child) {
var propertyNode = child.parent;
if (additionalProperties === false) {
const propertyNode = child.parent;
validationResult.problems.push({

@@ -917,5 +870,35 @@ location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },

}
else {
const propertyValidationResult = new ValidationResult();
validate(child, additionalProperties, propertyValidationResult, matchingSchemas);
validationResult.mergePropertyMatch(propertyValidationResult);
}
}
}
}
const unevaluatedProperties = schema.unevaluatedProperties;
if (unevaluatedProperties !== undefined && unevaluatedProperties !== true) {
const processed = [];
for (const propertyName of unprocessedProperties) {
if (!validationResult.processedProperties.has(propertyName)) {
processed.push(propertyName);
const child = seenKeys[propertyName];
if (child) {
if (unevaluatedProperties === false) {
const propertyNode = child.parent;
validationResult.problems.push({
location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
});
}
else {
const propertyValidationResult = new ValidationResult();
validate(child, unevaluatedProperties, propertyValidationResult, matchingSchemas);
validationResult.mergePropertyMatch(propertyValidationResult);
}
}
}
}
processed.forEach(propertyProcessed);
}
if (isNumber(schema.maxProperties)) {

@@ -937,38 +920,32 @@ if (node.properties.length > schema.maxProperties) {

}
if (schema.dependentRequired) {
for (const key in schema.dependentRequired) {
const prop = seenKeys[key];
const propertyDeps = schema.dependentRequired[key];
if (prop && Array.isArray(propertyDeps)) {
_validatePropertyDependencies(key, propertyDeps);
}
}
}
if (schema.dependentSchemas) {
for (const key in schema.dependentSchemas) {
const prop = seenKeys[key];
const propertyDeps = schema.dependentSchemas[key];
if (prop && isObject(propertyDeps)) {
_validatePropertyDependencies(key, propertyDeps);
}
}
}
if (schema.dependencies) {
for (var _m = 0, _o = Object.keys(schema.dependencies); _m < _o.length; _m++) {
var key = _o[_m];
var prop = seenKeys[key];
for (const key in schema.dependencies) {
const prop = seenKeys[key];
if (prop) {
var propertyDep = schema.dependencies[key];
if (Array.isArray(propertyDep)) {
for (var _p = 0, propertyDep_1 = propertyDep; _p < propertyDep_1.length; _p++) {
var requiredProp = propertyDep_1[_p];
if (!seenKeys[requiredProp]) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: localize('RequiredDependentPropWarning', 'Object is missing property {0} required by property {1}.', requiredProp, key)
});
}
else {
validationResult.propertiesValueMatches++;
}
}
}
else {
var propertySchema = asSchema(propertyDep);
if (propertySchema) {
var propertyValidationResult = new ValidationResult();
validate(node, propertySchema, propertyValidationResult, matchingSchemas);
validationResult.mergePropertyMatch(propertyValidationResult);
}
}
_validatePropertyDependencies(key, schema.dependencies[key]);
}
}
}
var propertyNames = asSchema(schema.propertyNames);
const propertyNames = asSchema(schema.propertyNames);
if (propertyNames) {
for (var _q = 0, _r = node.properties; _q < _r.length; _q++) {
var f = _r[_q];
var key = f.keyNode;
for (const f of node.properties) {
const key = f.keyNode;
if (key) {

@@ -979,15 +956,38 @@ validate(key, propertyNames, validationResult, NoOpSchemaCollector.instance);

}
function _validatePropertyDependencies(key, propertyDep) {
if (Array.isArray(propertyDep)) {
for (const requiredProp of propertyDep) {
if (!seenKeys[requiredProp]) {
validationResult.problems.push({
location: { offset: node.offset, length: node.length },
message: localize('RequiredDependentPropWarning', 'Object is missing property {0} required by property {1}.', requiredProp, key)
});
}
else {
validationResult.propertiesValueMatches++;
}
}
}
else {
const propertySchema = asSchema(propertyDep);
if (propertySchema) {
const propertyValidationResult = new ValidationResult();
validate(node, propertySchema, propertyValidationResult, matchingSchemas);
validationResult.mergePropertyMatch(propertyValidationResult);
}
}
}
}
}
export function parse(textDocument, config) {
var problems = [];
var lastProblemOffset = -1;
var text = textDocument.getText();
var scanner = Json.createScanner(text, false);
var commentRanges = config && config.collectComments ? [] : undefined;
const problems = [];
let lastProblemOffset = -1;
const text = textDocument.getText();
const scanner = Json.createScanner(text, false);
const commentRanges = config && config.collectComments ? [] : undefined;
function _scanNext() {
while (true) {
var token_1 = scanner.scan();
const token = scanner.scan();
_checkScanError();
switch (token_1) {
switch (token) {
case 12 /* LineCommentTrivia */:

@@ -1003,3 +1003,3 @@ case 13 /* BlockCommentTrivia */:

default:
return token_1;
return token;
}

@@ -1015,6 +1015,5 @@ }

}
function _errorAtRange(message, code, startOffset, endOffset, severity) {
if (severity === void 0) { severity = DiagnosticSeverity.Error; }
function _errorAtRange(message, code, startOffset, endOffset, severity = DiagnosticSeverity.Error) {
if (problems.length === 0 || startOffset !== lastProblemOffset) {
var range = Range.create(textDocument.positionAt(startOffset), textDocument.positionAt(endOffset));
const range = Range.create(textDocument.positionAt(startOffset), textDocument.positionAt(endOffset));
problems.push(Diagnostic.create(range, message, severity, code, textDocument.languageId));

@@ -1024,8 +1023,5 @@ lastProblemOffset = startOffset;

}
function _error(message, code, node, skipUntilAfter, skipUntil) {
if (node === void 0) { node = undefined; }
if (skipUntilAfter === void 0) { skipUntilAfter = []; }
if (skipUntil === void 0) { skipUntil = []; }
var start = scanner.getTokenOffset();
var end = scanner.getTokenOffset() + scanner.getTokenLength();
function _error(message, code, node = undefined, skipUntilAfter = [], skipUntil = []) {
let start = scanner.getTokenOffset();
let end = scanner.getTokenOffset() + scanner.getTokenLength();
if (start === end && start > 0) {

@@ -1043,12 +1039,12 @@ start--;

if (skipUntilAfter.length + skipUntil.length > 0) {
var token_2 = scanner.getToken();
while (token_2 !== 17 /* EOF */) {
if (skipUntilAfter.indexOf(token_2) !== -1) {
let token = scanner.getToken();
while (token !== 17 /* EOF */) {
if (skipUntilAfter.indexOf(token) !== -1) {
_scanNext();
break;
}
else if (skipUntil.indexOf(token_2) !== -1) {
else if (skipUntil.indexOf(token) !== -1) {
break;
}
token_2 = _scanNext();
token = _scanNext();
}

@@ -1092,6 +1088,6 @@ }

}
var node = new ArrayASTNodeImpl(parent, scanner.getTokenOffset());
const node = new ArrayASTNodeImpl(parent, scanner.getTokenOffset());
_scanNext(); // consume OpenBracketToken
var count = 0;
var needsComma = false;
const count = 0;
let needsComma = false;
while (scanner.getToken() !== 4 /* CloseBracketToken */ && scanner.getToken() !== 17 /* EOF */) {

@@ -1102,3 +1098,3 @@ if (scanner.getToken() === 5 /* CommaToken */) {

}
var commaOffset = scanner.getTokenOffset();
const commaOffset = scanner.getTokenOffset();
_scanNext(); // consume comma

@@ -1115,3 +1111,3 @@ if (scanner.getToken() === 4 /* CloseBracketToken */) {

}
var item = _parseValue(node);
const item = _parseValue(node);
if (!item) {

@@ -1130,6 +1126,6 @@ _error(localize('PropertyExpected', 'Value expected'), ErrorCode.ValueExpected, undefined, [], [4 /* CloseBracketToken */, 5 /* CommaToken */]);

}
var keyPlaceholder = new StringASTNodeImpl(undefined, 0, 0);
const keyPlaceholder = new StringASTNodeImpl(undefined, 0, 0);
function _parseProperty(parent, keysSeen) {
var node = new PropertyASTNodeImpl(parent, scanner.getTokenOffset(), keyPlaceholder);
var key = _parseString(node);
const node = new PropertyASTNodeImpl(parent, scanner.getTokenOffset(), keyPlaceholder);
let key = _parseString(node);
if (!key) {

@@ -1139,3 +1135,3 @@ if (scanner.getToken() === 16 /* Unknown */) {

_error(localize('DoubleQuotesExpected', 'Property keys must be doublequoted'), ErrorCode.Undefined);
var keyNode = new StringASTNodeImpl(node, scanner.getTokenOffset(), scanner.getTokenLength());
const keyNode = new StringASTNodeImpl(node, scanner.getTokenOffset(), scanner.getTokenLength());
keyNode.value = scanner.getTokenValue();

@@ -1150,6 +1146,6 @@ key = keyNode;

node.keyNode = key;
var seen = keysSeen[key.value];
const seen = keysSeen[key.value];
if (seen) {
_errorAtRange(localize('DuplicateKeyWarning', "Duplicate object key"), ErrorCode.DuplicateKey, node.keyNode.offset, node.keyNode.offset + node.keyNode.length, DiagnosticSeverity.Warning);
if (typeof seen === 'object') {
if (isObject(seen)) {
_errorAtRange(localize('DuplicateKeyWarning', "Duplicate object key"), ErrorCode.DuplicateKey, seen.keyNode.offset, seen.keyNode.offset + seen.keyNode.length, DiagnosticSeverity.Warning);

@@ -1173,3 +1169,3 @@ }

}
var value = _parseValue(node);
const value = _parseValue(node);
if (!value) {

@@ -1186,6 +1182,6 @@ return _error(localize('ValueExpected', 'Value expected'), ErrorCode.ValueExpected, node, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);

}
var node = new ObjectASTNodeImpl(parent, scanner.getTokenOffset());
var keysSeen = Object.create(null);
const node = new ObjectASTNodeImpl(parent, scanner.getTokenOffset());
const keysSeen = Object.create(null);
_scanNext(); // consume OpenBraceToken
var needsComma = false;
let needsComma = false;
while (scanner.getToken() !== 2 /* CloseBraceToken */ && scanner.getToken() !== 17 /* EOF */) {

@@ -1196,3 +1192,3 @@ if (scanner.getToken() === 5 /* CommaToken */) {

}
var commaOffset = scanner.getTokenOffset();
const commaOffset = scanner.getTokenOffset();
_scanNext(); // consume comma

@@ -1209,3 +1205,3 @@ if (scanner.getToken() === 2 /* CloseBraceToken */) {

}
var property = _parseProperty(node, keysSeen);
const property = _parseProperty(node, keysSeen);
if (!property) {

@@ -1228,3 +1224,3 @@ _error(localize('PropertyExpected', 'Property expected'), ErrorCode.PropertyExpected, undefined, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);

}
var node = new StringASTNodeImpl(parent, scanner.getTokenOffset());
const node = new StringASTNodeImpl(parent, scanner.getTokenOffset());
node.value = scanner.getTokenValue();

@@ -1237,7 +1233,7 @@ return _finalize(node, true);

}
var node = new NumberASTNodeImpl(parent, scanner.getTokenOffset());
const node = new NumberASTNodeImpl(parent, scanner.getTokenOffset());
if (scanner.getTokenError() === 0 /* None */) {
var tokenValue = scanner.getTokenValue();
const tokenValue = scanner.getTokenValue();
try {
var numberValue = JSON.parse(tokenValue);
const numberValue = JSON.parse(tokenValue);
if (!isNumber(numberValue)) {

@@ -1256,3 +1252,3 @@ return _error(localize('InvalidNumberFormat', 'Invalid number format.'), ErrorCode.Undefined, node);

function _parseLiteral(parent) {
var node;
let node;
switch (scanner.getToken()) {

@@ -1272,4 +1268,4 @@ case 7 /* NullKeyword */:

}
var _root = undefined;
var token = _scanNext();
let _root = undefined;
const token = _scanNext();
if (token !== 17 /* EOF */) {

@@ -1276,0 +1272,0 @@ _root = _parseValue(_root);

@@ -6,4 +6,4 @@ /*---------------------------------------------------------------------------------------------

import * as nls from 'vscode-nls';
var localize = nls.loadMessageBundle();
export var schemaContributions = {
const localize = nls.loadMessageBundle();
export const schemaContributions = {
schemaAssociations: [],

@@ -466,3 +466,3 @@ schemas: {

};
var descriptions = {
const descriptions = {
id: localize('schema.json.id', "A unique identifier for the schema."),

@@ -515,10 +515,10 @@ $schema: localize('schema.json.$schema', "The schema to verify this document against."),

};
for (var schemaName in schemaContributions.schemas) {
var schema = schemaContributions.schemas[schemaName];
for (var property in schema.properties) {
var propertyObject = schema.properties[property];
for (const schemaName in schemaContributions.schemas) {
const schema = schemaContributions.schemas[schemaName];
for (const property in schema.properties) {
let propertyObject = schema.properties[property];
if (typeof propertyObject === 'boolean') {
propertyObject = schema.properties[property] = {};
}
var description = descriptions[property];
const description = descriptions[property];
if (description) {

@@ -528,5 +528,5 @@ propertyObject['description'] = description;

else {
console.log("".concat(property, ": localize('schema.json.").concat(property, "', \"\")"));
console.log(`${property}: localize('schema.json.${property}', "")`);
}
}
}

@@ -12,10 +12,7 @@ /*---------------------------------------------------------------------------------------------

import * as nls from 'vscode-nls';
var localize = nls.loadMessageBundle();
var valueCommitCharacters = [',', '}', ']'];
var propertyCommitCharacters = [':'];
var JSONCompletion = /** @class */ (function () {
function JSONCompletion(schemaService, contributions, promiseConstructor, clientCapabilities) {
if (contributions === void 0) { contributions = []; }
if (promiseConstructor === void 0) { promiseConstructor = Promise; }
if (clientCapabilities === void 0) { clientCapabilities = {}; }
const localize = nls.loadMessageBundle();
const valueCommitCharacters = [',', '}', ']'];
const propertyCommitCharacters = [':'];
export class JSONCompletion {
constructor(schemaService, contributions = [], promiseConstructor = Promise, clientCapabilities = {}) {
this.schemaService = schemaService;

@@ -26,7 +23,7 @@ this.contributions = contributions;

}
JSONCompletion.prototype.doResolve = function (item) {
for (var i = this.contributions.length - 1; i >= 0; i--) {
var resolveCompletion = this.contributions[i].resolveCompletion;
doResolve(item) {
for (let i = this.contributions.length - 1; i >= 0; i--) {
const resolveCompletion = this.contributions[i].resolveCompletion;
if (resolveCompletion) {
var resolver = resolveCompletion(item);
const resolver = resolveCompletion(item);
if (resolver) {

@@ -38,12 +35,11 @@ return resolver;

return this.promiseConstructor.resolve(item);
};
JSONCompletion.prototype.doComplete = function (document, position, doc) {
var _this = this;
var result = {
}
doComplete(document, position, doc) {
const result = {
items: [],
isIncomplete: false
};
var text = document.getText();
var offset = document.offsetAt(position);
var node = doc.getNodeFromOffset(offset, true);
const text = document.getText();
const offset = document.offsetAt(position);
let node = doc.getNodeFromOffset(offset, true);
if (this.isInComment(document, node ? node.offset : 0, offset)) {

@@ -53,3 +49,3 @@ return Promise.resolve(result);

if (node && (offset === node.offset + node.length) && offset > 0) {
var ch = text[offset - 1];
const ch = text[offset - 1];
if (node.type === 'object' && ch === '}' || node.type === 'array' && ch === ']') {

@@ -60,4 +56,4 @@ // after ] or }

}
var currentWord = this.getCurrentWord(document, offset);
var overwriteRange;
const currentWord = this.getCurrentWord(document, offset);
let overwriteRange;
if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {

@@ -67,3 +63,3 @@ overwriteRange = Range.create(document.positionAt(node.offset), document.positionAt(node.offset + node.length));

else {
var overwriteStart = offset - currentWord.length;
let overwriteStart = offset - currentWord.length;
if (overwriteStart > 0 && text[overwriteStart - 1] === '"') {

@@ -74,12 +70,12 @@ overwriteStart--;

}
var supportsCommitCharacters = false; //this.doesSupportsCommitCharacters(); disabled for now, waiting for new API: https://github.com/microsoft/vscode/issues/42544
var proposed = {};
var collector = {
add: function (suggestion) {
var label = suggestion.label;
var existing = proposed[label];
const supportsCommitCharacters = false; //this.doesSupportsCommitCharacters(); disabled for now, waiting for new API: https://github.com/microsoft/vscode/issues/42544
const proposed = {};
const collector = {
add: (suggestion) => {
let label = suggestion.label;
const existing = proposed[label];
if (!existing) {
label = label.replace(/[\n]/g, '↵');
if (label.length > 60) {
var shortendedLabel = label.substr(0, 57).trim() + '...';
const shortendedLabel = label.substr(0, 57).trim() + '...';
if (!proposed[shortendedLabel]) {

@@ -108,23 +104,23 @@ label = shortendedLabel;

},
setAsIncomplete: function () {
setAsIncomplete: () => {
result.isIncomplete = true;
},
error: function (message) {
error: (message) => {
console.error(message);
},
log: function (message) {
log: (message) => {
console.log(message);
},
getNumberOfProposals: function () {
getNumberOfProposals: () => {
return result.items.length;
}
};
return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
var collectionPromises = [];
var addValue = true;
var currentKey = '';
var currentProperty = undefined;
return this.schemaService.getSchemaForResource(document.uri, doc).then((schema) => {
const collectionPromises = [];
let addValue = true;
let currentKey = '';
let currentProperty = undefined;
if (node) {
if (node.type === 'string') {
var parent = node.parent;
const parent = node.parent;
if (parent && parent.type === 'property' && parent.keyNode === node) {

@@ -147,4 +143,4 @@ addValue = !parent.valueNode;

// don't suggest properties that are already present
var properties = node.properties;
properties.forEach(function (p) {
const properties = node.properties;
properties.forEach(p => {
if (!currentProperty || currentProperty !== p) {

@@ -154,17 +150,17 @@ proposed[p.keyNode.value] = CompletionItem.create('__');

});
var separatorAfter_1 = '';
let separatorAfter = '';
if (addValue) {
separatorAfter_1 = _this.evaluateSeparatorAfter(document, document.offsetAt(overwriteRange.end));
separatorAfter = this.evaluateSeparatorAfter(document, document.offsetAt(overwriteRange.end));
}
if (schema) {
// property proposals with schema
_this.getPropertyCompletions(schema, doc, node, addValue, separatorAfter_1, collector);
this.getPropertyCompletions(schema, doc, node, addValue, separatorAfter, collector);
}
else {
// property proposals without schema
_this.getSchemaLessPropertyCompletions(doc, node, currentKey, collector);
this.getSchemaLessPropertyCompletions(doc, node, currentKey, collector);
}
var location_1 = Parser.getNodePath(node);
_this.contributions.forEach(function (contribution) {
var collectPromise = contribution.collectPropertyCompletions(document.uri, location_1, currentWord, addValue, separatorAfter_1 === '', collector);
const location = Parser.getNodePath(node);
this.contributions.forEach((contribution) => {
const collectPromise = contribution.collectPropertyCompletions(document.uri, location, currentWord, addValue, separatorAfter === '', collector);
if (collectPromise) {

@@ -177,4 +173,4 @@ collectionPromises.push(collectPromise);

kind: CompletionItemKind.Property,
label: _this.getLabelForValue(currentWord),
insertText: _this.getInsertTextForProperty(currentWord, undefined, false, separatorAfter_1),
label: this.getLabelForValue(currentWord),
insertText: this.getInsertTextForProperty(currentWord, undefined, false, separatorAfter),
insertTextFormat: InsertTextFormat.Snippet, documentation: '',

@@ -186,22 +182,22 @@ });

// proposals for values
var types = {};
const types = {};
if (schema) {
// value proposals with schema
_this.getValueCompletions(schema, doc, node, offset, document, collector, types);
this.getValueCompletions(schema, doc, node, offset, document, collector, types);
}
else {
// value proposals without schema
_this.getSchemaLessValueCompletions(doc, node, offset, document, collector);
this.getSchemaLessValueCompletions(doc, node, offset, document, collector);
}
if (_this.contributions.length > 0) {
_this.getContributedValueCompletions(doc, node, offset, document, collector, collectionPromises);
if (this.contributions.length > 0) {
this.getContributedValueCompletions(doc, node, offset, document, collector, collectionPromises);
}
return _this.promiseConstructor.all(collectionPromises).then(function () {
return this.promiseConstructor.all(collectionPromises).then(() => {
if (collector.getNumberOfProposals() === 0) {
var offsetForSeparator = offset;
let offsetForSeparator = offset;
if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
offsetForSeparator = node.offset + node.length;
}
var separatorAfter = _this.evaluateSeparatorAfter(document, offsetForSeparator);
_this.addFillerValueCompletions(types, separatorAfter, collector);
const separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator);
this.addFillerValueCompletions(types, separatorAfter, collector);
}

@@ -211,20 +207,19 @@ return result;

});
};
JSONCompletion.prototype.getPropertyCompletions = function (schema, doc, node, addValue, separatorAfter, collector) {
var _this = this;
var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset);
matchingSchemas.forEach(function (s) {
}
getPropertyCompletions(schema, doc, node, addValue, separatorAfter, collector) {
const matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset);
matchingSchemas.forEach((s) => {
if (s.node === node && !s.inverted) {
var schemaProperties_1 = s.schema.properties;
if (schemaProperties_1) {
Object.keys(schemaProperties_1).forEach(function (key) {
var propertySchema = schemaProperties_1[key];
const schemaProperties = s.schema.properties;
if (schemaProperties) {
Object.keys(schemaProperties).forEach((key) => {
const propertySchema = schemaProperties[key];
if (typeof propertySchema === 'object' && !propertySchema.deprecationMessage && !propertySchema.doNotSuggest) {
var proposal = {
const proposal = {
kind: CompletionItemKind.Property,
label: key,
insertText: _this.getInsertTextForProperty(key, propertySchema, addValue, separatorAfter),
insertText: this.getInsertTextForProperty(key, propertySchema, addValue, separatorAfter),
insertTextFormat: InsertTextFormat.Snippet,
filterText: _this.getFilterTextForValue(key),
documentation: _this.fromMarkup(propertySchema.markdownDescription) || propertySchema.description || '',
filterText: this.getFilterTextForValue(key),
documentation: this.fromMarkup(propertySchema.markdownDescription) || propertySchema.description || '',
};

@@ -234,3 +229,3 @@ if (propertySchema.suggestSortText !== undefined) {

}
if (proposal.insertText && endsWith(proposal.insertText, "$1".concat(separatorAfter))) {
if (proposal.insertText && endsWith(proposal.insertText, `$1${separatorAfter}`)) {
proposal.command = {

@@ -245,18 +240,17 @@ title: 'Suggest',

}
var schemaPropertyNames_1 = s.schema.propertyNames;
if (typeof schemaPropertyNames_1 === 'object' && !schemaPropertyNames_1.deprecationMessage && !schemaPropertyNames_1.doNotSuggest) {
var propertyNameCompletionItem = function (name, enumDescription) {
if (enumDescription === void 0) { enumDescription = undefined; }
var proposal = {
const schemaPropertyNames = s.schema.propertyNames;
if (typeof schemaPropertyNames === 'object' && !schemaPropertyNames.deprecationMessage && !schemaPropertyNames.doNotSuggest) {
const propertyNameCompletionItem = (name, enumDescription = undefined) => {
const proposal = {
kind: CompletionItemKind.Property,
label: name,
insertText: _this.getInsertTextForProperty(name, undefined, addValue, separatorAfter),
insertText: this.getInsertTextForProperty(name, undefined, addValue, separatorAfter),
insertTextFormat: InsertTextFormat.Snippet,
filterText: _this.getFilterTextForValue(name),
documentation: enumDescription || _this.fromMarkup(schemaPropertyNames_1.markdownDescription) || schemaPropertyNames_1.description || '',
filterText: this.getFilterTextForValue(name),
documentation: enumDescription || this.fromMarkup(schemaPropertyNames.markdownDescription) || schemaPropertyNames.description || '',
};
if (schemaPropertyNames_1.suggestSortText !== undefined) {
proposal.sortText = schemaPropertyNames_1.suggestSortText;
if (schemaPropertyNames.suggestSortText !== undefined) {
proposal.sortText = schemaPropertyNames.suggestSortText;
}
if (proposal.insertText && endsWith(proposal.insertText, "$1".concat(separatorAfter))) {
if (proposal.insertText && endsWith(proposal.insertText, `$1${separatorAfter}`)) {
proposal.command = {

@@ -269,16 +263,16 @@ title: 'Suggest',

};
if (schemaPropertyNames_1.enum) {
for (var i = 0; i < schemaPropertyNames_1.enum.length; i++) {
var enumDescription = undefined;
if (schemaPropertyNames_1.markdownEnumDescriptions && i < schemaPropertyNames_1.markdownEnumDescriptions.length) {
enumDescription = _this.fromMarkup(schemaPropertyNames_1.markdownEnumDescriptions[i]);
if (schemaPropertyNames.enum) {
for (let i = 0; i < schemaPropertyNames.enum.length; i++) {
let enumDescription = undefined;
if (schemaPropertyNames.markdownEnumDescriptions && i < schemaPropertyNames.markdownEnumDescriptions.length) {
enumDescription = this.fromMarkup(schemaPropertyNames.markdownEnumDescriptions[i]);
}
else if (schemaPropertyNames_1.enumDescriptions && i < schemaPropertyNames_1.enumDescriptions.length) {
enumDescription = schemaPropertyNames_1.enumDescriptions[i];
else if (schemaPropertyNames.enumDescriptions && i < schemaPropertyNames.enumDescriptions.length) {
enumDescription = schemaPropertyNames.enumDescriptions[i];
}
propertyNameCompletionItem(schemaPropertyNames_1.enum[i], enumDescription);
propertyNameCompletionItem(schemaPropertyNames.enum[i], enumDescription);
}
}
if (schemaPropertyNames_1.const) {
propertyNameCompletionItem(schemaPropertyNames_1.const);
if (schemaPropertyNames.const) {
propertyNameCompletionItem(schemaPropertyNames.const);
}

@@ -288,14 +282,13 @@ }

});
};
JSONCompletion.prototype.getSchemaLessPropertyCompletions = function (doc, node, currentKey, collector) {
var _this = this;
var collectCompletionsForSimilarObject = function (obj) {
obj.properties.forEach(function (p) {
var key = p.keyNode.value;
}
getSchemaLessPropertyCompletions(doc, node, currentKey, collector) {
const collectCompletionsForSimilarObject = (obj) => {
obj.properties.forEach((p) => {
const key = p.keyNode.value;
collector.add({
kind: CompletionItemKind.Property,
label: key,
insertText: _this.getInsertTextForValue(key, ''),
insertText: this.getInsertTextForValue(key, ''),
insertTextFormat: InsertTextFormat.Snippet,
filterText: _this.getFilterTextForValue(key),
filterText: this.getFilterTextForValue(key),
documentation: ''

@@ -308,5 +301,5 @@ });

// if the object is a property value, check the tree for other objects that hang under a property of the same name
var parentKey_1 = node.parent.keyNode.value;
doc.visit(function (n) {
if (n.type === 'property' && n !== node.parent && n.keyNode.value === parentKey_1 && n.valueNode && n.valueNode.type === 'object') {
const parentKey = node.parent.keyNode.value;
doc.visit(n => {
if (n.type === 'property' && n !== node.parent && n.keyNode.value === parentKey && n.valueNode && n.valueNode.type === 'object') {
collectCompletionsForSimilarObject(n.valueNode);

@@ -319,3 +312,3 @@ }

// if the object is in an array, use all other array elements as similar objects
node.parent.items.forEach(function (n) {
node.parent.items.forEach(n => {
if (n.type === 'object' && n !== node) {

@@ -336,6 +329,5 @@ collectCompletionsForSimilarObject(n);

}
};
JSONCompletion.prototype.getSchemaLessValueCompletions = function (doc, node, offset, document, collector) {
var _this = this;
var offsetForSeparator = offset;
}
getSchemaLessValueCompletions(doc, node, offset, document, collector) {
let offsetForSeparator = offset;
if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {

@@ -362,9 +354,9 @@ offsetForSeparator = node.offset + node.length;

}
var separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator);
var collectSuggestionsForValues = function (value) {
const separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator);
const collectSuggestionsForValues = (value) => {
if (value.parent && !Parser.contains(value.parent, offset, true)) {
collector.add({
kind: _this.getSuggestionKind(value.type),
label: _this.getLabelTextForMatchingNode(value, document),
insertText: _this.getInsertTextForMatchingNode(value, document, separatorAfter),
kind: this.getSuggestionKind(value.type),
label: this.getLabelTextForMatchingNode(value, document),
insertText: this.getInsertTextForMatchingNode(value, document, separatorAfter),
insertTextFormat: InsertTextFormat.Snippet, documentation: ''

@@ -374,3 +366,3 @@ });

if (value.type === 'boolean') {
_this.addBooleanValueCompletion(!value.value, separatorAfter, collector);
this.addBooleanValueCompletion(!value.value, separatorAfter, collector);
}

@@ -380,3 +372,3 @@ };

if (offset > (node.colonOffset || 0)) {
var valueNode = node.valueNode;
const valueNode = node.valueNode;
if (valueNode && (offset > (valueNode.offset + valueNode.length) || valueNode.type === 'object' || valueNode.type === 'array')) {

@@ -386,5 +378,5 @@ return;

// suggest values at the same key
var parentKey_2 = node.keyNode.value;
doc.visit(function (n) {
if (n.type === 'property' && n.keyNode.value === parentKey_2 && n.valueNode) {
const parentKey = node.keyNode.value;
doc.visit(n => {
if (n.type === 'property' && n.keyNode.value === parentKey && n.valueNode) {
collectSuggestionsForValues(n.valueNode);

@@ -394,3 +386,3 @@ }

});
if (parentKey_2 === '$schema' && node.parent && !node.parent.parent) {
if (parentKey === '$schema' && node.parent && !node.parent.parent) {
this.addDollarSchemaCompletions(separatorAfter, collector);

@@ -403,5 +395,5 @@ }

// suggest items of an array at the same key
var parentKey_3 = node.parent.keyNode.value;
doc.visit(function (n) {
if (n.type === 'property' && n.keyNode.value === parentKey_3 && n.valueNode && n.valueNode.type === 'array') {
const parentKey = node.parent.keyNode.value;
doc.visit((n) => {
if (n.type === 'property' && n.keyNode.value === parentKey && n.valueNode && n.valueNode.type === 'array') {
n.valueNode.items.forEach(collectSuggestionsForValues);

@@ -417,7 +409,7 @@ }

}
};
JSONCompletion.prototype.getValueCompletions = function (schema, doc, node, offset, document, collector, types) {
var offsetForSeparator = offset;
var parentKey = undefined;
var valueNode = undefined;
}
getValueCompletions(schema, doc, node, offset, document, collector, types) {
let offsetForSeparator = offset;
let parentKey = undefined;
let valueNode = undefined;
if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {

@@ -433,4 +425,4 @@ offsetForSeparator = node.offset + node.length;

if ((node.type === 'property') && offset > (node.colonOffset || 0)) {
var valueNode_1 = node.valueNode;
if (valueNode_1 && offset > (valueNode_1.offset + valueNode_1.length)) {
const valueNode = node.valueNode;
if (valueNode && offset > (valueNode.offset + valueNode.length)) {
return; // we are past the value node

@@ -442,10 +434,9 @@ }

if (node && (parentKey !== undefined || node.type === 'array')) {
var separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator);
var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset, valueNode);
for (var _i = 0, matchingSchemas_1 = matchingSchemas; _i < matchingSchemas_1.length; _i++) {
var s = matchingSchemas_1[_i];
const separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator);
const matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset, valueNode);
for (const s of matchingSchemas) {
if (s.node === node && !s.inverted && s.schema) {
if (node.type === 'array' && s.schema.items) {
if (Array.isArray(s.schema.items)) {
var index = this.findItemAtOffset(node, document, offset);
const index = this.findItemAtOffset(node, document, offset);
if (index < s.schema.items.length) {

@@ -460,5 +451,5 @@ this.addSchemaValueCompletions(s.schema.items[index], separatorAfter, collector, types);

if (parentKey !== undefined) {
var propertyMatched = false;
let propertyMatched = false;
if (s.schema.properties) {
var propertySchema = s.schema.properties[parentKey];
const propertySchema = s.schema.properties[parentKey];
if (propertySchema) {

@@ -470,8 +461,7 @@ propertyMatched = true;

if (s.schema.patternProperties && !propertyMatched) {
for (var _a = 0, _b = Object.keys(s.schema.patternProperties); _a < _b.length; _a++) {
var pattern = _b[_a];
var regex = extendedRegExp(pattern);
if (regex === null || regex === void 0 ? void 0 : regex.test(parentKey)) {
for (const pattern of Object.keys(s.schema.patternProperties)) {
const regex = extendedRegExp(pattern);
if (regex?.test(parentKey)) {
propertyMatched = true;
var propertySchema = s.schema.patternProperties[pattern];
const propertySchema = s.schema.patternProperties[pattern];
this.addSchemaValueCompletions(propertySchema, separatorAfter, collector, types);

@@ -482,3 +472,3 @@ }

if (s.schema.additionalProperties && !propertyMatched) {
var propertySchema = s.schema.additionalProperties;
const propertySchema = s.schema.additionalProperties;
this.addSchemaValueCompletions(propertySchema, separatorAfter, collector, types);

@@ -500,7 +490,7 @@ }

}
};
JSONCompletion.prototype.getContributedValueCompletions = function (doc, node, offset, document, collector, collectionPromises) {
}
getContributedValueCompletions(doc, node, offset, document, collector, collectionPromises) {
if (!node) {
this.contributions.forEach(function (contribution) {
var collectPromise = contribution.collectDefaultCompletions(document.uri, collector);
this.contributions.forEach((contribution) => {
const collectPromise = contribution.collectDefaultCompletions(document.uri, collector);
if (collectPromise) {

@@ -516,8 +506,8 @@ collectionPromises.push(collectPromise);

if (node && (node.type === 'property') && offset > (node.colonOffset || 0)) {
var parentKey_4 = node.keyNode.value;
var valueNode = node.valueNode;
const parentKey = node.keyNode.value;
const valueNode = node.valueNode;
if ((!valueNode || offset <= (valueNode.offset + valueNode.length)) && node.parent) {
var location_2 = Parser.getNodePath(node.parent);
this.contributions.forEach(function (contribution) {
var collectPromise = contribution.collectValueCompletions(document.uri, location_2, parentKey_4, collector);
const location = Parser.getNodePath(node.parent);
this.contributions.forEach((contribution) => {
const collectPromise = contribution.collectValueCompletions(document.uri, location, parentKey, collector);
if (collectPromise) {

@@ -530,5 +520,4 @@ collectionPromises.push(collectPromise);

}
};
JSONCompletion.prototype.addSchemaValueCompletions = function (schema, separatorAfter, collector, types) {
var _this = this;
}
addSchemaValueCompletions(schema, separatorAfter, collector, types) {
if (typeof schema === 'object') {

@@ -539,20 +528,18 @@ this.addEnumValueCompletions(schema, separatorAfter, collector);

if (Array.isArray(schema.allOf)) {
schema.allOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
schema.allOf.forEach(s => this.addSchemaValueCompletions(s, separatorAfter, collector, types));
}
if (Array.isArray(schema.anyOf)) {
schema.anyOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
schema.anyOf.forEach(s => this.addSchemaValueCompletions(s, separatorAfter, collector, types));
}
if (Array.isArray(schema.oneOf)) {
schema.oneOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
schema.oneOf.forEach(s => this.addSchemaValueCompletions(s, separatorAfter, collector, types));
}
}
};
JSONCompletion.prototype.addDefaultValueCompletions = function (schema, separatorAfter, collector, arrayDepth) {
var _this = this;
if (arrayDepth === void 0) { arrayDepth = 0; }
var hasProposals = false;
}
addDefaultValueCompletions(schema, separatorAfter, collector, arrayDepth = 0) {
let hasProposals = false;
if (isDefined(schema.default)) {
var type = schema.type;
var value = schema.default;
for (var i = arrayDepth; i > 0; i--) {
let type = schema.type;
let value = schema.default;
for (let i = arrayDepth; i > 0; i--) {
value = [value];

@@ -571,6 +558,6 @@ type = 'array';

if (Array.isArray(schema.examples)) {
schema.examples.forEach(function (example) {
var type = schema.type;
var value = example;
for (var i = arrayDepth; i > 0; i--) {
schema.examples.forEach(example => {
let type = schema.type;
let value = example;
for (let i = arrayDepth; i > 0; i--) {
value = [value];

@@ -580,5 +567,5 @@ type = 'array';

collector.add({
kind: _this.getSuggestionKind(type),
label: _this.getLabelForValue(value),
insertText: _this.getInsertTextForValue(value, separatorAfter),
kind: this.getSuggestionKind(type),
label: this.getLabelForValue(value),
insertText: this.getInsertTextForValue(value, separatorAfter),
insertTextFormat: InsertTextFormat.Snippet

@@ -590,21 +577,21 @@ });

if (Array.isArray(schema.defaultSnippets)) {
schema.defaultSnippets.forEach(function (s) {
var type = schema.type;
var value = s.body;
var label = s.label;
var insertText;
var filterText;
schema.defaultSnippets.forEach(s => {
let type = schema.type;
let value = s.body;
let label = s.label;
let insertText;
let filterText;
if (isDefined(value)) {
var type_1 = schema.type;
for (var i = arrayDepth; i > 0; i--) {
let type = schema.type;
for (let i = arrayDepth; i > 0; i--) {
value = [value];
type_1 = 'array';
type = 'array';
}
insertText = _this.getInsertTextForSnippetValue(value, separatorAfter);
filterText = _this.getFilterTextForSnippetValue(value);
label = label || _this.getLabelForSnippetValue(value);
insertText = this.getInsertTextForSnippetValue(value, separatorAfter);
filterText = this.getFilterTextForSnippetValue(value);
label = label || this.getLabelForSnippetValue(value);
}
else if (typeof s.bodyText === 'string') {
var prefix = '', suffix = '', indent = '';
for (var i = arrayDepth; i > 0; i--) {
let prefix = '', suffix = '', indent = '';
for (let i = arrayDepth; i > 0; i--) {
prefix = prefix + indent + '[\n';

@@ -623,8 +610,8 @@ suffix = suffix + '\n' + indent + ']';

collector.add({
kind: _this.getSuggestionKind(type),
label: label,
documentation: _this.fromMarkup(s.markdownDescription) || s.description,
insertText: insertText,
kind: this.getSuggestionKind(type),
label,
documentation: this.fromMarkup(s.markdownDescription) || s.description,
insertText,
insertTextFormat: InsertTextFormat.Snippet,
filterText: filterText
filterText
});

@@ -637,4 +624,4 @@ hasProposals = true;

}
};
JSONCompletion.prototype.addEnumValueCompletions = function (schema, separatorAfter, collector) {
}
addEnumValueCompletions(schema, separatorAfter, collector) {
if (isDefined(schema.const)) {

@@ -650,5 +637,5 @@ collector.add({

if (Array.isArray(schema.enum)) {
for (var i = 0, length = schema.enum.length; i < length; i++) {
var enm = schema.enum[i];
var documentation = this.fromMarkup(schema.markdownDescription) || schema.description;
for (let i = 0, length = schema.enum.length; i < length; i++) {
const enm = schema.enum[i];
let documentation = this.fromMarkup(schema.markdownDescription) || schema.description;
if (schema.markdownEnumDescriptions && i < schema.markdownEnumDescriptions.length && this.doesSupportMarkdown()) {

@@ -665,14 +652,14 @@ documentation = this.fromMarkup(schema.markdownEnumDescriptions[i]);

insertTextFormat: InsertTextFormat.Snippet,
documentation: documentation
documentation
});
}
}
};
JSONCompletion.prototype.collectTypes = function (schema, types) {
}
collectTypes(schema, types) {
if (Array.isArray(schema.enum) || isDefined(schema.const)) {
return;
}
var type = schema.type;
const type = schema.type;
if (Array.isArray(type)) {
type.forEach(function (t) { return types[t] = true; });
type.forEach(t => types[t] = true);
}

@@ -682,4 +669,4 @@ else if (type) {

}
};
JSONCompletion.prototype.addFillerValueCompletions = function (types, separatorAfter, collector) {
}
addFillerValueCompletions(types, separatorAfter, collector) {
if (types['object']) {

@@ -705,4 +692,4 @@ collector.add({

}
};
JSONCompletion.prototype.addBooleanValueCompletion = function (value, separatorAfter, collector) {
}
addBooleanValueCompletion(value, separatorAfter, collector) {
collector.add({

@@ -715,4 +702,4 @@ kind: this.getSuggestionKind('boolean'),

});
};
JSONCompletion.prototype.addNullValueCompletion = function (separatorAfter, collector) {
}
addNullValueCompletion(separatorAfter, collector) {
collector.add({

@@ -725,31 +712,30 @@ kind: this.getSuggestionKind('null'),

});
};
JSONCompletion.prototype.addDollarSchemaCompletions = function (separatorAfter, collector) {
var _this = this;
var schemaIds = this.schemaService.getRegisteredSchemaIds(function (schema) { return schema === 'http' || schema === 'https'; });
schemaIds.forEach(function (schemaId) { return collector.add({
}
addDollarSchemaCompletions(separatorAfter, collector) {
const schemaIds = this.schemaService.getRegisteredSchemaIds(schema => schema === 'http' || schema === 'https');
schemaIds.forEach(schemaId => collector.add({
kind: CompletionItemKind.Module,
label: _this.getLabelForValue(schemaId),
filterText: _this.getFilterTextForValue(schemaId),
insertText: _this.getInsertTextForValue(schemaId, separatorAfter),
label: this.getLabelForValue(schemaId),
filterText: this.getFilterTextForValue(schemaId),
insertText: this.getInsertTextForValue(schemaId, separatorAfter),
insertTextFormat: InsertTextFormat.Snippet, documentation: ''
}); });
};
JSONCompletion.prototype.getLabelForValue = function (value) {
}));
}
getLabelForValue(value) {
return JSON.stringify(value);
};
JSONCompletion.prototype.getFilterTextForValue = function (value) {
}
getFilterTextForValue(value) {
return JSON.stringify(value);
};
JSONCompletion.prototype.getFilterTextForSnippetValue = function (value) {
}
getFilterTextForSnippetValue(value) {
return JSON.stringify(value).replace(/\$\{\d+:([^}]+)\}|\$\d+/g, '$1');
};
JSONCompletion.prototype.getLabelForSnippetValue = function (value) {
var label = JSON.stringify(value);
}
getLabelForSnippetValue(value) {
const label = JSON.stringify(value);
return label.replace(/\$\{\d+:([^}]+)\}|\$\d+/g, '$1');
};
JSONCompletion.prototype.getInsertTextForPlainText = function (text) {
}
getInsertTextForPlainText(text) {
return text.replace(/[\\\$\}]/g, '\\$&'); // escape $, \ and }
};
JSONCompletion.prototype.getInsertTextForValue = function (value, separatorAfter) {
}
getInsertTextForValue(value, separatorAfter) {
var text = JSON.stringify(value, null, '\t');

@@ -763,5 +749,5 @@ if (text === '{}') {

return this.getInsertTextForPlainText(text + separatorAfter);
};
JSONCompletion.prototype.getInsertTextForSnippetValue = function (value, separatorAfter) {
var replacer = function (value) {
}
getInsertTextForSnippetValue(value, separatorAfter) {
const replacer = (value) => {
if (typeof value === 'string') {

@@ -775,4 +761,4 @@ if (value[0] === '^') {

return stringifyObject(value, '', replacer) + separatorAfter;
};
JSONCompletion.prototype.getInsertTextForGuessedValue = function (value, separatorAfter) {
}
getInsertTextForGuessedValue(value, separatorAfter) {
switch (typeof value) {

@@ -785,3 +771,3 @@ case 'object':

case 'string':
var snippetValue = JSON.stringify(value);
let snippetValue = JSON.stringify(value);
snippetValue = snippetValue.substr(1, snippetValue.length - 2); // remove quotes

@@ -795,6 +781,6 @@ snippetValue = this.getInsertTextForPlainText(snippetValue); // escape \ and }

return this.getInsertTextForValue(value, separatorAfter);
};
JSONCompletion.prototype.getSuggestionKind = function (type) {
}
getSuggestionKind(type) {
if (Array.isArray(type)) {
var array = type;
const array = type;
type = array.length > 0 ? array[0] : undefined;

@@ -811,4 +797,4 @@ }

}
};
JSONCompletion.prototype.getLabelTextForMatchingNode = function (node, document) {
}
getLabelTextForMatchingNode(node, document) {
switch (node.type) {

@@ -820,7 +806,7 @@ case 'array':

default:
var content = document.getText().substr(node.offset, node.length);
const content = document.getText().substr(node.offset, node.length);
return content;
}
};
JSONCompletion.prototype.getInsertTextForMatchingNode = function (node, document, separatorAfter) {
}
getInsertTextForMatchingNode(node, document, separatorAfter) {
switch (node.type) {

@@ -832,18 +818,18 @@ case 'array':

default:
var content = document.getText().substr(node.offset, node.length) + separatorAfter;
const content = document.getText().substr(node.offset, node.length) + separatorAfter;
return this.getInsertTextForPlainText(content);
}
};
JSONCompletion.prototype.getInsertTextForProperty = function (key, propertySchema, addValue, separatorAfter) {
var propertyText = this.getInsertTextForValue(key, '');
}
getInsertTextForProperty(key, propertySchema, addValue, separatorAfter) {
const propertyText = this.getInsertTextForValue(key, '');
if (!addValue) {
return propertyText;
}
var resultText = propertyText + ': ';
var value;
var nValueProposals = 0;
const resultText = propertyText + ': ';
let value;
let nValueProposals = 0;
if (propertySchema) {
if (Array.isArray(propertySchema.defaultSnippets)) {
if (propertySchema.defaultSnippets.length === 1) {
var body = propertySchema.defaultSnippets[0].body;
const body = propertySchema.defaultSnippets[0].body;
if (isDefined(body)) {

@@ -912,4 +898,4 @@ value = this.getInsertTextForSnippetValue(body, '');

return resultText + value + separatorAfter;
};
JSONCompletion.prototype.getCurrentWord = function (document, offset) {
}
getCurrentWord(document, offset) {
var i = offset - 1;

@@ -921,7 +907,7 @@ var text = document.getText();

return text.substring(i + 1, offset);
};
JSONCompletion.prototype.evaluateSeparatorAfter = function (document, offset) {
var scanner = Json.createScanner(document.getText(), true);
}
evaluateSeparatorAfter(document, offset) {
const scanner = Json.createScanner(document.getText(), true);
scanner.setPosition(offset);
var token = scanner.scan();
const token = scanner.scan();
switch (token) {

@@ -936,11 +922,11 @@ case 5 /* CommaToken */:

}
};
JSONCompletion.prototype.findItemAtOffset = function (node, document, offset) {
var scanner = Json.createScanner(document.getText(), true);
var children = node.items;
for (var i = children.length - 1; i >= 0; i--) {
var child = children[i];
}
findItemAtOffset(node, document, offset) {
const scanner = Json.createScanner(document.getText(), true);
const children = node.items;
for (let i = children.length - 1; i >= 0; i--) {
const child = children[i];
if (offset > child.offset + child.length) {
scanner.setPosition(child.offset + child.length);
var token = scanner.scan();
const token = scanner.scan();
if (token === 5 /* CommaToken */ && offset >= scanner.getTokenOffset() + scanner.getTokenLength()) {

@@ -956,7 +942,7 @@ return i + 1;

return 0;
};
JSONCompletion.prototype.isInComment = function (document, start, offset) {
var scanner = Json.createScanner(document.getText(), false);
}
isInComment(document, start, offset) {
const scanner = Json.createScanner(document.getText(), false);
scanner.setPosition(start);
var token = scanner.scan();
let token = scanner.scan();
while (token !== 17 /* EOF */ && (scanner.getTokenOffset() + scanner.getTokenLength() < offset)) {

@@ -966,4 +952,4 @@ token = scanner.scan();

return (token === 12 /* LineCommentTrivia */ || token === 13 /* BlockCommentTrivia */) && scanner.getTokenOffset() <= offset;
};
JSONCompletion.prototype.fromMarkup = function (markupString) {
}
fromMarkup(markupString) {
if (markupString && this.doesSupportMarkdown()) {

@@ -976,19 +962,17 @@ return {

return undefined;
};
JSONCompletion.prototype.doesSupportMarkdown = function () {
}
doesSupportMarkdown() {
if (!isDefined(this.supportsMarkdown)) {
var completion = this.clientCapabilities.textDocument && this.clientCapabilities.textDocument.completion;
const completion = this.clientCapabilities.textDocument && this.clientCapabilities.textDocument.completion;
this.supportsMarkdown = completion && completion.completionItem && Array.isArray(completion.completionItem.documentationFormat) && completion.completionItem.documentationFormat.indexOf(MarkupKind.Markdown) !== -1;
}
return this.supportsMarkdown;
};
JSONCompletion.prototype.doesSupportsCommitCharacters = function () {
}
doesSupportsCommitCharacters() {
if (!isDefined(this.supportsCommitCharacters)) {
var completion = this.clientCapabilities.textDocument && this.clientCapabilities.textDocument.completion;
const completion = this.clientCapabilities.textDocument && this.clientCapabilities.textDocument.completion;
this.supportsCommitCharacters = completion && completion.completionItem && !!completion.completionItem.commitCharactersSupport;
}
return this.supportsCommitCharacters;
};
return JSONCompletion;
}());
export { JSONCompletion };
}
}

@@ -9,27 +9,23 @@ /*---------------------------------------------------------------------------------------------

import { Range, TextEdit, SymbolKind, Location } from "../jsonLanguageTypes";
var JSONDocumentSymbols = /** @class */ (function () {
function JSONDocumentSymbols(schemaService) {
export class JSONDocumentSymbols {
constructor(schemaService) {
this.schemaService = schemaService;
}
JSONDocumentSymbols.prototype.findDocumentSymbols = function (document, doc, context) {
var _this = this;
if (context === void 0) { context = { resultLimit: Number.MAX_VALUE }; }
var root = doc.root;
findDocumentSymbols(document, doc, context = { resultLimit: Number.MAX_VALUE }) {
const root = doc.root;
if (!root) {
return [];
}
var limit = context.resultLimit || Number.MAX_VALUE;
let limit = context.resultLimit || Number.MAX_VALUE;
// special handling for key bindings
var resourceString = document.uri;
const resourceString = document.uri;
if ((resourceString === 'vscode://defaultsettings/keybindings.json') || Strings.endsWith(resourceString.toLowerCase(), '/user/keybindings.json')) {
if (root.type === 'array') {
var result_1 = [];
for (var _i = 0, _a = root.items; _i < _a.length; _i++) {
var item = _a[_i];
const result = [];
for (const item of root.items) {
if (item.type === 'object') {
for (var _b = 0, _c = item.properties; _b < _c.length; _b++) {
var property = _c[_b];
for (const property of item.properties) {
if (property.keyNode.value === 'key' && property.valueNode) {
var location = Location.create(document.uri, getRange(document, item));
result_1.push({ name: Parser.getNodeValue(property.valueNode), kind: SymbolKind.Function, location: location });
const location = Location.create(document.uri, getRange(document, item));
result.push({ name: Parser.getNodeValue(property.valueNode), kind: SymbolKind.Function, location: location });
limit--;

@@ -40,3 +36,3 @@ if (limit <= 0) {

}
return result_1;
return result;
}

@@ -47,16 +43,16 @@ }

}
return result_1;
return result;
}
}
var toVisit = [
const toVisit = [
{ node: root, containerName: '' }
];
var nextToVisit = 0;
var limitExceeded = false;
var result = [];
var collectOutlineEntries = function (node, containerName) {
let nextToVisit = 0;
let limitExceeded = false;
const result = [];
const collectOutlineEntries = (node, containerName) => {
if (node.type === 'array') {
node.items.forEach(function (node) {
node.items.forEach(node => {
if (node) {
toVisit.push({ node: node, containerName: containerName });
toVisit.push({ node, containerName });
}

@@ -66,10 +62,10 @@ });

else if (node.type === 'object') {
node.properties.forEach(function (property) {
var valueNode = property.valueNode;
node.properties.forEach((property) => {
const valueNode = property.valueNode;
if (valueNode) {
if (limit > 0) {
limit--;
var location = Location.create(document.uri, getRange(document, property));
var childContainerName = containerName ? containerName + '.' + property.keyNode.value : property.keyNode.value;
result.push({ name: _this.getKeyLabel(property), kind: _this.getSymbolKind(valueNode.type), location: location, containerName: containerName });
const location = Location.create(document.uri, getRange(document, property));
const childContainerName = containerName ? containerName + '.' + property.keyNode.value : property.keyNode.value;
result.push({ name: this.getKeyLabel(property), kind: this.getSymbolKind(valueNode.type), location: location, containerName: containerName });
toVisit.push({ node: valueNode, containerName: childContainerName });

@@ -86,3 +82,3 @@ }

while (nextToVisit < toVisit.length) {
var next = toVisit[nextToVisit++];
const next = toVisit[nextToVisit++];
collectOutlineEntries(next.node, next.containerName);

@@ -94,25 +90,21 @@ }

return result;
};
JSONDocumentSymbols.prototype.findDocumentSymbols2 = function (document, doc, context) {
var _this = this;
if (context === void 0) { context = { resultLimit: Number.MAX_VALUE }; }
var root = doc.root;
}
findDocumentSymbols2(document, doc, context = { resultLimit: Number.MAX_VALUE }) {
const root = doc.root;
if (!root) {
return [];
}
var limit = context.resultLimit || Number.MAX_VALUE;
let limit = context.resultLimit || Number.MAX_VALUE;
// special handling for key bindings
var resourceString = document.uri;
const resourceString = document.uri;
if ((resourceString === 'vscode://defaultsettings/keybindings.json') || Strings.endsWith(resourceString.toLowerCase(), '/user/keybindings.json')) {
if (root.type === 'array') {
var result_2 = [];
for (var _i = 0, _a = root.items; _i < _a.length; _i++) {
var item = _a[_i];
const result = [];
for (const item of root.items) {
if (item.type === 'object') {
for (var _b = 0, _c = item.properties; _b < _c.length; _b++) {
var property = _c[_b];
for (const property of item.properties) {
if (property.keyNode.value === 'key' && property.valueNode) {
var range = getRange(document, item);
var selectionRange = getRange(document, property.keyNode);
result_2.push({ name: Parser.getNodeValue(property.valueNode), kind: SymbolKind.Function, range: range, selectionRange: selectionRange });
const range = getRange(document, item);
const selectionRange = getRange(document, property.keyNode);
result.push({ name: Parser.getNodeValue(property.valueNode), kind: SymbolKind.Function, range, selectionRange });
limit--;

@@ -123,3 +115,3 @@ if (limit <= 0) {

}
return result_2;
return result;
}

@@ -130,23 +122,23 @@ }

}
return result_2;
return result;
}
}
var result = [];
var toVisit = [
{ node: root, result: result }
const result = [];
const toVisit = [
{ node: root, result }
];
var nextToVisit = 0;
var limitExceeded = false;
var collectOutlineEntries = function (node, result) {
let nextToVisit = 0;
let limitExceeded = false;
const collectOutlineEntries = (node, result) => {
if (node.type === 'array') {
node.items.forEach(function (node, index) {
node.items.forEach((node, index) => {
if (node) {
if (limit > 0) {
limit--;
var range = getRange(document, node);
var selectionRange = range;
var name = String(index);
var symbol = { name: name, kind: _this.getSymbolKind(node.type), range: range, selectionRange: selectionRange, children: [] };
const range = getRange(document, node);
const selectionRange = range;
const name = String(index);
const symbol = { name, kind: this.getSymbolKind(node.type), range, selectionRange, children: [] };
result.push(symbol);
toVisit.push({ result: symbol.children, node: node });
toVisit.push({ result: symbol.children, node });
}

@@ -160,11 +152,11 @@ else {

else if (node.type === 'object') {
node.properties.forEach(function (property) {
var valueNode = property.valueNode;
node.properties.forEach((property) => {
const valueNode = property.valueNode;
if (valueNode) {
if (limit > 0) {
limit--;
var range = getRange(document, property);
var selectionRange = getRange(document, property.keyNode);
var children = [];
var symbol = { name: _this.getKeyLabel(property), kind: _this.getSymbolKind(valueNode.type), range: range, selectionRange: selectionRange, children: children, detail: _this.getDetail(valueNode) };
const range = getRange(document, property);
const selectionRange = getRange(document, property.keyNode);
const children = [];
const symbol = { name: this.getKeyLabel(property), kind: this.getSymbolKind(valueNode.type), range, selectionRange, children, detail: this.getDetail(valueNode) };
result.push(symbol);

@@ -182,3 +174,3 @@ toVisit.push({ result: children, node: valueNode });

while (nextToVisit < toVisit.length) {
var next = toVisit[nextToVisit++];
const next = toVisit[nextToVisit++];
collectOutlineEntries(next.node, next.result);

@@ -190,4 +182,4 @@ }

return result;
};
JSONDocumentSymbols.prototype.getSymbolKind = function (nodeType) {
}
getSymbolKind(nodeType) {
switch (nodeType) {

@@ -207,5 +199,5 @@ case 'object':

}
};
JSONDocumentSymbols.prototype.getKeyLabel = function (property) {
var name = property.keyNode.value;
}
getKeyLabel(property) {
let name = property.keyNode.value;
if (name) {

@@ -217,5 +209,5 @@ name = name.replace(/[\n]/g, '↵');

}
return "\"".concat(name, "\"");
};
JSONDocumentSymbols.prototype.getDetail = function (node) {
return `"${name}"`;
}
getDetail(node) {
if (!node) {

@@ -236,19 +228,18 @@ return undefined;

return undefined;
};
JSONDocumentSymbols.prototype.findDocumentColors = function (document, doc, context) {
return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
var result = [];
}
findDocumentColors(document, doc, context) {
return this.schemaService.getSchemaForResource(document.uri, doc).then(schema => {
const result = [];
if (schema) {
var limit = context && typeof context.resultLimit === 'number' ? context.resultLimit : Number.MAX_VALUE;
var matchingSchemas = doc.getMatchingSchemas(schema.schema);
var visitedNode = {};
for (var _i = 0, matchingSchemas_1 = matchingSchemas; _i < matchingSchemas_1.length; _i++) {
var s = matchingSchemas_1[_i];
let limit = context && typeof context.resultLimit === 'number' ? context.resultLimit : Number.MAX_VALUE;
const matchingSchemas = doc.getMatchingSchemas(schema.schema);
const visitedNode = {};
for (const s of matchingSchemas) {
if (!s.inverted && s.schema && (s.schema.format === 'color' || s.schema.format === 'color-hex') && s.node && s.node.type === 'string') {
var nodeId = String(s.node.offset);
const nodeId = String(s.node.offset);
if (!visitedNode[nodeId]) {
var color = colorFromHex(Parser.getNodeValue(s.node));
const color = colorFromHex(Parser.getNodeValue(s.node));
if (color) {
var range = getRange(document, s.node);
result.push({ color: color, range: range });
const range = getRange(document, s.node);
result.push({ color, range });
}

@@ -269,25 +260,23 @@ visitedNode[nodeId] = true;

});
};
JSONDocumentSymbols.prototype.getColorPresentations = function (document, doc, color, range) {
var result = [];
var red256 = Math.round(color.red * 255), green256 = Math.round(color.green * 255), blue256 = Math.round(color.blue * 255);
}
getColorPresentations(document, doc, color, range) {
const result = [];
const red256 = Math.round(color.red * 255), green256 = Math.round(color.green * 255), blue256 = Math.round(color.blue * 255);
function toTwoDigitHex(n) {
var r = n.toString(16);
const r = n.toString(16);
return r.length !== 2 ? '0' + r : r;
}
var label;
let label;
if (color.alpha === 1) {
label = "#".concat(toTwoDigitHex(red256)).concat(toTwoDigitHex(green256)).concat(toTwoDigitHex(blue256));
label = `#${toTwoDigitHex(red256)}${toTwoDigitHex(green256)}${toTwoDigitHex(blue256)}`;
}
else {
label = "#".concat(toTwoDigitHex(red256)).concat(toTwoDigitHex(green256)).concat(toTwoDigitHex(blue256)).concat(toTwoDigitHex(Math.round(color.alpha * 255)));
label = `#${toTwoDigitHex(red256)}${toTwoDigitHex(green256)}${toTwoDigitHex(blue256)}${toTwoDigitHex(Math.round(color.alpha * 255))}`;
}
result.push({ label: label, textEdit: TextEdit.replace(range, JSON.stringify(label)) });
return result;
};
return JSONDocumentSymbols;
}());
export { JSONDocumentSymbols };
}
}
function getRange(document, node) {
return Range.create(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
}

@@ -8,8 +8,8 @@ /*---------------------------------------------------------------------------------------------

export function getFoldingRanges(document, context) {
var ranges = [];
var nestingLevels = [];
var stack = [];
var prevStart = -1;
var scanner = createScanner(document.getText(), false);
var token = scanner.scan();
const ranges = [];
const nestingLevels = [];
const stack = [];
let prevStart = -1;
const scanner = createScanner(document.getText(), false);
let token = scanner.scan();
function addRange(range) {

@@ -23,4 +23,4 @@ ranges.push(range);

case 3 /* OpenBracketToken */: {
var startLine = document.positionAt(scanner.getTokenOffset()).line;
var range = { startLine: startLine, endLine: startLine, kind: token === 1 /* OpenBraceToken */ ? 'object' : 'array' };
const startLine = document.positionAt(scanner.getTokenOffset()).line;
const range = { startLine, endLine: startLine, kind: token === 1 /* OpenBraceToken */ ? 'object' : 'array' };
stack.push(range);

@@ -31,6 +31,6 @@ break;

case 4 /* CloseBracketToken */: {
var kind = token === 2 /* CloseBraceToken */ ? 'object' : 'array';
const kind = token === 2 /* CloseBraceToken */ ? 'object' : 'array';
if (stack.length > 0 && stack[stack.length - 1].kind === kind) {
var range = stack.pop();
var line = document.positionAt(scanner.getTokenOffset()).line;
const range = stack.pop();
const line = document.positionAt(scanner.getTokenOffset()).line;
if (range && line > range.startLine + 1 && prevStart !== range.startLine) {

@@ -45,4 +45,4 @@ range.endLine = line - 1;

case 13 /* BlockCommentTrivia */: {
var startLine = document.positionAt(scanner.getTokenOffset()).line;
var endLine = document.positionAt(scanner.getTokenOffset() + scanner.getTokenLength()).line;
const startLine = document.positionAt(scanner.getTokenOffset()).line;
const endLine = document.positionAt(scanner.getTokenOffset() + scanner.getTokenLength()).line;
if (scanner.getTokenError() === 1 /* UnexpectedEndOfComment */ && startLine + 1 < document.lineCount) {

@@ -53,3 +53,3 @@ scanner.setPosition(document.offsetAt(Position.create(startLine + 1, 0)));

if (startLine < endLine) {
addRange({ startLine: startLine, endLine: endLine, kind: FoldingRangeKind.Comment });
addRange({ startLine, endLine, kind: FoldingRangeKind.Comment });
prevStart = startLine;

@@ -61,12 +61,12 @@ }

case 12 /* LineCommentTrivia */: {
var text = document.getText().substr(scanner.getTokenOffset(), scanner.getTokenLength());
var m = text.match(/^\/\/\s*#(region\b)|(endregion\b)/);
const text = document.getText().substr(scanner.getTokenOffset(), scanner.getTokenLength());
const m = text.match(/^\/\/\s*#(region\b)|(endregion\b)/);
if (m) {
var line = document.positionAt(scanner.getTokenOffset()).line;
const line = document.positionAt(scanner.getTokenOffset()).line;
if (m[1]) { // start pattern match
var range = { startLine: line, endLine: line, kind: FoldingRangeKind.Region };
const range = { startLine: line, endLine: line, kind: FoldingRangeKind.Region };
stack.push(range);
}
else {
var i = stack.length - 1;
let i = stack.length - 1;
while (i >= 0 && stack[i].kind !== FoldingRangeKind.Region) {

@@ -76,3 +76,3 @@ i--;

if (i >= 0) {
var range = stack[i];
const range = stack[i];
stack.length = i;

@@ -92,3 +92,3 @@ if (line > range.startLine && prevStart !== range.startLine) {

}
var rangeLimit = context && context.rangeLimit;
const rangeLimit = context && context.rangeLimit;
if (typeof rangeLimit !== 'number' || ranges.length <= rangeLimit) {

@@ -100,5 +100,4 @@ return ranges;

}
var counts = [];
for (var _i = 0, nestingLevels_1 = nestingLevels; _i < nestingLevels_1.length; _i++) {
var level = nestingLevels_1[_i];
const counts = [];
for (let level of nestingLevels) {
if (level < 30) {

@@ -108,6 +107,6 @@ counts[level] = (counts[level] || 0) + 1;

}
var entries = 0;
var maxLevel = 0;
for (var i = 0; i < counts.length; i++) {
var n = counts[i];
let entries = 0;
let maxLevel = 0;
for (let i = 0; i < counts.length; i++) {
const n = counts[i];
if (n) {

@@ -121,5 +120,5 @@ if (n + entries > rangeLimit) {

}
var result = [];
for (var i = 0; i < ranges.length; i++) {
var level = nestingLevels[i];
const result = [];
for (let i = 0; i < ranges.length; i++) {
const level = nestingLevels[i];
if (typeof level === 'number') {

@@ -126,0 +125,0 @@ if (level < maxLevel || (level === maxLevel && entries++ < rangeLimit)) {

@@ -7,5 +7,4 @@ /*---------------------------------------------------------------------------------------------

import { Range } from '../jsonLanguageTypes';
var JSONHover = /** @class */ (function () {
function JSONHover(schemaService, contributions, promiseConstructor) {
if (contributions === void 0) { contributions = []; }
export class JSONHover {
constructor(schemaService, contributions = [], promiseConstructor) {
this.schemaService = schemaService;

@@ -15,12 +14,12 @@ this.contributions = contributions;

}
JSONHover.prototype.doHover = function (document, position, doc) {
var offset = document.offsetAt(position);
var node = doc.getNodeFromOffset(offset);
doHover(document, position, doc) {
const offset = document.offsetAt(position);
let node = doc.getNodeFromOffset(offset);
if (!node || (node.type === 'object' || node.type === 'array') && offset > node.offset + 1 && offset < node.offset + node.length - 1) {
return this.promise.resolve(null);
}
var hoverRangeNode = node;
const hoverRangeNode = node;
// use the property description when hovering over an object key
if (node.type === 'string') {
var parent = node.parent;
const parent = node.parent;
if (parent && parent.type === 'property' && parent.keyNode === node) {

@@ -33,5 +32,5 @@ node = parent.valueNode;

}
var hoverRange = Range.create(document.positionAt(hoverRangeNode.offset), document.positionAt(hoverRangeNode.offset + hoverRangeNode.length));
var createHover = function (contents) {
var result = {
const hoverRange = Range.create(document.positionAt(hoverRangeNode.offset), document.positionAt(hoverRangeNode.offset + hoverRangeNode.length));
var createHover = (contents) => {
const result = {
contents: contents,

@@ -42,32 +41,32 @@ range: hoverRange

};
var location = Parser.getNodePath(node);
for (var i = this.contributions.length - 1; i >= 0; i--) {
var contribution = this.contributions[i];
var promise = contribution.getInfoContribution(document.uri, location);
const location = Parser.getNodePath(node);
for (let i = this.contributions.length - 1; i >= 0; i--) {
const contribution = this.contributions[i];
const promise = contribution.getInfoContribution(document.uri, location);
if (promise) {
return promise.then(function (htmlContent) { return createHover(htmlContent); });
return promise.then(htmlContent => createHover(htmlContent));
}
}
return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
return this.schemaService.getSchemaForResource(document.uri, doc).then((schema) => {
if (schema && node) {
var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset);
var title_1 = undefined;
var markdownDescription_1 = undefined;
var markdownEnumValueDescription_1 = undefined, enumValue_1 = undefined;
matchingSchemas.every(function (s) {
const matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset);
let title = undefined;
let markdownDescription = undefined;
let markdownEnumValueDescription = undefined, enumValue = undefined;
matchingSchemas.every((s) => {
if (s.node === node && !s.inverted && s.schema) {
title_1 = title_1 || s.schema.title;
markdownDescription_1 = markdownDescription_1 || s.schema.markdownDescription || toMarkdown(s.schema.description);
title = title || s.schema.title;
markdownDescription = markdownDescription || s.schema.markdownDescription || toMarkdown(s.schema.description);
if (s.schema.enum) {
var idx = s.schema.enum.indexOf(Parser.getNodeValue(node));
const idx = s.schema.enum.indexOf(Parser.getNodeValue(node));
if (s.schema.markdownEnumDescriptions) {
markdownEnumValueDescription_1 = s.schema.markdownEnumDescriptions[idx];
markdownEnumValueDescription = s.schema.markdownEnumDescriptions[idx];
}
else if (s.schema.enumDescriptions) {
markdownEnumValueDescription_1 = toMarkdown(s.schema.enumDescriptions[idx]);
markdownEnumValueDescription = toMarkdown(s.schema.enumDescriptions[idx]);
}
if (markdownEnumValueDescription_1) {
enumValue_1 = s.schema.enum[idx];
if (typeof enumValue_1 !== 'string') {
enumValue_1 = JSON.stringify(enumValue_1);
if (markdownEnumValueDescription) {
enumValue = s.schema.enum[idx];
if (typeof enumValue !== 'string') {
enumValue = JSON.stringify(enumValue);
}

@@ -79,17 +78,17 @@ }

});
var result = '';
if (title_1) {
result = toMarkdown(title_1);
let result = '';
if (title) {
result = toMarkdown(title);
}
if (markdownDescription_1) {
if (markdownDescription) {
if (result.length > 0) {
result += "\n\n";
}
result += markdownDescription_1;
result += markdownDescription;
}
if (markdownEnumValueDescription_1) {
if (markdownEnumValueDescription) {
if (result.length > 0) {
result += "\n\n";
}
result += "`".concat(toMarkdownCodeBlock(enumValue_1), "`: ").concat(markdownEnumValueDescription_1);
result += `\`${toMarkdownCodeBlock(enumValue)}\`: ${markdownEnumValueDescription}`;
}

@@ -100,9 +99,7 @@ return createHover([result]);

});
};
return JSONHover;
}());
export { JSONHover };
}
}
function toMarkdown(plain) {
if (plain) {
var res = plain.replace(/([^\n\r])(\r?\n)([^\n\r])/gm, '$1\n\n$3'); // single new lines to \n\n (Markdown paragraph)
const res = plain.replace(/([^\n\r])(\r?\n)([^\n\r])/gm, '$1\n\n$3'); // single new lines to \n\n (Markdown paragraph)
return res.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&"); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash

@@ -109,0 +106,0 @@ }

@@ -7,12 +7,11 @@ /*---------------------------------------------------------------------------------------------

export function findLinks(document, doc) {
var links = [];
doc.visit(function (node) {
var _a;
if (node.type === "property" && node.keyNode.value === "$ref" && ((_a = node.valueNode) === null || _a === void 0 ? void 0 : _a.type) === 'string') {
var path = node.valueNode.value;
var targetNode = findTargetNode(doc, path);
const links = [];
doc.visit(node => {
if (node.type === "property" && node.keyNode.value === "$ref" && node.valueNode?.type === 'string') {
const path = node.valueNode.value;
const targetNode = findTargetNode(doc, path);
if (targetNode) {
var targetPos = document.positionAt(targetNode.offset);
const targetPos = document.positionAt(targetNode.offset);
links.push({
target: "".concat(document.uri, "#").concat(targetPos.line + 1, ",").concat(targetPos.character + 1),
target: `${document.uri}#${targetPos.line + 1},${targetPos.character + 1}`,
range: createRange(document, node.valueNode)

@@ -30,3 +29,3 @@ });

function findTargetNode(doc, path) {
var tokens = parseJSONPointer(path);
const tokens = parseJSONPointer(path);
if (!tokens) {

@@ -44,5 +43,5 @@ return null;

}
var token = pointer.shift();
const token = pointer.shift();
if (node && node.type === 'object') {
var propertyNode = node.properties.find(function (propertyNode) { return propertyNode.keyNode.value === token; });
const propertyNode = node.properties.find((propertyNode) => propertyNode.keyNode.value === token);
if (!propertyNode) {

@@ -55,4 +54,4 @@ return null;

if (token.match(/^(0|[1-9][0-9]*)$/)) {
var index = Number.parseInt(token);
var arrayItem = node.items[index];
const index = Number.parseInt(token);
const arrayItem = node.items[index];
if (!arrayItem) {

@@ -59,0 +58,0 @@ return null;

@@ -11,12 +11,12 @@ /*---------------------------------------------------------------------------------------------

import { createRegex } from '../utils/glob';
var localize = nls.loadMessageBundle();
var BANG = '!';
var PATH_SEP = '/';
var FilePatternAssociation = /** @class */ (function () {
function FilePatternAssociation(pattern, uris) {
import { isObject, isString } from '../utils/objects';
const localize = nls.loadMessageBundle();
const BANG = '!';
const PATH_SEP = '/';
class FilePatternAssociation {
constructor(pattern, uris) {
this.globWrappers = [];
try {
for (var _i = 0, pattern_1 = pattern; _i < pattern_1.length; _i++) {
var patternString = pattern_1[_i];
var include = patternString[0] !== BANG;
for (let patternString of pattern) {
const include = patternString[0] !== BANG;
if (!include) {

@@ -43,6 +43,5 @@ patternString = patternString.substring(1);

}
FilePatternAssociation.prototype.matchesPattern = function (fileName) {
var match = false;
for (var _i = 0, _a = this.globWrappers; _i < _a.length; _i++) {
var _b = _a[_i], regexp = _b.regexp, include = _b.include;
matchesPattern(fileName) {
let match = false;
for (const { regexp, include } of this.globWrappers) {
if (regexp.test(fileName)) {

@@ -53,10 +52,9 @@ match = include;

return match;
};
FilePatternAssociation.prototype.getURIs = function () {
}
getURIs() {
return this.uris;
};
return FilePatternAssociation;
}());
var SchemaHandle = /** @class */ (function () {
function SchemaHandle(service, uri, unresolvedSchemaContent) {
}
}
class SchemaHandle {
constructor(service, uri, unresolvedSchemaContent) {
this.service = service;

@@ -70,3 +68,3 @@ this.uri = uri;

}
SchemaHandle.prototype.getUnresolvedSchema = function () {
getUnresolvedSchema() {
if (!this.unresolvedSchema) {

@@ -76,14 +74,13 @@ this.unresolvedSchema = this.service.loadSchema(this.uri);

return this.unresolvedSchema;
};
SchemaHandle.prototype.getResolvedSchema = function () {
var _this = this;
}
getResolvedSchema() {
if (!this.resolvedSchema) {
this.resolvedSchema = this.getUnresolvedSchema().then(function (unresolved) {
return _this.service.resolveSchemaContent(unresolved, _this);
this.resolvedSchema = this.getUnresolvedSchema().then(unresolved => {
return this.service.resolveSchemaContent(unresolved, this);
});
}
return this.resolvedSchema;
};
SchemaHandle.prototype.clearSchema = function () {
var hasChanges = !!this.unresolvedSchema;
}
clearSchema() {
const hasChanges = !!this.unresolvedSchema;
this.resolvedSchema = undefined;

@@ -94,22 +91,19 @@ this.unresolvedSchema = undefined;

return hasChanges;
};
return SchemaHandle;
}());
var UnresolvedSchema = /** @class */ (function () {
function UnresolvedSchema(schema, errors) {
if (errors === void 0) { errors = []; }
}
}
export class UnresolvedSchema {
constructor(schema, errors = []) {
this.schema = schema;
this.errors = errors;
}
return UnresolvedSchema;
}());
export { UnresolvedSchema };
var ResolvedSchema = /** @class */ (function () {
function ResolvedSchema(schema, errors) {
if (errors === void 0) { errors = []; }
}
export class ResolvedSchema {
constructor(schema, errors = [], warnings = [], schemaDraft) {
this.schema = schema;
this.errors = errors;
this.warnings = warnings;
this.schemaDraft = schemaDraft;
}
ResolvedSchema.prototype.getSection = function (path) {
var schemaRef = this.getSectionRecursive(path, this.schema);
getSection(path) {
const schemaRef = this.getSectionRecursive(path, this.schema);
if (schemaRef) {

@@ -119,8 +113,8 @@ return Parser.asSchema(schemaRef);

return undefined;
};
ResolvedSchema.prototype.getSectionRecursive = function (path, schema) {
}
getSectionRecursive(path, schema) {
if (!schema || typeof schema === 'boolean' || path.length === 0) {
return schema;
}
var next = path.shift();
const next = path.shift();
if (schema.properties && typeof schema.properties[next]) {

@@ -130,6 +124,5 @@ return this.getSectionRecursive(path, schema.properties[next]);

else if (schema.patternProperties) {
for (var _i = 0, _a = Object.keys(schema.patternProperties); _i < _a.length; _i++) {
var pattern = _a[_i];
var regex = Strings.extendedRegExp(pattern);
if (regex === null || regex === void 0 ? void 0 : regex.test(next)) {
for (const pattern of Object.keys(schema.patternProperties)) {
const regex = Strings.extendedRegExp(pattern);
if (regex?.test(next)) {
return this.getSectionRecursive(path, schema.patternProperties[pattern]);

@@ -144,3 +137,3 @@ }

if (Array.isArray(schema.items)) {
var index = parseInt(next, 10);
const index = parseInt(next, 10);
if (!isNaN(index) && schema.items[index]) {

@@ -155,8 +148,6 @@ return this.getSectionRecursive(path, schema.items[index]);

return undefined;
};
return ResolvedSchema;
}());
export { ResolvedSchema };
var JSONSchemaService = /** @class */ (function () {
function JSONSchemaService(requestService, contextService, promiseConstructor) {
}
}
export class JSONSchemaService {
constructor(requestService, contextService, promiseConstructor) {
this.contextService = contextService;

@@ -172,32 +163,27 @@ this.requestService = requestService;

}
JSONSchemaService.prototype.getRegisteredSchemaIds = function (filter) {
return Object.keys(this.registeredSchemasIds).filter(function (id) {
var scheme = URI.parse(id).scheme;
getRegisteredSchemaIds(filter) {
return Object.keys(this.registeredSchemasIds).filter(id => {
const scheme = URI.parse(id).scheme;
return scheme !== 'schemaservice' && (!filter || filter(scheme));
});
};
Object.defineProperty(JSONSchemaService.prototype, "promise", {
get: function () {
return this.promiseConstructor;
},
enumerable: false,
configurable: true
});
JSONSchemaService.prototype.dispose = function () {
}
get promise() {
return this.promiseConstructor;
}
dispose() {
while (this.callOnDispose.length > 0) {
this.callOnDispose.pop()();
}
};
JSONSchemaService.prototype.onResourceChange = function (uri) {
var _this = this;
}
onResourceChange(uri) {
// always clear this local cache when a resource changes
this.cachedSchemaForResource = undefined;
var hasChanges = false;
let hasChanges = false;
uri = normalizeId(uri);
var toWalk = [uri];
var all = Object.keys(this.schemasById).map(function (key) { return _this.schemasById[key]; });
const toWalk = [uri];
const all = Object.keys(this.schemasById).map(key => this.schemasById[key]);
while (toWalk.length) {
var curr = toWalk.pop();
for (var i = 0; i < all.length; i++) {
var handle = all[i];
const curr = toWalk.pop();
for (let i = 0; i < all.length; i++) {
const handle = all[i];
if (handle && (handle.uri === curr || handle.dependencies.has(curr))) {

@@ -215,8 +201,8 @@ if (handle.uri !== curr) {

return hasChanges;
};
JSONSchemaService.prototype.setSchemaContributions = function (schemaContributions) {
}
setSchemaContributions(schemaContributions) {
if (schemaContributions.schemas) {
var schemas = schemaContributions.schemas;
for (var id in schemas) {
var normalizedId = normalizeId(id);
const schemas = schemaContributions.schemas;
for (const id in schemas) {
const normalizedId = normalizeId(id);
this.contributionSchemas[normalizedId] = this.addSchemaHandle(normalizedId, schemas[id]);

@@ -226,26 +212,25 @@ }

if (Array.isArray(schemaContributions.schemaAssociations)) {
var schemaAssociations = schemaContributions.schemaAssociations;
for (var _i = 0, schemaAssociations_1 = schemaAssociations; _i < schemaAssociations_1.length; _i++) {
var schemaAssociation = schemaAssociations_1[_i];
var uris = schemaAssociation.uris.map(normalizeId);
var association = this.addFilePatternAssociation(schemaAssociation.pattern, uris);
const schemaAssociations = schemaContributions.schemaAssociations;
for (let schemaAssociation of schemaAssociations) {
const uris = schemaAssociation.uris.map(normalizeId);
const association = this.addFilePatternAssociation(schemaAssociation.pattern, uris);
this.contributionAssociations.push(association);
}
}
};
JSONSchemaService.prototype.addSchemaHandle = function (id, unresolvedSchemaContent) {
var schemaHandle = new SchemaHandle(this, id, unresolvedSchemaContent);
}
addSchemaHandle(id, unresolvedSchemaContent) {
const schemaHandle = new SchemaHandle(this, id, unresolvedSchemaContent);
this.schemasById[id] = schemaHandle;
return schemaHandle;
};
JSONSchemaService.prototype.getOrAddSchemaHandle = function (id, unresolvedSchemaContent) {
}
getOrAddSchemaHandle(id, unresolvedSchemaContent) {
return this.schemasById[id] || this.addSchemaHandle(id, unresolvedSchemaContent);
};
JSONSchemaService.prototype.addFilePatternAssociation = function (pattern, uris) {
var fpa = new FilePatternAssociation(pattern, uris);
}
addFilePatternAssociation(pattern, uris) {
const fpa = new FilePatternAssociation(pattern, uris);
this.filePatternAssociations.push(fpa);
return fpa;
};
JSONSchemaService.prototype.registerExternalSchema = function (uri, filePatterns, unresolvedSchemaContent) {
var id = normalizeId(uri);
}
registerExternalSchema(uri, filePatterns, unresolvedSchemaContent) {
const id = normalizeId(uri);
this.registeredSchemasIds[id] = true;

@@ -257,4 +242,4 @@ this.cachedSchemaForResource = undefined;

return unresolvedSchemaContent ? this.addSchemaHandle(id, unresolvedSchemaContent) : this.getOrAddSchemaHandle(id);
};
JSONSchemaService.prototype.clearExternalSchemas = function () {
}
clearExternalSchemas() {
this.schemasById = {};

@@ -264,14 +249,13 @@ this.filePatternAssociations = [];

this.cachedSchemaForResource = undefined;
for (var id in this.contributionSchemas) {
for (const id in this.contributionSchemas) {
this.schemasById[id] = this.contributionSchemas[id];
this.registeredSchemasIds[id] = true;
}
for (var _i = 0, _a = this.contributionAssociations; _i < _a.length; _i++) {
var contributionAssociation = _a[_i];
for (const contributionAssociation of this.contributionAssociations) {
this.filePatternAssociations.push(contributionAssociation);
}
};
JSONSchemaService.prototype.getResolvedSchema = function (schemaId) {
var id = normalizeId(schemaId);
var schemaHandle = this.schemasById[id];
}
getResolvedSchema(schemaId) {
const id = normalizeId(schemaId);
const schemaHandle = this.schemasById[id];
if (schemaHandle) {

@@ -281,21 +265,21 @@ return schemaHandle.getResolvedSchema();

return this.promise.resolve(undefined);
};
JSONSchemaService.prototype.loadSchema = function (url) {
}
loadSchema(url) {
if (!this.requestService) {
var errorMessage = localize('json.schema.norequestservice', 'Unable to load schema from \'{0}\'. No schema request service available', toDisplayString(url));
const errorMessage = localize('json.schema.norequestservice', 'Unable to load schema from \'{0}\'. No schema request service available', toDisplayString(url));
return this.promise.resolve(new UnresolvedSchema({}, [errorMessage]));
}
return this.requestService(url).then(function (content) {
return this.requestService(url).then(content => {
if (!content) {
var errorMessage = localize('json.schema.nocontent', 'Unable to load schema from \'{0}\': No content.', toDisplayString(url));
const errorMessage = localize('json.schema.nocontent', 'Unable to load schema from \'{0}\': No content.', toDisplayString(url));
return new UnresolvedSchema({}, [errorMessage]);
}
var schemaContent = {};
var jsonErrors = [];
let schemaContent = {};
const jsonErrors = [];
schemaContent = Json.parse(content, jsonErrors);
var errors = jsonErrors.length ? [localize('json.schema.invalidFormat', 'Unable to parse content from \'{0}\': Parse error at offset {1}.', toDisplayString(url), jsonErrors[0].offset)] : [];
const errors = jsonErrors.length ? [localize('json.schema.invalidFormat', 'Unable to parse content from \'{0}\': Parse error at offset {1}.', toDisplayString(url), jsonErrors[0].offset)] : [];
return new UnresolvedSchema(schemaContent, errors);
}, function (error) {
var errorMessage = error.toString();
var errorSplit = error.toString().split('Error: ');
}, (error) => {
let errorMessage = error.toString();
const errorSplit = error.toString().split('Error: ');
if (errorSplit.length > 1) {

@@ -310,27 +294,19 @@ // more concise error message, URL and context are attached by caller anyways

});
};
JSONSchemaService.prototype.resolveSchemaContent = function (schemaToResolve, handle) {
var _this = this;
var resolveErrors = schemaToResolve.errors.slice(0);
var schema = schemaToResolve.schema;
if (schema.$schema) {
var id = normalizeId(schema.$schema);
if (id === 'http://json-schema.org/draft-03/schema') {
return this.promise.resolve(new ResolvedSchema({}, [localize('json.schema.draft03.notsupported', "Draft-03 schemas are not supported.")]));
}
else if (id === 'https://json-schema.org/draft/2019-09/schema') {
resolveErrors.push(localize('json.schema.draft201909.notsupported', "Draft 2019-09 schemas are not yet fully supported."));
}
else if (id === 'https://json-schema.org/draft/2020-12/schema') {
resolveErrors.push(localize('json.schema.draft202012.notsupported', "Draft 2020-12 schemas are not yet fully supported."));
}
}
resolveSchemaContent(schemaToResolve, handle) {
const resolveErrors = schemaToResolve.errors.slice(0);
const schema = schemaToResolve.schema;
let schemaDraft = schema.$schema ? normalizeId(schema.$schema) : undefined;
if (schemaDraft === 'http://json-schema.org/draft-03/schema') {
return this.promise.resolve(new ResolvedSchema({}, [localize('json.schema.draft03.notsupported', "Draft-03 schemas are not supported.")], [], schemaDraft));
}
var contextService = this.contextService;
var findSectionByJSONPointer = function (schema, path) {
let usesUnsupportedFeatures = new Set();
const contextService = this.contextService;
const findSectionByJSONPointer = (schema, path) => {
path = decodeURIComponent(path);
var current = schema;
let current = schema;
if (path[0] === '/') {
path = path.substring(1);
}
path.split('/').some(function (part) {
path.split('/').some((part) => {
part = part.replace(/~1/g, '/').replace(/~0/g, '~');

@@ -342,3 +318,3 @@ current = current[part];

};
var findSchemaById = function (schema, handle, id) {
const findSchemaById = (schema, handle, id) => {
if (!handle.anchors) {

@@ -349,4 +325,4 @@ handle.anchors = collectAnchors(schema);

};
var merge = function (target, section) {
for (var key in section) {
const merge = (target, section) => {
for (const key in section) {
if (section.hasOwnProperty(key) && !target.hasOwnProperty(key) && key !== 'id' && key !== '$id') {

@@ -357,4 +333,4 @@ target[key] = section[key];

};
var mergeRef = function (target, sourceRoot, sourceHandle, refSegment) {
var section;
const mergeRef = (target, sourceRoot, sourceHandle, refSegment) => {
let section;
if (refSegment === undefined || refSegment.length === 0) {

@@ -378,3 +354,3 @@ section = sourceRoot;

};
var resolveExternalLink = function (node, uri, refSegment, parentHandle) {
const resolveExternalLink = (node, uri, refSegment, parentHandle) => {
if (contextService && !/^[A-Za-z][A-Za-z0-9+\-.+]*:\/\/.*/.test(uri)) {

@@ -384,7 +360,7 @@ uri = contextService.resolveRelativePath(uri, parentHandle.uri);

uri = normalizeId(uri);
var referencedHandle = _this.getOrAddSchemaHandle(uri);
return referencedHandle.getUnresolvedSchema().then(function (unresolvedSchema) {
const referencedHandle = this.getOrAddSchemaHandle(uri);
return referencedHandle.getUnresolvedSchema().then(unresolvedSchema => {
parentHandle.dependencies.add(uri);
if (unresolvedSchema.errors.length) {
var loc = refSegment ? uri + '#' + refSegment : uri;
const loc = refSegment ? uri + '#' + refSegment : uri;
resolveErrors.push(localize('json.schema.problemloadingref', 'Problems loading reference \'{0}\': {1}', loc, unresolvedSchema.errors[0]));

@@ -396,9 +372,9 @@ }

};
var resolveRefs = function (node, parentSchema, parentHandle) {
var openPromises = [];
_this.traverseNodes(node, function (next) {
var seenRefs = new Set();
const resolveRefs = (node, parentSchema, parentHandle) => {
const openPromises = [];
this.traverseNodes(node, next => {
const seenRefs = new Set();
while (next.$ref) {
var ref = next.$ref;
var segments = ref.split('#', 2);
const ref = next.$ref;
const segments = ref.split('#', 2);
delete next.$ref;

@@ -413,3 +389,3 @@ if (segments[0].length > 0) {

if (!seenRefs.has(ref)) {
var id = segments[1];
const id = segments[1];
mergeRef(next, parentSchema, parentHandle, id);

@@ -420,15 +396,19 @@ seenRefs.add(ref);

}
if (next.$recursiveRef) {
usesUnsupportedFeatures.add('$recursiveRef');
}
if (next.$dynamicRef) {
usesUnsupportedFeatures.add('$dynamicRef');
}
});
return _this.promise.all(openPromises);
return this.promise.all(openPromises);
};
var collectAnchors = function (root) {
var result = new Map();
_this.traverseNodes(root, function (next) {
var id = next.$id || next.id;
if (typeof id === 'string' && id.charAt(0) === '#') {
// delete next.$id;
// delete next.id;
var anchor = id.substring(1);
const collectAnchors = (root) => {
const result = new Map();
this.traverseNodes(root, next => {
const id = next.$id || next.id;
const anchor = isString(id) && id.charAt(0) === '#' ? id.substring(1) : next.$anchor;
if (anchor) {
if (result.has(anchor)) {
resolveErrors.push(localize('json.schema.duplicateid', 'Duplicate id declaration: \'{0}\'', id));
resolveErrors.push(localize('json.schema.duplicateid', 'Duplicate anchor declaration: \'{0}\'', anchor));
}

@@ -439,22 +419,27 @@ else {

}
if (next.$recursiveAnchor) {
usesUnsupportedFeatures.add('$recursiveAnchor');
}
if (next.$dynamicAnchor) {
usesUnsupportedFeatures.add('$dynamicAnchor');
}
});
return result;
};
return resolveRefs(schema, schema, handle).then(function (_) {
return new ResolvedSchema(schema, resolveErrors);
return resolveRefs(schema, schema, handle).then(_ => {
let resolveWarnings = [];
if (usesUnsupportedFeatures.size) {
resolveWarnings.push(localize('json.schema.warnings', 'The schema uses meta-schema features ({0}) that are not yet supported by the validator.', Array.from(usesUnsupportedFeatures.keys()).join(', ')));
}
return new ResolvedSchema(schema, resolveErrors, resolveWarnings, schemaDraft);
});
};
JSONSchemaService.prototype.traverseNodes = function (root, handle) {
}
traverseNodes(root, handle) {
if (!root || typeof root !== 'object') {
return Promise.resolve(null);
}
var seen = new Set();
var collectEntries = function () {
var entries = [];
for (var _i = 0; _i < arguments.length; _i++) {
entries[_i] = arguments[_i];
}
for (var _a = 0, entries_1 = entries; _a < entries_1.length; _a++) {
var entry = entries_1[_a];
if (typeof entry === 'object') {
const seen = new Set();
const collectEntries = (...entries) => {
for (const entry of entries) {
if (isObject(entry)) {
toWalk.push(entry);

@@ -464,14 +449,9 @@ }

};
var collectMapEntries = function () {
var maps = [];
for (var _i = 0; _i < arguments.length; _i++) {
maps[_i] = arguments[_i];
}
for (var _a = 0, maps_1 = maps; _a < maps_1.length; _a++) {
var map = maps_1[_a];
if (typeof map === 'object') {
for (var k in map) {
var key = k;
var entry = map[key];
if (typeof entry === 'object') {
const collectMapEntries = (...maps) => {
for (const map of maps) {
if (isObject(map)) {
for (const k in map) {
const key = k;
const entry = map[key];
if (isObject(entry)) {
toWalk.push(entry);

@@ -483,13 +463,7 @@ }

};
var collectArrayEntries = function () {
var arrays = [];
for (var _i = 0; _i < arguments.length; _i++) {
arrays[_i] = arguments[_i];
}
for (var _a = 0, arrays_1 = arrays; _a < arrays_1.length; _a++) {
var array = arrays_1[_a];
const collectArrayEntries = (...arrays) => {
for (const array of arrays) {
if (Array.isArray(array)) {
for (var _b = 0, array_1 = array; _b < array_1.length; _b++) {
var entry = array_1[_b];
if (typeof entry === 'object') {
for (const entry of array) {
if (isObject(entry)) {
toWalk.push(entry);

@@ -501,4 +475,16 @@ }

};
var toWalk = [root];
var next = toWalk.pop();
const collectEntryOrArrayEntries = (items) => {
if (Array.isArray(items)) {
for (const entry of items) {
if (isObject(entry)) {
toWalk.push(entry);
}
}
}
else if (isObject(items)) {
toWalk.push(items);
}
};
const toWalk = [root];
let next = toWalk.pop();
while (next) {

@@ -508,17 +494,16 @@ if (!seen.has(next)) {

handle(next);
collectEntries(next.items, next.additionalItems, next.additionalProperties, next.not, next.contains, next.propertyNames, next.if, next.then, next.else);
collectMapEntries(next.definitions, next.properties, next.patternProperties, next.dependencies);
collectArrayEntries(next.anyOf, next.allOf, next.oneOf, next.items);
collectEntries(next.additionalItems, next.additionalProperties, next.not, next.contains, next.propertyNames, next.if, next.then, next.else, next.unevaluatedItems, next.unevaluatedProperties);
collectMapEntries(next.definitions, next.$defs, next.properties, next.patternProperties, next.dependencies, next.dependentSchemas);
collectArrayEntries(next.anyOf, next.allOf, next.oneOf, next.prefixItems);
collectEntryOrArrayEntries(next.items);
}
next = toWalk.pop();
}
};
}
;
JSONSchemaService.prototype.getSchemaFromProperty = function (resource, document) {
var _a, _b;
if (((_a = document.root) === null || _a === void 0 ? void 0 : _a.type) === 'object') {
for (var _i = 0, _c = document.root.properties; _i < _c.length; _i++) {
var p = _c[_i];
if (p.keyNode.value === '$schema' && ((_b = p.valueNode) === null || _b === void 0 ? void 0 : _b.type) === 'string') {
var schemaId = p.valueNode.value;
getSchemaFromProperty(resource, document) {
if (document.root?.type === 'object') {
for (const p of document.root.properties) {
if (p.keyNode.value === '$schema' && p.valueNode?.type === 'string') {
let schemaId = p.valueNode.value;
if (this.contextService && !/^\w[\w\d+.-]*:/.test(schemaId)) { // has scheme

@@ -532,12 +517,10 @@ schemaId = this.contextService.resolveRelativePath(schemaId, resource);

return undefined;
};
JSONSchemaService.prototype.getAssociatedSchemas = function (resource) {
var seen = Object.create(null);
var schemas = [];
var normalizedResource = normalizeResourceForMatching(resource);
for (var _i = 0, _a = this.filePatternAssociations; _i < _a.length; _i++) {
var entry = _a[_i];
}
getAssociatedSchemas(resource) {
const seen = Object.create(null);
const schemas = [];
const normalizedResource = normalizeResourceForMatching(resource);
for (const entry of this.filePatternAssociations) {
if (entry.matchesPattern(normalizedResource)) {
for (var _b = 0, _c = entry.getURIs(); _b < _c.length; _b++) {
var schemaId = _c[_b];
for (const schemaId of entry.getURIs()) {
if (!seen[schemaId]) {

@@ -551,5 +534,5 @@ schemas.push(schemaId);

return schemas;
};
JSONSchemaService.prototype.getSchemaURIsForResource = function (resource, document) {
var schemeId = document && this.getSchemaFromProperty(resource, document);
}
getSchemaURIsForResource(resource, document) {
let schemeId = document && this.getSchemaFromProperty(resource, document);
if (schemeId) {

@@ -559,9 +542,9 @@ return [schemeId];

return this.getAssociatedSchemas(resource);
};
JSONSchemaService.prototype.getSchemaForResource = function (resource, document) {
}
getSchemaForResource(resource, document) {
if (document) {
// first use $schema if present
var schemeId = this.getSchemaFromProperty(resource, document);
let schemeId = this.getSchemaFromProperty(resource, document);
if (schemeId) {
var id = normalizeId(schemeId);
const id = normalizeId(schemeId);
return this.getOrAddSchemaHandle(id).getResolvedSchema();

@@ -573,8 +556,8 @@ }

}
var schemas = this.getAssociatedSchemas(resource);
var resolvedSchema = schemas.length > 0 ? this.createCombinedSchema(resource, schemas).getResolvedSchema() : this.promise.resolve(undefined);
this.cachedSchemaForResource = { resource: resource, resolvedSchema: resolvedSchema };
const schemas = this.getAssociatedSchemas(resource);
const resolvedSchema = schemas.length > 0 ? this.createCombinedSchema(resource, schemas).getResolvedSchema() : this.promise.resolve(undefined);
this.cachedSchemaForResource = { resource, resolvedSchema };
return resolvedSchema;
};
JSONSchemaService.prototype.createCombinedSchema = function (resource, schemaIds) {
}
createCombinedSchema(resource, schemaIds) {
if (schemaIds.length === 1) {

@@ -584,28 +567,26 @@ return this.getOrAddSchemaHandle(schemaIds[0]);

else {
var combinedSchemaId = 'schemaservice://combinedSchema/' + encodeURIComponent(resource);
var combinedSchema = {
allOf: schemaIds.map(function (schemaId) { return ({ $ref: schemaId }); })
const combinedSchemaId = 'schemaservice://combinedSchema/' + encodeURIComponent(resource);
const combinedSchema = {
allOf: schemaIds.map(schemaId => ({ $ref: schemaId }))
};
return this.addSchemaHandle(combinedSchemaId, combinedSchema);
}
};
JSONSchemaService.prototype.getMatchingSchemas = function (document, jsonDocument, schema) {
}
getMatchingSchemas(document, jsonDocument, schema) {
if (schema) {
var id = schema.id || ('schemaservice://untitled/matchingSchemas/' + idCounter++);
var handle = this.addSchemaHandle(id, schema);
return handle.getResolvedSchema().then(function (resolvedSchema) {
return jsonDocument.getMatchingSchemas(resolvedSchema.schema).filter(function (s) { return !s.inverted; });
const id = schema.id || ('schemaservice://untitled/matchingSchemas/' + idCounter++);
const handle = this.addSchemaHandle(id, schema);
return handle.getResolvedSchema().then(resolvedSchema => {
return jsonDocument.getMatchingSchemas(resolvedSchema.schema).filter(s => !s.inverted);
});
}
return this.getSchemaForResource(document.uri, jsonDocument).then(function (schema) {
return this.getSchemaForResource(document.uri, jsonDocument).then(schema => {
if (schema) {
return jsonDocument.getMatchingSchemas(schema.schema).filter(function (s) { return !s.inverted; });
return jsonDocument.getMatchingSchemas(schema.schema).filter(s => !s.inverted);
}
return [];
});
};
return JSONSchemaService;
}());
export { JSONSchemaService };
var idCounter = 0;
}
}
let idCounter = 0;
function normalizeId(id) {

@@ -631,3 +612,3 @@ // remove trailing '#', normalize drive capitalization

try {
var uri = URI.parse(url);
const uri = URI.parse(url);
if (uri.scheme === 'file') {

@@ -634,0 +615,0 @@ return uri.fsPath;

@@ -9,5 +9,5 @@ /*---------------------------------------------------------------------------------------------

function getSelectionRange(position) {
var offset = document.offsetAt(position);
var node = doc.getNodeFromOffset(offset, true);
var result = [];
let offset = document.offsetAt(position);
let node = doc.getNodeFromOffset(offset, true);
const result = [];
while (node) {

@@ -19,3 +19,3 @@ switch (node.type) {

// range without ", [ or {
var cStart = node.offset + 1, cEnd = node.offset + node.length - 1;
const cStart = node.offset + 1, cEnd = node.offset + node.length - 1;
if (cStart < cEnd && offset >= cStart && offset <= cEnd) {

@@ -34,3 +34,3 @@ result.push(newRange(cStart, cEnd));

if (node.type === 'property' || node.parent && node.parent.type === 'array') {
var afterCommaOffset = getOffsetAfterNextToken(node.offset + node.length, 5 /* CommaToken */);
const afterCommaOffset = getOffsetAfterNextToken(node.offset + node.length, 5 /* CommaToken */);
if (afterCommaOffset !== -1) {

@@ -42,4 +42,4 @@ result.push(newRange(node.offset, afterCommaOffset));

}
var current = undefined;
for (var index = result.length - 1; index >= 0; index--) {
let current = undefined;
for (let index = result.length - 1; index >= 0; index--) {
current = SelectionRange.create(result[index], current);

@@ -55,6 +55,6 @@ }

}
var scanner = createScanner(document.getText(), true);
const scanner = createScanner(document.getText(), true);
function getOffsetAfterNextToken(offset, expectedToken) {
scanner.setPosition(offset);
var token = scanner.scan();
let token = scanner.scan();
if (token === expectedToken) {

@@ -61,0 +61,0 @@ return scanner.getTokenOffset() + scanner.getTokenLength();

@@ -8,5 +8,5 @@ /*---------------------------------------------------------------------------------------------

import { isBoolean } from '../utils/objects';
var localize = nls.loadMessageBundle();
var JSONValidation = /** @class */ (function () {
function JSONValidation(jsonSchemaService, promiseConstructor) {
const localize = nls.loadMessageBundle();
export class JSONValidation {
constructor(jsonSchemaService, promiseConstructor) {
this.jsonSchemaService = jsonSchemaService;

@@ -16,3 +16,3 @@ this.promise = promiseConstructor;

}
JSONValidation.prototype.configure = function (raw) {
configure(raw) {
if (raw) {

@@ -22,13 +22,12 @@ this.validationEnabled = raw.validate !== false;

}
};
JSONValidation.prototype.doValidation = function (textDocument, jsonDocument, documentSettings, schema) {
var _this = this;
}
doValidation(textDocument, jsonDocument, documentSettings, schema) {
if (!this.validationEnabled) {
return this.promise.resolve([]);
}
var diagnostics = [];
var added = {};
var addProblem = function (problem) {
const diagnostics = [];
const added = {};
const addProblem = (problem) => {
// remove duplicated messages
var signature = problem.range.start.line + ' ' + problem.range.start.character + ' ' + problem.message;
const signature = problem.range.start.line + ' ' + problem.range.start.character + ' ' + problem.message;
if (!added[signature]) {

@@ -39,23 +38,31 @@ added[signature] = true;

};
var getDiagnostics = function (schema) {
var trailingCommaSeverity = (documentSettings === null || documentSettings === void 0 ? void 0 : documentSettings.trailingCommas) ? toDiagnosticSeverity(documentSettings.trailingCommas) : DiagnosticSeverity.Error;
var commentSeverity = (documentSettings === null || documentSettings === void 0 ? void 0 : documentSettings.comments) ? toDiagnosticSeverity(documentSettings.comments) : _this.commentSeverity;
var schemaValidation = (documentSettings === null || documentSettings === void 0 ? void 0 : documentSettings.schemaValidation) ? toDiagnosticSeverity(documentSettings.schemaValidation) : DiagnosticSeverity.Warning;
var schemaRequest = (documentSettings === null || documentSettings === void 0 ? void 0 : documentSettings.schemaRequest) ? toDiagnosticSeverity(documentSettings.schemaRequest) : DiagnosticSeverity.Warning;
const getDiagnostics = (schema) => {
let trailingCommaSeverity = documentSettings?.trailingCommas ? toDiagnosticSeverity(documentSettings.trailingCommas) : DiagnosticSeverity.Error;
let commentSeverity = documentSettings?.comments ? toDiagnosticSeverity(documentSettings.comments) : this.commentSeverity;
let schemaValidation = documentSettings?.schemaValidation ? toDiagnosticSeverity(documentSettings.schemaValidation) : DiagnosticSeverity.Warning;
let schemaRequest = documentSettings?.schemaRequest ? toDiagnosticSeverity(documentSettings.schemaRequest) : DiagnosticSeverity.Warning;
if (schema) {
if (schema.errors.length && jsonDocument.root && schemaRequest) {
var astRoot = jsonDocument.root;
var property = astRoot.type === 'object' ? astRoot.properties[0] : undefined;
if (property && property.keyNode.value === '$schema') {
var node = property.valueNode || property;
var range = Range.create(textDocument.positionAt(node.offset), textDocument.positionAt(node.offset + node.length));
addProblem(Diagnostic.create(range, schema.errors[0], schemaRequest, ErrorCode.SchemaResolveError));
const addSchemaProblem = (errorMessage, errorCode) => {
if (jsonDocument.root && schemaRequest) {
const astRoot = jsonDocument.root;
const property = astRoot.type === 'object' ? astRoot.properties[0] : undefined;
if (property && property.keyNode.value === '$schema') {
const node = property.valueNode || property;
const range = Range.create(textDocument.positionAt(node.offset), textDocument.positionAt(node.offset + node.length));
addProblem(Diagnostic.create(range, errorMessage, schemaRequest, errorCode));
}
else {
const range = Range.create(textDocument.positionAt(astRoot.offset), textDocument.positionAt(astRoot.offset + 1));
addProblem(Diagnostic.create(range, errorMessage, schemaRequest, errorCode));
}
}
else {
var range = Range.create(textDocument.positionAt(astRoot.offset), textDocument.positionAt(astRoot.offset + 1));
addProblem(Diagnostic.create(range, schema.errors[0], schemaRequest, ErrorCode.SchemaResolveError));
}
};
if (schema.errors.length) {
addSchemaProblem(schema.errors[0], ErrorCode.SchemaResolveError);
}
else if (schemaValidation) {
var semanticErrors = jsonDocument.validate(textDocument, schema.schema, schemaValidation);
for (const warning of schema.warnings) {
addSchemaProblem(warning, ErrorCode.SchemaUnsupportedFeature);
}
const semanticErrors = jsonDocument.validate(textDocument, schema.schema, schemaValidation);
if (semanticErrors) {

@@ -72,4 +79,3 @@ semanticErrors.forEach(addProblem);

}
for (var _i = 0, _a = jsonDocument.syntaxErrors; _i < _a.length; _i++) {
var p = _a[_i];
for (const p of jsonDocument.syntaxErrors) {
if (p.code === ErrorCode.TrailingComma) {

@@ -84,5 +90,5 @@ if (typeof trailingCommaSeverity !== 'number') {

if (typeof commentSeverity === 'number') {
var message_1 = localize('InvalidCommentToken', 'Comments are not permitted in JSON.');
jsonDocument.comments.forEach(function (c) {
addProblem(Diagnostic.create(c, message_1, commentSeverity, ErrorCode.CommentNotPermitted));
const message = localize('InvalidCommentToken', 'Comments are not permitted in JSON.');
jsonDocument.comments.forEach(c => {
addProblem(Diagnostic.create(c, message, commentSeverity, ErrorCode.CommentNotPermitted));
});

@@ -93,19 +99,17 @@ }

if (schema) {
var id = schema.id || ('schemaservice://untitled/' + idCounter++);
var handle = this.jsonSchemaService.registerExternalSchema(id, [], schema);
return handle.getResolvedSchema().then(function (resolvedSchema) {
const id = schema.id || ('schemaservice://untitled/' + idCounter++);
const handle = this.jsonSchemaService.registerExternalSchema(id, [], schema);
return handle.getResolvedSchema().then(resolvedSchema => {
return getDiagnostics(resolvedSchema);
});
}
return this.jsonSchemaService.getSchemaForResource(textDocument.uri, jsonDocument).then(function (schema) {
return this.jsonSchemaService.getSchemaForResource(textDocument.uri, jsonDocument).then(schema => {
return getDiagnostics(schema);
});
};
JSONValidation.prototype.getLanguageStatus = function (textDocument, jsonDocument) {
}
getLanguageStatus(textDocument, jsonDocument) {
return { schemas: this.jsonSchemaService.getSchemaURIsForResource(textDocument.uri, jsonDocument) };
};
return JSONValidation;
}());
export { JSONValidation };
var idCounter = 0;
}
}
let idCounter = 0;
function schemaAllowsComments(schemaRef) {

@@ -117,5 +121,4 @@ if (schemaRef && typeof schemaRef === 'object') {

if (schemaRef.allOf) {
for (var _i = 0, _a = schemaRef.allOf; _i < _a.length; _i++) {
var schema = _a[_i];
var allow = schemaAllowsComments(schema);
for (const schema of schemaRef.allOf) {
const allow = schemaAllowsComments(schema);
if (isBoolean(allow)) {

@@ -134,3 +137,3 @@ return allow;

}
var deprSchemaRef = schemaRef;
const deprSchemaRef = schemaRef;
if (isBoolean(deprSchemaRef['allowsTrailingCommas'])) { // deprecated

@@ -140,5 +143,4 @@ return deprSchemaRef['allowsTrailingCommas'];

if (schemaRef.allOf) {
for (var _i = 0, _a = schemaRef.allOf; _i < _a.length; _i++) {
var schema = _a[_i];
var allow = schemaAllowsTrailingCommas(schema);
for (const schema of schemaRef.allOf) {
const allow = schemaAllowsTrailingCommas(schema);
if (isBoolean(allow)) {

@@ -145,0 +147,0 @@ return allow;

@@ -5,7 +5,7 @@ /*---------------------------------------------------------------------------------------------

*--------------------------------------------------------------------------------------------*/
var Digit0 = 48;
var Digit9 = 57;
var A = 65;
var a = 97;
var f = 102;
const Digit0 = 48;
const Digit9 = 57;
const A = 65;
const a = 97;
const f = 102;
export function hexDigit(charCode) {

@@ -62,4 +62,3 @@ if (charCode < Digit0) {

}
export function colorFrom256RGB(red, green, blue, alpha) {
if (alpha === void 0) { alpha = 1.0; }
export function colorFrom256RGB(red, green, blue, alpha = 1.0) {
return {

@@ -69,4 +68,4 @@ red: red / 255.0,

blue: blue / 255.0,
alpha: alpha
alpha
};
}

@@ -10,9 +10,9 @@ /*---------------------------------------------------------------------------------------------

}
var str = String(glob);
const str = String(glob);
// The regexp we are building, as a string.
var reStr = "";
let reStr = "";
// Whether we are matching so called "extended" globs (like bash) and should
// support single character matching, matching ranges of characters, group
// matching, etc.
var extended = opts ? !!opts.extended : false;
const extended = opts ? !!opts.extended : false;
// When globstar is _false_ (default), '/foo/*' is translated a regexp like

@@ -27,10 +27,10 @@ // '^\/foo\/.*$' which will match any string beginning with '/foo/'

// globstar is _false_
var globstar = opts ? !!opts.globstar : false;
const globstar = opts ? !!opts.globstar : false;
// If we are doing extended matching, this boolean is true when we are inside
// a group (eg {*.html,*.js}), and false otherwise.
var inGroup = false;
let inGroup = false;
// RegExp flags (eg "i" ) to pass in to RegExp constructor.
var flags = opts && typeof (opts.flags) === "string" ? opts.flags : "";
var c;
for (var i = 0, len = str.length; i < len; i++) {
const flags = opts && typeof (opts.flags) === "string" ? opts.flags : "";
let c;
for (let i = 0, len = str.length; i < len; i++) {
c = str[i];

@@ -83,4 +83,4 @@ switch (c) {

// Also store the previous and next characters
var prevChar = str[i - 1];
var starCount = 1;
const prevChar = str[i - 1];
let starCount = 1;
while (str[i + 1] === "*") {

@@ -90,3 +90,3 @@ starCount++;

}
var nextChar = str[i + 1];
const nextChar = str[i + 1];
if (!globstar) {

@@ -98,3 +98,3 @@ // globstar is disabled, so treat any number of "*" as one

// globstar is enabled, so determine if this is a globstar segment
var isGlobstar = starCount > 1 // multiple "*"'s
const isGlobstar = starCount > 1 // multiple "*"'s
&& (prevChar === "/" || prevChar === undefined || prevChar === '{' || prevChar === ',') // from the start of the segment

@@ -101,0 +101,0 @@ && (nextChar === "/" || nextChar === undefined || nextChar === ',' || nextChar === '}'); // to the end of the segment

@@ -7,3 +7,3 @@ /*---------------------------------------------------------------------------------------------

if (obj !== null && typeof obj === 'object') {
var newIndent = indent + '\t';
const newIndent = indent + '\t';
if (Array.isArray(obj)) {

@@ -13,4 +13,4 @@ if (obj.length === 0) {

}
var result = '[\n';
for (var i = 0; i < obj.length; i++) {
let result = '[\n';
for (let i = 0; i < obj.length; i++) {
result += newIndent + stringifyObject(obj[i], newIndent, stringifyLiteral);

@@ -26,9 +26,9 @@ if (i < obj.length - 1) {

else {
var keys = Object.keys(obj);
const keys = Object.keys(obj);
if (keys.length === 0) {
return '{}';
}
var result = '{\n';
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
let result = '{\n';
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
result += newIndent + JSON.stringify(key) + ': ' + stringifyObject(obj[key], newIndent, stringifyLiteral);

@@ -35,0 +35,0 @@ if (i < keys.length - 1) {

@@ -66,1 +66,4 @@ /*---------------------------------------------------------------------------------------------

}
export function isObject(val) {
return typeof val === 'object' && val !== null && !Array.isArray(val);
}

@@ -9,3 +9,3 @@ /*---------------------------------------------------------------------------------------------

}
for (var i = 0; i < needle.length; i++) {
for (let i = 0; i < needle.length; i++) {
if (haystack[i] !== needle[i]) {

@@ -21,3 +21,3 @@ return false;

export function endsWith(haystack, needle) {
var diff = haystack.length - needle.length;
const diff = haystack.length - needle.length;
if (diff > 0) {

@@ -48,3 +48,3 @@ return haystack.lastIndexOf(needle) === diff;

export function extendedRegExp(pattern) {
var flags = '';
let flags = '';
if (startsWith(pattern, '(?i)')) {

@@ -51,0 +51,0 @@ pattern = pattern.substring(4);

@@ -0,0 +0,0 @@ import { Thenable, MarkedString, CompletionItem } from './jsonLanguageService';

@@ -0,0 +0,0 @@ (function (factory) {

@@ -0,0 +0,0 @@ import { Thenable, ASTNode, Color, ColorInformation, ColorPresentation, LanguageServiceParams, LanguageSettings, DocumentLanguageSettings, FoldingRange, JSONSchema, SelectionRange, FoldingRangesContext, DocumentSymbolsContext, ColorInformationContext as DocumentColorsContext, TextDocument, Position, CompletionItem, CompletionList, Hover, Range, SymbolInformation, Diagnostic, TextEdit, FormattingOptions, DocumentSymbol, DefinitionLink, MatchingSchema, JSONLanguageStatus } from './jsonLanguageTypes';

@@ -27,28 +27,28 @@ /*---------------------------------------------------------------------------------------------

exports.getLanguageService = void 0;
var jsonCompletion_1 = require("./services/jsonCompletion");
var jsonHover_1 = require("./services/jsonHover");
var jsonValidation_1 = require("./services/jsonValidation");
var jsonDocumentSymbols_1 = require("./services/jsonDocumentSymbols");
var jsonParser_1 = require("./parser/jsonParser");
var configuration_1 = require("./services/configuration");
var jsonSchemaService_1 = require("./services/jsonSchemaService");
var jsonFolding_1 = require("./services/jsonFolding");
var jsonSelectionRanges_1 = require("./services/jsonSelectionRanges");
var jsonc_parser_1 = require("jsonc-parser");
var jsonLanguageTypes_1 = require("./jsonLanguageTypes");
var jsonLinks_1 = require("./services/jsonLinks");
const jsonCompletion_1 = require("./services/jsonCompletion");
const jsonHover_1 = require("./services/jsonHover");
const jsonValidation_1 = require("./services/jsonValidation");
const jsonDocumentSymbols_1 = require("./services/jsonDocumentSymbols");
const jsonParser_1 = require("./parser/jsonParser");
const configuration_1 = require("./services/configuration");
const jsonSchemaService_1 = require("./services/jsonSchemaService");
const jsonFolding_1 = require("./services/jsonFolding");
const jsonSelectionRanges_1 = require("./services/jsonSelectionRanges");
const jsonc_parser_1 = require("jsonc-parser");
const jsonLanguageTypes_1 = require("./jsonLanguageTypes");
const jsonLinks_1 = require("./services/jsonLinks");
__exportStar(require("./jsonLanguageTypes"), exports);
function getLanguageService(params) {
var promise = params.promiseConstructor || Promise;
var jsonSchemaService = new jsonSchemaService_1.JSONSchemaService(params.schemaRequestService, params.workspaceContext, promise);
const promise = params.promiseConstructor || Promise;
const jsonSchemaService = new jsonSchemaService_1.JSONSchemaService(params.schemaRequestService, params.workspaceContext, promise);
jsonSchemaService.setSchemaContributions(configuration_1.schemaContributions);
var jsonCompletion = new jsonCompletion_1.JSONCompletion(jsonSchemaService, params.contributions, promise, params.clientCapabilities);
var jsonHover = new jsonHover_1.JSONHover(jsonSchemaService, params.contributions, promise);
var jsonDocumentSymbols = new jsonDocumentSymbols_1.JSONDocumentSymbols(jsonSchemaService);
var jsonValidation = new jsonValidation_1.JSONValidation(jsonSchemaService, promise);
const jsonCompletion = new jsonCompletion_1.JSONCompletion(jsonSchemaService, params.contributions, promise, params.clientCapabilities);
const jsonHover = new jsonHover_1.JSONHover(jsonSchemaService, params.contributions, promise);
const jsonDocumentSymbols = new jsonDocumentSymbols_1.JSONDocumentSymbols(jsonSchemaService);
const jsonValidation = new jsonValidation_1.JSONValidation(jsonSchemaService, promise);
return {
configure: function (settings) {
configure: (settings) => {
jsonSchemaService.clearExternalSchemas();
if (settings.schemas) {
settings.schemas.forEach(function (settings) {
settings.schemas.forEach(settings => {
jsonSchemaService.registerExternalSchema(settings.uri, settings.fileMatch, settings.schema);

@@ -59,7 +59,7 @@ });

},
resetSchema: function (uri) { return jsonSchemaService.onResourceChange(uri); },
resetSchema: (uri) => jsonSchemaService.onResourceChange(uri),
doValidation: jsonValidation.doValidation.bind(jsonValidation),
getLanguageStatus: jsonValidation.getLanguageStatus.bind(jsonValidation),
parseJSONDocument: function (document) { return (0, jsonParser_1.parse)(document, { collectComments: true }); },
newJSONDocument: function (root, diagnostics) { return (0, jsonParser_1.newJSONDocument)(root, diagnostics); },
parseJSONDocument: (document) => (0, jsonParser_1.parse)(document, { collectComments: true }),
newJSONDocument: (root, diagnostics) => (0, jsonParser_1.newJSONDocument)(root, diagnostics),
getMatchingSchemas: jsonSchemaService.getMatchingSchemas.bind(jsonSchemaService),

@@ -75,13 +75,13 @@ doResolve: jsonCompletion.doResolve.bind(jsonCompletion),

getSelectionRanges: jsonSelectionRanges_1.getSelectionRanges,
findDefinition: function () { return Promise.resolve([]); },
findDefinition: () => Promise.resolve([]),
findLinks: jsonLinks_1.findLinks,
format: function (d, r, o) {
var range = undefined;
format: (d, r, o) => {
let range = undefined;
if (r) {
var offset = d.offsetAt(r.start);
var length = d.offsetAt(r.end) - offset;
range = { offset: offset, length: length };
const offset = d.offsetAt(r.start);
const length = d.offsetAt(r.end) - offset;
range = { offset, length };
}
var options = { tabSize: o ? o.tabSize : 4, insertSpaces: (o === null || o === void 0 ? void 0 : o.insertSpaces) === true, insertFinalNewline: (o === null || o === void 0 ? void 0 : o.insertFinalNewline) === true, eol: '\n' };
return (0, jsonc_parser_1.format)(d.getText(), range, options).map(function (e) {
const options = { tabSize: o ? o.tabSize : 4, insertSpaces: o?.insertSpaces === true, insertFinalNewline: o?.insertFinalNewline === true, eol: '\n' };
return (0, jsonc_parser_1.format)(d.getText(), range, options).map(e => {
return jsonLanguageTypes_1.TextEdit.replace(jsonLanguageTypes_1.Range.create(d.positionAt(e.offset), d.positionAt(e.offset + e.length)), e.content);

@@ -88,0 +88,0 @@ });

@@ -28,3 +28,4 @@ import { JSONWorkerContribution, JSONPath, Segment, CompletionsCollector } from './jsonContributions';

CommentNotPermitted = 521,
SchemaResolveError = 768
SchemaResolveError = 768,
SchemaUnsupportedFeature = 769
}

@@ -31,0 +32,0 @@ export declare type ASTNode = ObjectASTNode | PropertyASTNode | ArrayASTNode | StringASTNode | NumberASTNode | BooleanASTNode | NullASTNode;

@@ -17,3 +17,3 @@ /*---------------------------------------------------------------------------------------------

exports.ClientCapabilities = exports.ErrorCode = exports.DocumentHighlightKind = exports.VersionedTextDocumentIdentifier = exports.TextDocumentEdit = exports.CodeActionKind = exports.TextEdit = exports.WorkspaceEdit = exports.DocumentLink = exports.DocumentHighlight = exports.CodeAction = exports.Command = exports.CodeActionContext = exports.MarkedString = exports.Hover = exports.Location = exports.DocumentSymbol = exports.SymbolKind = exports.SymbolInformation = exports.InsertTextFormat = exports.CompletionItemTag = exports.CompletionList = exports.CompletionItemKind = exports.CompletionItem = exports.DiagnosticSeverity = exports.Diagnostic = exports.SelectionRange = exports.FoldingRangeKind = exports.FoldingRange = exports.ColorPresentation = exports.ColorInformation = exports.Color = exports.MarkupKind = exports.MarkupContent = exports.Position = exports.Range = exports.TextDocument = void 0;
var vscode_languageserver_types_1 = require("vscode-languageserver-types");
const vscode_languageserver_types_1 = require("vscode-languageserver-types");
Object.defineProperty(exports, "Range", { enumerable: true, get: function () { return vscode_languageserver_types_1.Range; } });

@@ -53,3 +53,3 @@ Object.defineProperty(exports, "Position", { enumerable: true, get: function () { return vscode_languageserver_types_1.Position; } });

Object.defineProperty(exports, "DocumentHighlightKind", { enumerable: true, get: function () { return vscode_languageserver_types_1.DocumentHighlightKind; } });
var vscode_languageserver_textdocument_1 = require("vscode-languageserver-textdocument");
const vscode_languageserver_textdocument_1 = require("vscode-languageserver-textdocument");
Object.defineProperty(exports, "TextDocument", { enumerable: true, get: function () { return vscode_languageserver_textdocument_1.TextDocument; } });

@@ -80,2 +80,3 @@ /**

ErrorCode[ErrorCode["SchemaResolveError"] = 768] = "SchemaResolveError";
ErrorCode[ErrorCode["SchemaUnsupportedFeature"] = 769] = "SchemaUnsupportedFeature";
})(ErrorCode = exports.ErrorCode || (exports.ErrorCode = {}));

@@ -82,0 +83,0 @@ var ClientCapabilities;

@@ -15,3 +15,3 @@ export declare type JSONSchemaRef = JSONSchema | boolean;

patternProperties?: JSONSchemaMap;
additionalProperties?: boolean | JSONSchemaRef;
additionalProperties?: JSONSchemaRef;
minProperties?: number;

@@ -26,3 +26,3 @@ maxProperties?: number;

uniqueItems?: boolean;
additionalItems?: boolean | JSONSchemaRef;
additionalItems?: JSONSchemaRef;
pattern?: string;

@@ -52,2 +52,21 @@ minLength?: number;

else?: JSONSchemaRef;
unevaluatedProperties?: boolean | JSONSchemaRef;
unevaluatedItems?: boolean | JSONSchemaRef;
minContains?: number;
maxContains?: number;
deprecated?: boolean;
dependentRequired?: {
[prop: string]: string[];
};
dependentSchemas?: JSONSchemaMap;
$defs?: {
[name: string]: JSONSchema;
};
$anchor?: string;
$recursiveRef?: string;
$recursiveAnchor?: string;
$vocabulary?: any;
prefixItems?: JSONSchemaRef[];
$dynamicRef?: string;
$dynamicAnchor?: string;
defaultSnippets?: {

@@ -54,0 +73,0 @@ label?: string;

@@ -0,0 +0,0 @@ (function (factory) {

@@ -17,4 +17,4 @@ /*---------------------------------------------------------------------------------------------

exports.schemaContributions = void 0;
var nls = require("vscode-nls");
var localize = nls.loadMessageBundle();
const nls = require("vscode-nls");
const localize = nls.loadMessageBundle();
exports.schemaContributions = {

@@ -478,3 +478,3 @@ schemaAssociations: [],

};
var descriptions = {
const descriptions = {
id: localize('schema.json.id', "A unique identifier for the schema."),

@@ -527,10 +527,10 @@ $schema: localize('schema.json.$schema', "The schema to verify this document against."),

};
for (var schemaName in exports.schemaContributions.schemas) {
var schema = exports.schemaContributions.schemas[schemaName];
for (var property in schema.properties) {
var propertyObject = schema.properties[property];
for (const schemaName in exports.schemaContributions.schemas) {
const schema = exports.schemaContributions.schemas[schemaName];
for (const property in schema.properties) {
let propertyObject = schema.properties[property];
if (typeof propertyObject === 'boolean') {
propertyObject = schema.properties[property] = {};
}
var description = descriptions[property];
const description = descriptions[property];
if (description) {

@@ -540,3 +540,3 @@ propertyObject['description'] = description;

else {
console.log("".concat(property, ": localize('schema.json.").concat(property, "', \"\")"));
console.log(`${property}: localize('schema.json.${property}', "")`);
}

@@ -543,0 +543,0 @@ }

@@ -17,17 +17,14 @@ /*---------------------------------------------------------------------------------------------

exports.JSONCompletion = void 0;
var Parser = require("../parser/jsonParser");
var Json = require("jsonc-parser");
var json_1 = require("../utils/json");
var strings_1 = require("../utils/strings");
var objects_1 = require("../utils/objects");
var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
var nls = require("vscode-nls");
var localize = nls.loadMessageBundle();
var valueCommitCharacters = [',', '}', ']'];
var propertyCommitCharacters = [':'];
var JSONCompletion = /** @class */ (function () {
function JSONCompletion(schemaService, contributions, promiseConstructor, clientCapabilities) {
if (contributions === void 0) { contributions = []; }
if (promiseConstructor === void 0) { promiseConstructor = Promise; }
if (clientCapabilities === void 0) { clientCapabilities = {}; }
const Parser = require("../parser/jsonParser");
const Json = require("jsonc-parser");
const json_1 = require("../utils/json");
const strings_1 = require("../utils/strings");
const objects_1 = require("../utils/objects");
const jsonLanguageTypes_1 = require("../jsonLanguageTypes");
const nls = require("vscode-nls");
const localize = nls.loadMessageBundle();
const valueCommitCharacters = [',', '}', ']'];
const propertyCommitCharacters = [':'];
class JSONCompletion {
constructor(schemaService, contributions = [], promiseConstructor = Promise, clientCapabilities = {}) {
this.schemaService = schemaService;

@@ -38,7 +35,7 @@ this.contributions = contributions;

}
JSONCompletion.prototype.doResolve = function (item) {
for (var i = this.contributions.length - 1; i >= 0; i--) {
var resolveCompletion = this.contributions[i].resolveCompletion;
doResolve(item) {
for (let i = this.contributions.length - 1; i >= 0; i--) {
const resolveCompletion = this.contributions[i].resolveCompletion;
if (resolveCompletion) {
var resolver = resolveCompletion(item);
const resolver = resolveCompletion(item);
if (resolver) {

@@ -50,12 +47,11 @@ return resolver;

return this.promiseConstructor.resolve(item);
};
JSONCompletion.prototype.doComplete = function (document, position, doc) {
var _this = this;
var result = {
}
doComplete(document, position, doc) {
const result = {
items: [],
isIncomplete: false
};
var text = document.getText();
var offset = document.offsetAt(position);
var node = doc.getNodeFromOffset(offset, true);
const text = document.getText();
const offset = document.offsetAt(position);
let node = doc.getNodeFromOffset(offset, true);
if (this.isInComment(document, node ? node.offset : 0, offset)) {

@@ -65,3 +61,3 @@ return Promise.resolve(result);

if (node && (offset === node.offset + node.length) && offset > 0) {
var ch = text[offset - 1];
const ch = text[offset - 1];
if (node.type === 'object' && ch === '}' || node.type === 'array' && ch === ']') {

@@ -72,4 +68,4 @@ // after ] or }

}
var currentWord = this.getCurrentWord(document, offset);
var overwriteRange;
const currentWord = this.getCurrentWord(document, offset);
let overwriteRange;
if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {

@@ -79,3 +75,3 @@ overwriteRange = jsonLanguageTypes_1.Range.create(document.positionAt(node.offset), document.positionAt(node.offset + node.length));

else {
var overwriteStart = offset - currentWord.length;
let overwriteStart = offset - currentWord.length;
if (overwriteStart > 0 && text[overwriteStart - 1] === '"') {

@@ -86,12 +82,12 @@ overwriteStart--;

}
var supportsCommitCharacters = false; //this.doesSupportsCommitCharacters(); disabled for now, waiting for new API: https://github.com/microsoft/vscode/issues/42544
var proposed = {};
var collector = {
add: function (suggestion) {
var label = suggestion.label;
var existing = proposed[label];
const supportsCommitCharacters = false; //this.doesSupportsCommitCharacters(); disabled for now, waiting for new API: https://github.com/microsoft/vscode/issues/42544
const proposed = {};
const collector = {
add: (suggestion) => {
let label = suggestion.label;
const existing = proposed[label];
if (!existing) {
label = label.replace(/[\n]/g, '↵');
if (label.length > 60) {
var shortendedLabel = label.substr(0, 57).trim() + '...';
const shortendedLabel = label.substr(0, 57).trim() + '...';
if (!proposed[shortendedLabel]) {

@@ -120,23 +116,23 @@ label = shortendedLabel;

},
setAsIncomplete: function () {
setAsIncomplete: () => {
result.isIncomplete = true;
},
error: function (message) {
error: (message) => {
console.error(message);
},
log: function (message) {
log: (message) => {
console.log(message);
},
getNumberOfProposals: function () {
getNumberOfProposals: () => {
return result.items.length;
}
};
return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
var collectionPromises = [];
var addValue = true;
var currentKey = '';
var currentProperty = undefined;
return this.schemaService.getSchemaForResource(document.uri, doc).then((schema) => {
const collectionPromises = [];
let addValue = true;
let currentKey = '';
let currentProperty = undefined;
if (node) {
if (node.type === 'string') {
var parent = node.parent;
const parent = node.parent;
if (parent && parent.type === 'property' && parent.keyNode === node) {

@@ -159,4 +155,4 @@ addValue = !parent.valueNode;

// don't suggest properties that are already present
var properties = node.properties;
properties.forEach(function (p) {
const properties = node.properties;
properties.forEach(p => {
if (!currentProperty || currentProperty !== p) {

@@ -166,17 +162,17 @@ proposed[p.keyNode.value] = jsonLanguageTypes_1.CompletionItem.create('__');

});
var separatorAfter_1 = '';
let separatorAfter = '';
if (addValue) {
separatorAfter_1 = _this.evaluateSeparatorAfter(document, document.offsetAt(overwriteRange.end));
separatorAfter = this.evaluateSeparatorAfter(document, document.offsetAt(overwriteRange.end));
}
if (schema) {
// property proposals with schema
_this.getPropertyCompletions(schema, doc, node, addValue, separatorAfter_1, collector);
this.getPropertyCompletions(schema, doc, node, addValue, separatorAfter, collector);
}
else {
// property proposals without schema
_this.getSchemaLessPropertyCompletions(doc, node, currentKey, collector);
this.getSchemaLessPropertyCompletions(doc, node, currentKey, collector);
}
var location_1 = Parser.getNodePath(node);
_this.contributions.forEach(function (contribution) {
var collectPromise = contribution.collectPropertyCompletions(document.uri, location_1, currentWord, addValue, separatorAfter_1 === '', collector);
const location = Parser.getNodePath(node);
this.contributions.forEach((contribution) => {
const collectPromise = contribution.collectPropertyCompletions(document.uri, location, currentWord, addValue, separatorAfter === '', collector);
if (collectPromise) {

@@ -189,4 +185,4 @@ collectionPromises.push(collectPromise);

kind: jsonLanguageTypes_1.CompletionItemKind.Property,
label: _this.getLabelForValue(currentWord),
insertText: _this.getInsertTextForProperty(currentWord, undefined, false, separatorAfter_1),
label: this.getLabelForValue(currentWord),
insertText: this.getInsertTextForProperty(currentWord, undefined, false, separatorAfter),
insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet, documentation: '',

@@ -198,22 +194,22 @@ });

// proposals for values
var types = {};
const types = {};
if (schema) {
// value proposals with schema
_this.getValueCompletions(schema, doc, node, offset, document, collector, types);
this.getValueCompletions(schema, doc, node, offset, document, collector, types);
}
else {
// value proposals without schema
_this.getSchemaLessValueCompletions(doc, node, offset, document, collector);
this.getSchemaLessValueCompletions(doc, node, offset, document, collector);
}
if (_this.contributions.length > 0) {
_this.getContributedValueCompletions(doc, node, offset, document, collector, collectionPromises);
if (this.contributions.length > 0) {
this.getContributedValueCompletions(doc, node, offset, document, collector, collectionPromises);
}
return _this.promiseConstructor.all(collectionPromises).then(function () {
return this.promiseConstructor.all(collectionPromises).then(() => {
if (collector.getNumberOfProposals() === 0) {
var offsetForSeparator = offset;
let offsetForSeparator = offset;
if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
offsetForSeparator = node.offset + node.length;
}
var separatorAfter = _this.evaluateSeparatorAfter(document, offsetForSeparator);
_this.addFillerValueCompletions(types, separatorAfter, collector);
const separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator);
this.addFillerValueCompletions(types, separatorAfter, collector);
}

@@ -223,20 +219,19 @@ return result;

});
};
JSONCompletion.prototype.getPropertyCompletions = function (schema, doc, node, addValue, separatorAfter, collector) {
var _this = this;
var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset);
matchingSchemas.forEach(function (s) {
}
getPropertyCompletions(schema, doc, node, addValue, separatorAfter, collector) {
const matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset);
matchingSchemas.forEach((s) => {
if (s.node === node && !s.inverted) {
var schemaProperties_1 = s.schema.properties;
if (schemaProperties_1) {
Object.keys(schemaProperties_1).forEach(function (key) {
var propertySchema = schemaProperties_1[key];
const schemaProperties = s.schema.properties;
if (schemaProperties) {
Object.keys(schemaProperties).forEach((key) => {
const propertySchema = schemaProperties[key];
if (typeof propertySchema === 'object' && !propertySchema.deprecationMessage && !propertySchema.doNotSuggest) {
var proposal = {
const proposal = {
kind: jsonLanguageTypes_1.CompletionItemKind.Property,
label: key,
insertText: _this.getInsertTextForProperty(key, propertySchema, addValue, separatorAfter),
insertText: this.getInsertTextForProperty(key, propertySchema, addValue, separatorAfter),
insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
filterText: _this.getFilterTextForValue(key),
documentation: _this.fromMarkup(propertySchema.markdownDescription) || propertySchema.description || '',
filterText: this.getFilterTextForValue(key),
documentation: this.fromMarkup(propertySchema.markdownDescription) || propertySchema.description || '',
};

@@ -246,3 +241,3 @@ if (propertySchema.suggestSortText !== undefined) {

}
if (proposal.insertText && (0, strings_1.endsWith)(proposal.insertText, "$1".concat(separatorAfter))) {
if (proposal.insertText && (0, strings_1.endsWith)(proposal.insertText, `$1${separatorAfter}`)) {
proposal.command = {

@@ -257,18 +252,17 @@ title: 'Suggest',

}
var schemaPropertyNames_1 = s.schema.propertyNames;
if (typeof schemaPropertyNames_1 === 'object' && !schemaPropertyNames_1.deprecationMessage && !schemaPropertyNames_1.doNotSuggest) {
var propertyNameCompletionItem = function (name, enumDescription) {
if (enumDescription === void 0) { enumDescription = undefined; }
var proposal = {
const schemaPropertyNames = s.schema.propertyNames;
if (typeof schemaPropertyNames === 'object' && !schemaPropertyNames.deprecationMessage && !schemaPropertyNames.doNotSuggest) {
const propertyNameCompletionItem = (name, enumDescription = undefined) => {
const proposal = {
kind: jsonLanguageTypes_1.CompletionItemKind.Property,
label: name,
insertText: _this.getInsertTextForProperty(name, undefined, addValue, separatorAfter),
insertText: this.getInsertTextForProperty(name, undefined, addValue, separatorAfter),
insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
filterText: _this.getFilterTextForValue(name),
documentation: enumDescription || _this.fromMarkup(schemaPropertyNames_1.markdownDescription) || schemaPropertyNames_1.description || '',
filterText: this.getFilterTextForValue(name),
documentation: enumDescription || this.fromMarkup(schemaPropertyNames.markdownDescription) || schemaPropertyNames.description || '',
};
if (schemaPropertyNames_1.suggestSortText !== undefined) {
proposal.sortText = schemaPropertyNames_1.suggestSortText;
if (schemaPropertyNames.suggestSortText !== undefined) {
proposal.sortText = schemaPropertyNames.suggestSortText;
}
if (proposal.insertText && (0, strings_1.endsWith)(proposal.insertText, "$1".concat(separatorAfter))) {
if (proposal.insertText && (0, strings_1.endsWith)(proposal.insertText, `$1${separatorAfter}`)) {
proposal.command = {

@@ -281,16 +275,16 @@ title: 'Suggest',

};
if (schemaPropertyNames_1.enum) {
for (var i = 0; i < schemaPropertyNames_1.enum.length; i++) {
var enumDescription = undefined;
if (schemaPropertyNames_1.markdownEnumDescriptions && i < schemaPropertyNames_1.markdownEnumDescriptions.length) {
enumDescription = _this.fromMarkup(schemaPropertyNames_1.markdownEnumDescriptions[i]);
if (schemaPropertyNames.enum) {
for (let i = 0; i < schemaPropertyNames.enum.length; i++) {
let enumDescription = undefined;
if (schemaPropertyNames.markdownEnumDescriptions && i < schemaPropertyNames.markdownEnumDescriptions.length) {
enumDescription = this.fromMarkup(schemaPropertyNames.markdownEnumDescriptions[i]);
}
else if (schemaPropertyNames_1.enumDescriptions && i < schemaPropertyNames_1.enumDescriptions.length) {
enumDescription = schemaPropertyNames_1.enumDescriptions[i];
else if (schemaPropertyNames.enumDescriptions && i < schemaPropertyNames.enumDescriptions.length) {
enumDescription = schemaPropertyNames.enumDescriptions[i];
}
propertyNameCompletionItem(schemaPropertyNames_1.enum[i], enumDescription);
propertyNameCompletionItem(schemaPropertyNames.enum[i], enumDescription);
}
}
if (schemaPropertyNames_1.const) {
propertyNameCompletionItem(schemaPropertyNames_1.const);
if (schemaPropertyNames.const) {
propertyNameCompletionItem(schemaPropertyNames.const);
}

@@ -300,14 +294,13 @@ }

});
};
JSONCompletion.prototype.getSchemaLessPropertyCompletions = function (doc, node, currentKey, collector) {
var _this = this;
var collectCompletionsForSimilarObject = function (obj) {
obj.properties.forEach(function (p) {
var key = p.keyNode.value;
}
getSchemaLessPropertyCompletions(doc, node, currentKey, collector) {
const collectCompletionsForSimilarObject = (obj) => {
obj.properties.forEach((p) => {
const key = p.keyNode.value;
collector.add({
kind: jsonLanguageTypes_1.CompletionItemKind.Property,
label: key,
insertText: _this.getInsertTextForValue(key, ''),
insertText: this.getInsertTextForValue(key, ''),
insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
filterText: _this.getFilterTextForValue(key),
filterText: this.getFilterTextForValue(key),
documentation: ''

@@ -320,5 +313,5 @@ });

// if the object is a property value, check the tree for other objects that hang under a property of the same name
var parentKey_1 = node.parent.keyNode.value;
doc.visit(function (n) {
if (n.type === 'property' && n !== node.parent && n.keyNode.value === parentKey_1 && n.valueNode && n.valueNode.type === 'object') {
const parentKey = node.parent.keyNode.value;
doc.visit(n => {
if (n.type === 'property' && n !== node.parent && n.keyNode.value === parentKey && n.valueNode && n.valueNode.type === 'object') {
collectCompletionsForSimilarObject(n.valueNode);

@@ -331,3 +324,3 @@ }

// if the object is in an array, use all other array elements as similar objects
node.parent.items.forEach(function (n) {
node.parent.items.forEach(n => {
if (n.type === 'object' && n !== node) {

@@ -348,6 +341,5 @@ collectCompletionsForSimilarObject(n);

}
};
JSONCompletion.prototype.getSchemaLessValueCompletions = function (doc, node, offset, document, collector) {
var _this = this;
var offsetForSeparator = offset;
}
getSchemaLessValueCompletions(doc, node, offset, document, collector) {
let offsetForSeparator = offset;
if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {

@@ -374,9 +366,9 @@ offsetForSeparator = node.offset + node.length;

}
var separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator);
var collectSuggestionsForValues = function (value) {
const separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator);
const collectSuggestionsForValues = (value) => {
if (value.parent && !Parser.contains(value.parent, offset, true)) {
collector.add({
kind: _this.getSuggestionKind(value.type),
label: _this.getLabelTextForMatchingNode(value, document),
insertText: _this.getInsertTextForMatchingNode(value, document, separatorAfter),
kind: this.getSuggestionKind(value.type),
label: this.getLabelTextForMatchingNode(value, document),
insertText: this.getInsertTextForMatchingNode(value, document, separatorAfter),
insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet, documentation: ''

@@ -386,3 +378,3 @@ });

if (value.type === 'boolean') {
_this.addBooleanValueCompletion(!value.value, separatorAfter, collector);
this.addBooleanValueCompletion(!value.value, separatorAfter, collector);
}

@@ -392,3 +384,3 @@ };

if (offset > (node.colonOffset || 0)) {
var valueNode = node.valueNode;
const valueNode = node.valueNode;
if (valueNode && (offset > (valueNode.offset + valueNode.length) || valueNode.type === 'object' || valueNode.type === 'array')) {

@@ -398,5 +390,5 @@ return;

// suggest values at the same key
var parentKey_2 = node.keyNode.value;
doc.visit(function (n) {
if (n.type === 'property' && n.keyNode.value === parentKey_2 && n.valueNode) {
const parentKey = node.keyNode.value;
doc.visit(n => {
if (n.type === 'property' && n.keyNode.value === parentKey && n.valueNode) {
collectSuggestionsForValues(n.valueNode);

@@ -406,3 +398,3 @@ }

});
if (parentKey_2 === '$schema' && node.parent && !node.parent.parent) {
if (parentKey === '$schema' && node.parent && !node.parent.parent) {
this.addDollarSchemaCompletions(separatorAfter, collector);

@@ -415,5 +407,5 @@ }

// suggest items of an array at the same key
var parentKey_3 = node.parent.keyNode.value;
doc.visit(function (n) {
if (n.type === 'property' && n.keyNode.value === parentKey_3 && n.valueNode && n.valueNode.type === 'array') {
const parentKey = node.parent.keyNode.value;
doc.visit((n) => {
if (n.type === 'property' && n.keyNode.value === parentKey && n.valueNode && n.valueNode.type === 'array') {
n.valueNode.items.forEach(collectSuggestionsForValues);

@@ -429,7 +421,7 @@ }

}
};
JSONCompletion.prototype.getValueCompletions = function (schema, doc, node, offset, document, collector, types) {
var offsetForSeparator = offset;
var parentKey = undefined;
var valueNode = undefined;
}
getValueCompletions(schema, doc, node, offset, document, collector, types) {
let offsetForSeparator = offset;
let parentKey = undefined;
let valueNode = undefined;
if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {

@@ -445,4 +437,4 @@ offsetForSeparator = node.offset + node.length;

if ((node.type === 'property') && offset > (node.colonOffset || 0)) {
var valueNode_1 = node.valueNode;
if (valueNode_1 && offset > (valueNode_1.offset + valueNode_1.length)) {
const valueNode = node.valueNode;
if (valueNode && offset > (valueNode.offset + valueNode.length)) {
return; // we are past the value node

@@ -454,10 +446,9 @@ }

if (node && (parentKey !== undefined || node.type === 'array')) {
var separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator);
var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset, valueNode);
for (var _i = 0, matchingSchemas_1 = matchingSchemas; _i < matchingSchemas_1.length; _i++) {
var s = matchingSchemas_1[_i];
const separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator);
const matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset, valueNode);
for (const s of matchingSchemas) {
if (s.node === node && !s.inverted && s.schema) {
if (node.type === 'array' && s.schema.items) {
if (Array.isArray(s.schema.items)) {
var index = this.findItemAtOffset(node, document, offset);
const index = this.findItemAtOffset(node, document, offset);
if (index < s.schema.items.length) {

@@ -472,5 +463,5 @@ this.addSchemaValueCompletions(s.schema.items[index], separatorAfter, collector, types);

if (parentKey !== undefined) {
var propertyMatched = false;
let propertyMatched = false;
if (s.schema.properties) {
var propertySchema = s.schema.properties[parentKey];
const propertySchema = s.schema.properties[parentKey];
if (propertySchema) {

@@ -482,8 +473,7 @@ propertyMatched = true;

if (s.schema.patternProperties && !propertyMatched) {
for (var _a = 0, _b = Object.keys(s.schema.patternProperties); _a < _b.length; _a++) {
var pattern = _b[_a];
var regex = (0, strings_1.extendedRegExp)(pattern);
if (regex === null || regex === void 0 ? void 0 : regex.test(parentKey)) {
for (const pattern of Object.keys(s.schema.patternProperties)) {
const regex = (0, strings_1.extendedRegExp)(pattern);
if (regex?.test(parentKey)) {
propertyMatched = true;
var propertySchema = s.schema.patternProperties[pattern];
const propertySchema = s.schema.patternProperties[pattern];
this.addSchemaValueCompletions(propertySchema, separatorAfter, collector, types);

@@ -494,3 +484,3 @@ }

if (s.schema.additionalProperties && !propertyMatched) {
var propertySchema = s.schema.additionalProperties;
const propertySchema = s.schema.additionalProperties;
this.addSchemaValueCompletions(propertySchema, separatorAfter, collector, types);

@@ -512,7 +502,7 @@ }

}
};
JSONCompletion.prototype.getContributedValueCompletions = function (doc, node, offset, document, collector, collectionPromises) {
}
getContributedValueCompletions(doc, node, offset, document, collector, collectionPromises) {
if (!node) {
this.contributions.forEach(function (contribution) {
var collectPromise = contribution.collectDefaultCompletions(document.uri, collector);
this.contributions.forEach((contribution) => {
const collectPromise = contribution.collectDefaultCompletions(document.uri, collector);
if (collectPromise) {

@@ -528,8 +518,8 @@ collectionPromises.push(collectPromise);

if (node && (node.type === 'property') && offset > (node.colonOffset || 0)) {
var parentKey_4 = node.keyNode.value;
var valueNode = node.valueNode;
const parentKey = node.keyNode.value;
const valueNode = node.valueNode;
if ((!valueNode || offset <= (valueNode.offset + valueNode.length)) && node.parent) {
var location_2 = Parser.getNodePath(node.parent);
this.contributions.forEach(function (contribution) {
var collectPromise = contribution.collectValueCompletions(document.uri, location_2, parentKey_4, collector);
const location = Parser.getNodePath(node.parent);
this.contributions.forEach((contribution) => {
const collectPromise = contribution.collectValueCompletions(document.uri, location, parentKey, collector);
if (collectPromise) {

@@ -542,5 +532,4 @@ collectionPromises.push(collectPromise);

}
};
JSONCompletion.prototype.addSchemaValueCompletions = function (schema, separatorAfter, collector, types) {
var _this = this;
}
addSchemaValueCompletions(schema, separatorAfter, collector, types) {
if (typeof schema === 'object') {

@@ -551,20 +540,18 @@ this.addEnumValueCompletions(schema, separatorAfter, collector);

if (Array.isArray(schema.allOf)) {
schema.allOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
schema.allOf.forEach(s => this.addSchemaValueCompletions(s, separatorAfter, collector, types));
}
if (Array.isArray(schema.anyOf)) {
schema.anyOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
schema.anyOf.forEach(s => this.addSchemaValueCompletions(s, separatorAfter, collector, types));
}
if (Array.isArray(schema.oneOf)) {
schema.oneOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
schema.oneOf.forEach(s => this.addSchemaValueCompletions(s, separatorAfter, collector, types));
}
}
};
JSONCompletion.prototype.addDefaultValueCompletions = function (schema, separatorAfter, collector, arrayDepth) {
var _this = this;
if (arrayDepth === void 0) { arrayDepth = 0; }
var hasProposals = false;
}
addDefaultValueCompletions(schema, separatorAfter, collector, arrayDepth = 0) {
let hasProposals = false;
if ((0, objects_1.isDefined)(schema.default)) {
var type = schema.type;
var value = schema.default;
for (var i = arrayDepth; i > 0; i--) {
let type = schema.type;
let value = schema.default;
for (let i = arrayDepth; i > 0; i--) {
value = [value];

@@ -583,6 +570,6 @@ type = 'array';

if (Array.isArray(schema.examples)) {
schema.examples.forEach(function (example) {
var type = schema.type;
var value = example;
for (var i = arrayDepth; i > 0; i--) {
schema.examples.forEach(example => {
let type = schema.type;
let value = example;
for (let i = arrayDepth; i > 0; i--) {
value = [value];

@@ -592,5 +579,5 @@ type = 'array';

collector.add({
kind: _this.getSuggestionKind(type),
label: _this.getLabelForValue(value),
insertText: _this.getInsertTextForValue(value, separatorAfter),
kind: this.getSuggestionKind(type),
label: this.getLabelForValue(value),
insertText: this.getInsertTextForValue(value, separatorAfter),
insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet

@@ -602,21 +589,21 @@ });

if (Array.isArray(schema.defaultSnippets)) {
schema.defaultSnippets.forEach(function (s) {
var type = schema.type;
var value = s.body;
var label = s.label;
var insertText;
var filterText;
schema.defaultSnippets.forEach(s => {
let type = schema.type;
let value = s.body;
let label = s.label;
let insertText;
let filterText;
if ((0, objects_1.isDefined)(value)) {
var type_1 = schema.type;
for (var i = arrayDepth; i > 0; i--) {
let type = schema.type;
for (let i = arrayDepth; i > 0; i--) {
value = [value];
type_1 = 'array';
type = 'array';
}
insertText = _this.getInsertTextForSnippetValue(value, separatorAfter);
filterText = _this.getFilterTextForSnippetValue(value);
label = label || _this.getLabelForSnippetValue(value);
insertText = this.getInsertTextForSnippetValue(value, separatorAfter);
filterText = this.getFilterTextForSnippetValue(value);
label = label || this.getLabelForSnippetValue(value);
}
else if (typeof s.bodyText === 'string') {
var prefix = '', suffix = '', indent = '';
for (var i = arrayDepth; i > 0; i--) {
let prefix = '', suffix = '', indent = '';
for (let i = arrayDepth; i > 0; i--) {
prefix = prefix + indent + '[\n';

@@ -635,8 +622,8 @@ suffix = suffix + '\n' + indent + ']';

collector.add({
kind: _this.getSuggestionKind(type),
label: label,
documentation: _this.fromMarkup(s.markdownDescription) || s.description,
insertText: insertText,
kind: this.getSuggestionKind(type),
label,
documentation: this.fromMarkup(s.markdownDescription) || s.description,
insertText,
insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
filterText: filterText
filterText
});

@@ -649,4 +636,4 @@ hasProposals = true;

}
};
JSONCompletion.prototype.addEnumValueCompletions = function (schema, separatorAfter, collector) {
}
addEnumValueCompletions(schema, separatorAfter, collector) {
if ((0, objects_1.isDefined)(schema.const)) {

@@ -662,5 +649,5 @@ collector.add({

if (Array.isArray(schema.enum)) {
for (var i = 0, length = schema.enum.length; i < length; i++) {
var enm = schema.enum[i];
var documentation = this.fromMarkup(schema.markdownDescription) || schema.description;
for (let i = 0, length = schema.enum.length; i < length; i++) {
const enm = schema.enum[i];
let documentation = this.fromMarkup(schema.markdownDescription) || schema.description;
if (schema.markdownEnumDescriptions && i < schema.markdownEnumDescriptions.length && this.doesSupportMarkdown()) {

@@ -677,14 +664,14 @@ documentation = this.fromMarkup(schema.markdownEnumDescriptions[i]);

insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet,
documentation: documentation
documentation
});
}
}
};
JSONCompletion.prototype.collectTypes = function (schema, types) {
}
collectTypes(schema, types) {
if (Array.isArray(schema.enum) || (0, objects_1.isDefined)(schema.const)) {
return;
}
var type = schema.type;
const type = schema.type;
if (Array.isArray(type)) {
type.forEach(function (t) { return types[t] = true; });
type.forEach(t => types[t] = true);
}

@@ -694,4 +681,4 @@ else if (type) {

}
};
JSONCompletion.prototype.addFillerValueCompletions = function (types, separatorAfter, collector) {
}
addFillerValueCompletions(types, separatorAfter, collector) {
if (types['object']) {

@@ -717,4 +704,4 @@ collector.add({

}
};
JSONCompletion.prototype.addBooleanValueCompletion = function (value, separatorAfter, collector) {
}
addBooleanValueCompletion(value, separatorAfter, collector) {
collector.add({

@@ -727,4 +714,4 @@ kind: this.getSuggestionKind('boolean'),

});
};
JSONCompletion.prototype.addNullValueCompletion = function (separatorAfter, collector) {
}
addNullValueCompletion(separatorAfter, collector) {
collector.add({

@@ -737,31 +724,30 @@ kind: this.getSuggestionKind('null'),

});
};
JSONCompletion.prototype.addDollarSchemaCompletions = function (separatorAfter, collector) {
var _this = this;
var schemaIds = this.schemaService.getRegisteredSchemaIds(function (schema) { return schema === 'http' || schema === 'https'; });
schemaIds.forEach(function (schemaId) { return collector.add({
}
addDollarSchemaCompletions(separatorAfter, collector) {
const schemaIds = this.schemaService.getRegisteredSchemaIds(schema => schema === 'http' || schema === 'https');
schemaIds.forEach(schemaId => collector.add({
kind: jsonLanguageTypes_1.CompletionItemKind.Module,
label: _this.getLabelForValue(schemaId),
filterText: _this.getFilterTextForValue(schemaId),
insertText: _this.getInsertTextForValue(schemaId, separatorAfter),
label: this.getLabelForValue(schemaId),
filterText: this.getFilterTextForValue(schemaId),
insertText: this.getInsertTextForValue(schemaId, separatorAfter),
insertTextFormat: jsonLanguageTypes_1.InsertTextFormat.Snippet, documentation: ''
}); });
};
JSONCompletion.prototype.getLabelForValue = function (value) {
}));
}
getLabelForValue(value) {
return JSON.stringify(value);
};
JSONCompletion.prototype.getFilterTextForValue = function (value) {
}
getFilterTextForValue(value) {
return JSON.stringify(value);
};
JSONCompletion.prototype.getFilterTextForSnippetValue = function (value) {
}
getFilterTextForSnippetValue(value) {
return JSON.stringify(value).replace(/\$\{\d+:([^}]+)\}|\$\d+/g, '$1');
};
JSONCompletion.prototype.getLabelForSnippetValue = function (value) {
var label = JSON.stringify(value);
}
getLabelForSnippetValue(value) {
const label = JSON.stringify(value);
return label.replace(/\$\{\d+:([^}]+)\}|\$\d+/g, '$1');
};
JSONCompletion.prototype.getInsertTextForPlainText = function (text) {
}
getInsertTextForPlainText(text) {
return text.replace(/[\\\$\}]/g, '\\$&'); // escape $, \ and }
};
JSONCompletion.prototype.getInsertTextForValue = function (value, separatorAfter) {
}
getInsertTextForValue(value, separatorAfter) {
var text = JSON.stringify(value, null, '\t');

@@ -775,5 +761,5 @@ if (text === '{}') {

return this.getInsertTextForPlainText(text + separatorAfter);
};
JSONCompletion.prototype.getInsertTextForSnippetValue = function (value, separatorAfter) {
var replacer = function (value) {
}
getInsertTextForSnippetValue(value, separatorAfter) {
const replacer = (value) => {
if (typeof value === 'string') {

@@ -787,4 +773,4 @@ if (value[0] === '^') {

return (0, json_1.stringifyObject)(value, '', replacer) + separatorAfter;
};
JSONCompletion.prototype.getInsertTextForGuessedValue = function (value, separatorAfter) {
}
getInsertTextForGuessedValue(value, separatorAfter) {
switch (typeof value) {

@@ -797,3 +783,3 @@ case 'object':

case 'string':
var snippetValue = JSON.stringify(value);
let snippetValue = JSON.stringify(value);
snippetValue = snippetValue.substr(1, snippetValue.length - 2); // remove quotes

@@ -807,6 +793,6 @@ snippetValue = this.getInsertTextForPlainText(snippetValue); // escape \ and }

return this.getInsertTextForValue(value, separatorAfter);
};
JSONCompletion.prototype.getSuggestionKind = function (type) {
}
getSuggestionKind(type) {
if (Array.isArray(type)) {
var array = type;
const array = type;
type = array.length > 0 ? array[0] : undefined;

@@ -823,4 +809,4 @@ }

}
};
JSONCompletion.prototype.getLabelTextForMatchingNode = function (node, document) {
}
getLabelTextForMatchingNode(node, document) {
switch (node.type) {

@@ -832,7 +818,7 @@ case 'array':

default:
var content = document.getText().substr(node.offset, node.length);
const content = document.getText().substr(node.offset, node.length);
return content;
}
};
JSONCompletion.prototype.getInsertTextForMatchingNode = function (node, document, separatorAfter) {
}
getInsertTextForMatchingNode(node, document, separatorAfter) {
switch (node.type) {

@@ -844,18 +830,18 @@ case 'array':

default:
var content = document.getText().substr(node.offset, node.length) + separatorAfter;
const content = document.getText().substr(node.offset, node.length) + separatorAfter;
return this.getInsertTextForPlainText(content);
}
};
JSONCompletion.prototype.getInsertTextForProperty = function (key, propertySchema, addValue, separatorAfter) {
var propertyText = this.getInsertTextForValue(key, '');
}
getInsertTextForProperty(key, propertySchema, addValue, separatorAfter) {
const propertyText = this.getInsertTextForValue(key, '');
if (!addValue) {
return propertyText;
}
var resultText = propertyText + ': ';
var value;
var nValueProposals = 0;
const resultText = propertyText + ': ';
let value;
let nValueProposals = 0;
if (propertySchema) {
if (Array.isArray(propertySchema.defaultSnippets)) {
if (propertySchema.defaultSnippets.length === 1) {
var body = propertySchema.defaultSnippets[0].body;
const body = propertySchema.defaultSnippets[0].body;
if ((0, objects_1.isDefined)(body)) {

@@ -924,4 +910,4 @@ value = this.getInsertTextForSnippetValue(body, '');

return resultText + value + separatorAfter;
};
JSONCompletion.prototype.getCurrentWord = function (document, offset) {
}
getCurrentWord(document, offset) {
var i = offset - 1;

@@ -933,7 +919,7 @@ var text = document.getText();

return text.substring(i + 1, offset);
};
JSONCompletion.prototype.evaluateSeparatorAfter = function (document, offset) {
var scanner = Json.createScanner(document.getText(), true);
}
evaluateSeparatorAfter(document, offset) {
const scanner = Json.createScanner(document.getText(), true);
scanner.setPosition(offset);
var token = scanner.scan();
const token = scanner.scan();
switch (token) {

@@ -948,11 +934,11 @@ case 5 /* CommaToken */:

}
};
JSONCompletion.prototype.findItemAtOffset = function (node, document, offset) {
var scanner = Json.createScanner(document.getText(), true);
var children = node.items;
for (var i = children.length - 1; i >= 0; i--) {
var child = children[i];
}
findItemAtOffset(node, document, offset) {
const scanner = Json.createScanner(document.getText(), true);
const children = node.items;
for (let i = children.length - 1; i >= 0; i--) {
const child = children[i];
if (offset > child.offset + child.length) {
scanner.setPosition(child.offset + child.length);
var token = scanner.scan();
const token = scanner.scan();
if (token === 5 /* CommaToken */ && offset >= scanner.getTokenOffset() + scanner.getTokenLength()) {

@@ -968,7 +954,7 @@ return i + 1;

return 0;
};
JSONCompletion.prototype.isInComment = function (document, start, offset) {
var scanner = Json.createScanner(document.getText(), false);
}
isInComment(document, start, offset) {
const scanner = Json.createScanner(document.getText(), false);
scanner.setPosition(start);
var token = scanner.scan();
let token = scanner.scan();
while (token !== 17 /* EOF */ && (scanner.getTokenOffset() + scanner.getTokenLength() < offset)) {

@@ -978,4 +964,4 @@ token = scanner.scan();

return (token === 12 /* LineCommentTrivia */ || token === 13 /* BlockCommentTrivia */) && scanner.getTokenOffset() <= offset;
};
JSONCompletion.prototype.fromMarkup = function (markupString) {
}
fromMarkup(markupString) {
if (markupString && this.doesSupportMarkdown()) {

@@ -988,20 +974,19 @@ return {

return undefined;
};
JSONCompletion.prototype.doesSupportMarkdown = function () {
}
doesSupportMarkdown() {
if (!(0, objects_1.isDefined)(this.supportsMarkdown)) {
var completion = this.clientCapabilities.textDocument && this.clientCapabilities.textDocument.completion;
const completion = this.clientCapabilities.textDocument && this.clientCapabilities.textDocument.completion;
this.supportsMarkdown = completion && completion.completionItem && Array.isArray(completion.completionItem.documentationFormat) && completion.completionItem.documentationFormat.indexOf(jsonLanguageTypes_1.MarkupKind.Markdown) !== -1;
}
return this.supportsMarkdown;
};
JSONCompletion.prototype.doesSupportsCommitCharacters = function () {
}
doesSupportsCommitCharacters() {
if (!(0, objects_1.isDefined)(this.supportsCommitCharacters)) {
var completion = this.clientCapabilities.textDocument && this.clientCapabilities.textDocument.completion;
const completion = this.clientCapabilities.textDocument && this.clientCapabilities.textDocument.completion;
this.supportsCommitCharacters = completion && completion.completionItem && !!completion.completionItem.commitCharactersSupport;
}
return this.supportsCommitCharacters;
};
return JSONCompletion;
}());
}
}
exports.JSONCompletion = JSONCompletion;
});

@@ -17,31 +17,27 @@ /*---------------------------------------------------------------------------------------------

exports.JSONDocumentSymbols = void 0;
var Parser = require("../parser/jsonParser");
var Strings = require("../utils/strings");
var colors_1 = require("../utils/colors");
var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
var JSONDocumentSymbols = /** @class */ (function () {
function JSONDocumentSymbols(schemaService) {
const Parser = require("../parser/jsonParser");
const Strings = require("../utils/strings");
const colors_1 = require("../utils/colors");
const jsonLanguageTypes_1 = require("../jsonLanguageTypes");
class JSONDocumentSymbols {
constructor(schemaService) {
this.schemaService = schemaService;
}
JSONDocumentSymbols.prototype.findDocumentSymbols = function (document, doc, context) {
var _this = this;
if (context === void 0) { context = { resultLimit: Number.MAX_VALUE }; }
var root = doc.root;
findDocumentSymbols(document, doc, context = { resultLimit: Number.MAX_VALUE }) {
const root = doc.root;
if (!root) {
return [];
}
var limit = context.resultLimit || Number.MAX_VALUE;
let limit = context.resultLimit || Number.MAX_VALUE;
// special handling for key bindings
var resourceString = document.uri;
const resourceString = document.uri;
if ((resourceString === 'vscode://defaultsettings/keybindings.json') || Strings.endsWith(resourceString.toLowerCase(), '/user/keybindings.json')) {
if (root.type === 'array') {
var result_1 = [];
for (var _i = 0, _a = root.items; _i < _a.length; _i++) {
var item = _a[_i];
const result = [];
for (const item of root.items) {
if (item.type === 'object') {
for (var _b = 0, _c = item.properties; _b < _c.length; _b++) {
var property = _c[_b];
for (const property of item.properties) {
if (property.keyNode.value === 'key' && property.valueNode) {
var location = jsonLanguageTypes_1.Location.create(document.uri, getRange(document, item));
result_1.push({ name: Parser.getNodeValue(property.valueNode), kind: jsonLanguageTypes_1.SymbolKind.Function, location: location });
const location = jsonLanguageTypes_1.Location.create(document.uri, getRange(document, item));
result.push({ name: Parser.getNodeValue(property.valueNode), kind: jsonLanguageTypes_1.SymbolKind.Function, location: location });
limit--;

@@ -52,3 +48,3 @@ if (limit <= 0) {

}
return result_1;
return result;
}

@@ -59,16 +55,16 @@ }

}
return result_1;
return result;
}
}
var toVisit = [
const toVisit = [
{ node: root, containerName: '' }
];
var nextToVisit = 0;
var limitExceeded = false;
var result = [];
var collectOutlineEntries = function (node, containerName) {
let nextToVisit = 0;
let limitExceeded = false;
const result = [];
const collectOutlineEntries = (node, containerName) => {
if (node.type === 'array') {
node.items.forEach(function (node) {
node.items.forEach(node => {
if (node) {
toVisit.push({ node: node, containerName: containerName });
toVisit.push({ node, containerName });
}

@@ -78,10 +74,10 @@ });

else if (node.type === 'object') {
node.properties.forEach(function (property) {
var valueNode = property.valueNode;
node.properties.forEach((property) => {
const valueNode = property.valueNode;
if (valueNode) {
if (limit > 0) {
limit--;
var location = jsonLanguageTypes_1.Location.create(document.uri, getRange(document, property));
var childContainerName = containerName ? containerName + '.' + property.keyNode.value : property.keyNode.value;
result.push({ name: _this.getKeyLabel(property), kind: _this.getSymbolKind(valueNode.type), location: location, containerName: containerName });
const location = jsonLanguageTypes_1.Location.create(document.uri, getRange(document, property));
const childContainerName = containerName ? containerName + '.' + property.keyNode.value : property.keyNode.value;
result.push({ name: this.getKeyLabel(property), kind: this.getSymbolKind(valueNode.type), location: location, containerName: containerName });
toVisit.push({ node: valueNode, containerName: childContainerName });

@@ -98,3 +94,3 @@ }

while (nextToVisit < toVisit.length) {
var next = toVisit[nextToVisit++];
const next = toVisit[nextToVisit++];
collectOutlineEntries(next.node, next.containerName);

@@ -106,25 +102,21 @@ }

return result;
};
JSONDocumentSymbols.prototype.findDocumentSymbols2 = function (document, doc, context) {
var _this = this;
if (context === void 0) { context = { resultLimit: Number.MAX_VALUE }; }
var root = doc.root;
}
findDocumentSymbols2(document, doc, context = { resultLimit: Number.MAX_VALUE }) {
const root = doc.root;
if (!root) {
return [];
}
var limit = context.resultLimit || Number.MAX_VALUE;
let limit = context.resultLimit || Number.MAX_VALUE;
// special handling for key bindings
var resourceString = document.uri;
const resourceString = document.uri;
if ((resourceString === 'vscode://defaultsettings/keybindings.json') || Strings.endsWith(resourceString.toLowerCase(), '/user/keybindings.json')) {
if (root.type === 'array') {
var result_2 = [];
for (var _i = 0, _a = root.items; _i < _a.length; _i++) {
var item = _a[_i];
const result = [];
for (const item of root.items) {
if (item.type === 'object') {
for (var _b = 0, _c = item.properties; _b < _c.length; _b++) {
var property = _c[_b];
for (const property of item.properties) {
if (property.keyNode.value === 'key' && property.valueNode) {
var range = getRange(document, item);
var selectionRange = getRange(document, property.keyNode);
result_2.push({ name: Parser.getNodeValue(property.valueNode), kind: jsonLanguageTypes_1.SymbolKind.Function, range: range, selectionRange: selectionRange });
const range = getRange(document, item);
const selectionRange = getRange(document, property.keyNode);
result.push({ name: Parser.getNodeValue(property.valueNode), kind: jsonLanguageTypes_1.SymbolKind.Function, range, selectionRange });
limit--;

@@ -135,3 +127,3 @@ if (limit <= 0) {

}
return result_2;
return result;
}

@@ -142,23 +134,23 @@ }

}
return result_2;
return result;
}
}
var result = [];
var toVisit = [
{ node: root, result: result }
const result = [];
const toVisit = [
{ node: root, result }
];
var nextToVisit = 0;
var limitExceeded = false;
var collectOutlineEntries = function (node, result) {
let nextToVisit = 0;
let limitExceeded = false;
const collectOutlineEntries = (node, result) => {
if (node.type === 'array') {
node.items.forEach(function (node, index) {
node.items.forEach((node, index) => {
if (node) {
if (limit > 0) {
limit--;
var range = getRange(document, node);
var selectionRange = range;
var name = String(index);
var symbol = { name: name, kind: _this.getSymbolKind(node.type), range: range, selectionRange: selectionRange, children: [] };
const range = getRange(document, node);
const selectionRange = range;
const name = String(index);
const symbol = { name, kind: this.getSymbolKind(node.type), range, selectionRange, children: [] };
result.push(symbol);
toVisit.push({ result: symbol.children, node: node });
toVisit.push({ result: symbol.children, node });
}

@@ -172,11 +164,11 @@ else {

else if (node.type === 'object') {
node.properties.forEach(function (property) {
var valueNode = property.valueNode;
node.properties.forEach((property) => {
const valueNode = property.valueNode;
if (valueNode) {
if (limit > 0) {
limit--;
var range = getRange(document, property);
var selectionRange = getRange(document, property.keyNode);
var children = [];
var symbol = { name: _this.getKeyLabel(property), kind: _this.getSymbolKind(valueNode.type), range: range, selectionRange: selectionRange, children: children, detail: _this.getDetail(valueNode) };
const range = getRange(document, property);
const selectionRange = getRange(document, property.keyNode);
const children = [];
const symbol = { name: this.getKeyLabel(property), kind: this.getSymbolKind(valueNode.type), range, selectionRange, children, detail: this.getDetail(valueNode) };
result.push(symbol);

@@ -194,3 +186,3 @@ toVisit.push({ result: children, node: valueNode });

while (nextToVisit < toVisit.length) {
var next = toVisit[nextToVisit++];
const next = toVisit[nextToVisit++];
collectOutlineEntries(next.node, next.result);

@@ -202,4 +194,4 @@ }

return result;
};
JSONDocumentSymbols.prototype.getSymbolKind = function (nodeType) {
}
getSymbolKind(nodeType) {
switch (nodeType) {

@@ -219,5 +211,5 @@ case 'object':

}
};
JSONDocumentSymbols.prototype.getKeyLabel = function (property) {
var name = property.keyNode.value;
}
getKeyLabel(property) {
let name = property.keyNode.value;
if (name) {

@@ -229,5 +221,5 @@ name = name.replace(/[\n]/g, '↵');

}
return "\"".concat(name, "\"");
};
JSONDocumentSymbols.prototype.getDetail = function (node) {
return `"${name}"`;
}
getDetail(node) {
if (!node) {

@@ -248,19 +240,18 @@ return undefined;

return undefined;
};
JSONDocumentSymbols.prototype.findDocumentColors = function (document, doc, context) {
return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
var result = [];
}
findDocumentColors(document, doc, context) {
return this.schemaService.getSchemaForResource(document.uri, doc).then(schema => {
const result = [];
if (schema) {
var limit = context && typeof context.resultLimit === 'number' ? context.resultLimit : Number.MAX_VALUE;
var matchingSchemas = doc.getMatchingSchemas(schema.schema);
var visitedNode = {};
for (var _i = 0, matchingSchemas_1 = matchingSchemas; _i < matchingSchemas_1.length; _i++) {
var s = matchingSchemas_1[_i];
let limit = context && typeof context.resultLimit === 'number' ? context.resultLimit : Number.MAX_VALUE;
const matchingSchemas = doc.getMatchingSchemas(schema.schema);
const visitedNode = {};
for (const s of matchingSchemas) {
if (!s.inverted && s.schema && (s.schema.format === 'color' || s.schema.format === 'color-hex') && s.node && s.node.type === 'string') {
var nodeId = String(s.node.offset);
const nodeId = String(s.node.offset);
if (!visitedNode[nodeId]) {
var color = (0, colors_1.colorFromHex)(Parser.getNodeValue(s.node));
const color = (0, colors_1.colorFromHex)(Parser.getNodeValue(s.node));
if (color) {
var range = getRange(document, s.node);
result.push({ color: color, range: range });
const range = getRange(document, s.node);
result.push({ color, range });
}

@@ -281,22 +272,21 @@ visitedNode[nodeId] = true;

});
};
JSONDocumentSymbols.prototype.getColorPresentations = function (document, doc, color, range) {
var result = [];
var red256 = Math.round(color.red * 255), green256 = Math.round(color.green * 255), blue256 = Math.round(color.blue * 255);
}
getColorPresentations(document, doc, color, range) {
const result = [];
const red256 = Math.round(color.red * 255), green256 = Math.round(color.green * 255), blue256 = Math.round(color.blue * 255);
function toTwoDigitHex(n) {
var r = n.toString(16);
const r = n.toString(16);
return r.length !== 2 ? '0' + r : r;
}
var label;
let label;
if (color.alpha === 1) {
label = "#".concat(toTwoDigitHex(red256)).concat(toTwoDigitHex(green256)).concat(toTwoDigitHex(blue256));
label = `#${toTwoDigitHex(red256)}${toTwoDigitHex(green256)}${toTwoDigitHex(blue256)}`;
}
else {
label = "#".concat(toTwoDigitHex(red256)).concat(toTwoDigitHex(green256)).concat(toTwoDigitHex(blue256)).concat(toTwoDigitHex(Math.round(color.alpha * 255)));
label = `#${toTwoDigitHex(red256)}${toTwoDigitHex(green256)}${toTwoDigitHex(blue256)}${toTwoDigitHex(Math.round(color.alpha * 255))}`;
}
result.push({ label: label, textEdit: jsonLanguageTypes_1.TextEdit.replace(range, JSON.stringify(label)) });
return result;
};
return JSONDocumentSymbols;
}());
}
}
exports.JSONDocumentSymbols = JSONDocumentSymbols;

@@ -303,0 +293,0 @@ function getRange(document, node) {

@@ -17,11 +17,11 @@ /*---------------------------------------------------------------------------------------------

exports.getFoldingRanges = void 0;
var jsonc_parser_1 = require("jsonc-parser");
var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
const jsonc_parser_1 = require("jsonc-parser");
const jsonLanguageTypes_1 = require("../jsonLanguageTypes");
function getFoldingRanges(document, context) {
var ranges = [];
var nestingLevels = [];
var stack = [];
var prevStart = -1;
var scanner = (0, jsonc_parser_1.createScanner)(document.getText(), false);
var token = scanner.scan();
const ranges = [];
const nestingLevels = [];
const stack = [];
let prevStart = -1;
const scanner = (0, jsonc_parser_1.createScanner)(document.getText(), false);
let token = scanner.scan();
function addRange(range) {

@@ -35,4 +35,4 @@ ranges.push(range);

case 3 /* OpenBracketToken */: {
var startLine = document.positionAt(scanner.getTokenOffset()).line;
var range = { startLine: startLine, endLine: startLine, kind: token === 1 /* OpenBraceToken */ ? 'object' : 'array' };
const startLine = document.positionAt(scanner.getTokenOffset()).line;
const range = { startLine, endLine: startLine, kind: token === 1 /* OpenBraceToken */ ? 'object' : 'array' };
stack.push(range);

@@ -43,6 +43,6 @@ break;

case 4 /* CloseBracketToken */: {
var kind = token === 2 /* CloseBraceToken */ ? 'object' : 'array';
const kind = token === 2 /* CloseBraceToken */ ? 'object' : 'array';
if (stack.length > 0 && stack[stack.length - 1].kind === kind) {
var range = stack.pop();
var line = document.positionAt(scanner.getTokenOffset()).line;
const range = stack.pop();
const line = document.positionAt(scanner.getTokenOffset()).line;
if (range && line > range.startLine + 1 && prevStart !== range.startLine) {

@@ -57,4 +57,4 @@ range.endLine = line - 1;

case 13 /* BlockCommentTrivia */: {
var startLine = document.positionAt(scanner.getTokenOffset()).line;
var endLine = document.positionAt(scanner.getTokenOffset() + scanner.getTokenLength()).line;
const startLine = document.positionAt(scanner.getTokenOffset()).line;
const endLine = document.positionAt(scanner.getTokenOffset() + scanner.getTokenLength()).line;
if (scanner.getTokenError() === 1 /* UnexpectedEndOfComment */ && startLine + 1 < document.lineCount) {

@@ -65,3 +65,3 @@ scanner.setPosition(document.offsetAt(jsonLanguageTypes_1.Position.create(startLine + 1, 0)));

if (startLine < endLine) {
addRange({ startLine: startLine, endLine: endLine, kind: jsonLanguageTypes_1.FoldingRangeKind.Comment });
addRange({ startLine, endLine, kind: jsonLanguageTypes_1.FoldingRangeKind.Comment });
prevStart = startLine;

@@ -73,12 +73,12 @@ }

case 12 /* LineCommentTrivia */: {
var text = document.getText().substr(scanner.getTokenOffset(), scanner.getTokenLength());
var m = text.match(/^\/\/\s*#(region\b)|(endregion\b)/);
const text = document.getText().substr(scanner.getTokenOffset(), scanner.getTokenLength());
const m = text.match(/^\/\/\s*#(region\b)|(endregion\b)/);
if (m) {
var line = document.positionAt(scanner.getTokenOffset()).line;
const line = document.positionAt(scanner.getTokenOffset()).line;
if (m[1]) { // start pattern match
var range = { startLine: line, endLine: line, kind: jsonLanguageTypes_1.FoldingRangeKind.Region };
const range = { startLine: line, endLine: line, kind: jsonLanguageTypes_1.FoldingRangeKind.Region };
stack.push(range);
}
else {
var i = stack.length - 1;
let i = stack.length - 1;
while (i >= 0 && stack[i].kind !== jsonLanguageTypes_1.FoldingRangeKind.Region) {

@@ -88,3 +88,3 @@ i--;

if (i >= 0) {
var range = stack[i];
const range = stack[i];
stack.length = i;

@@ -104,3 +104,3 @@ if (line > range.startLine && prevStart !== range.startLine) {

}
var rangeLimit = context && context.rangeLimit;
const rangeLimit = context && context.rangeLimit;
if (typeof rangeLimit !== 'number' || ranges.length <= rangeLimit) {

@@ -112,5 +112,4 @@ return ranges;

}
var counts = [];
for (var _i = 0, nestingLevels_1 = nestingLevels; _i < nestingLevels_1.length; _i++) {
var level = nestingLevels_1[_i];
const counts = [];
for (let level of nestingLevels) {
if (level < 30) {

@@ -120,6 +119,6 @@ counts[level] = (counts[level] || 0) + 1;

}
var entries = 0;
var maxLevel = 0;
for (var i = 0; i < counts.length; i++) {
var n = counts[i];
let entries = 0;
let maxLevel = 0;
for (let i = 0; i < counts.length; i++) {
const n = counts[i];
if (n) {

@@ -133,5 +132,5 @@ if (n + entries > rangeLimit) {

}
var result = [];
for (var i = 0; i < ranges.length; i++) {
var level = nestingLevels[i];
const result = [];
for (let i = 0; i < ranges.length; i++) {
const level = nestingLevels[i];
if (typeof level === 'number') {

@@ -138,0 +137,0 @@ if (level < maxLevel || (level === maxLevel && entries++ < rangeLimit)) {

@@ -17,7 +17,6 @@ /*---------------------------------------------------------------------------------------------

exports.JSONHover = void 0;
var Parser = require("../parser/jsonParser");
var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
var JSONHover = /** @class */ (function () {
function JSONHover(schemaService, contributions, promiseConstructor) {
if (contributions === void 0) { contributions = []; }
const Parser = require("../parser/jsonParser");
const jsonLanguageTypes_1 = require("../jsonLanguageTypes");
class JSONHover {
constructor(schemaService, contributions = [], promiseConstructor) {
this.schemaService = schemaService;

@@ -27,12 +26,12 @@ this.contributions = contributions;

}
JSONHover.prototype.doHover = function (document, position, doc) {
var offset = document.offsetAt(position);
var node = doc.getNodeFromOffset(offset);
doHover(document, position, doc) {
const offset = document.offsetAt(position);
let node = doc.getNodeFromOffset(offset);
if (!node || (node.type === 'object' || node.type === 'array') && offset > node.offset + 1 && offset < node.offset + node.length - 1) {
return this.promise.resolve(null);
}
var hoverRangeNode = node;
const hoverRangeNode = node;
// use the property description when hovering over an object key
if (node.type === 'string') {
var parent = node.parent;
const parent = node.parent;
if (parent && parent.type === 'property' && parent.keyNode === node) {

@@ -45,5 +44,5 @@ node = parent.valueNode;

}
var hoverRange = jsonLanguageTypes_1.Range.create(document.positionAt(hoverRangeNode.offset), document.positionAt(hoverRangeNode.offset + hoverRangeNode.length));
var createHover = function (contents) {
var result = {
const hoverRange = jsonLanguageTypes_1.Range.create(document.positionAt(hoverRangeNode.offset), document.positionAt(hoverRangeNode.offset + hoverRangeNode.length));
var createHover = (contents) => {
const result = {
contents: contents,

@@ -54,32 +53,32 @@ range: hoverRange

};
var location = Parser.getNodePath(node);
for (var i = this.contributions.length - 1; i >= 0; i--) {
var contribution = this.contributions[i];
var promise = contribution.getInfoContribution(document.uri, location);
const location = Parser.getNodePath(node);
for (let i = this.contributions.length - 1; i >= 0; i--) {
const contribution = this.contributions[i];
const promise = contribution.getInfoContribution(document.uri, location);
if (promise) {
return promise.then(function (htmlContent) { return createHover(htmlContent); });
return promise.then(htmlContent => createHover(htmlContent));
}
}
return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
return this.schemaService.getSchemaForResource(document.uri, doc).then((schema) => {
if (schema && node) {
var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset);
var title_1 = undefined;
var markdownDescription_1 = undefined;
var markdownEnumValueDescription_1 = undefined, enumValue_1 = undefined;
matchingSchemas.every(function (s) {
const matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset);
let title = undefined;
let markdownDescription = undefined;
let markdownEnumValueDescription = undefined, enumValue = undefined;
matchingSchemas.every((s) => {
if (s.node === node && !s.inverted && s.schema) {
title_1 = title_1 || s.schema.title;
markdownDescription_1 = markdownDescription_1 || s.schema.markdownDescription || toMarkdown(s.schema.description);
title = title || s.schema.title;
markdownDescription = markdownDescription || s.schema.markdownDescription || toMarkdown(s.schema.description);
if (s.schema.enum) {
var idx = s.schema.enum.indexOf(Parser.getNodeValue(node));
const idx = s.schema.enum.indexOf(Parser.getNodeValue(node));
if (s.schema.markdownEnumDescriptions) {
markdownEnumValueDescription_1 = s.schema.markdownEnumDescriptions[idx];
markdownEnumValueDescription = s.schema.markdownEnumDescriptions[idx];
}
else if (s.schema.enumDescriptions) {
markdownEnumValueDescription_1 = toMarkdown(s.schema.enumDescriptions[idx]);
markdownEnumValueDescription = toMarkdown(s.schema.enumDescriptions[idx]);
}
if (markdownEnumValueDescription_1) {
enumValue_1 = s.schema.enum[idx];
if (typeof enumValue_1 !== 'string') {
enumValue_1 = JSON.stringify(enumValue_1);
if (markdownEnumValueDescription) {
enumValue = s.schema.enum[idx];
if (typeof enumValue !== 'string') {
enumValue = JSON.stringify(enumValue);
}

@@ -91,17 +90,17 @@ }

});
var result = '';
if (title_1) {
result = toMarkdown(title_1);
let result = '';
if (title) {
result = toMarkdown(title);
}
if (markdownDescription_1) {
if (markdownDescription) {
if (result.length > 0) {
result += "\n\n";
}
result += markdownDescription_1;
result += markdownDescription;
}
if (markdownEnumValueDescription_1) {
if (markdownEnumValueDescription) {
if (result.length > 0) {
result += "\n\n";
}
result += "`".concat(toMarkdownCodeBlock(enumValue_1), "`: ").concat(markdownEnumValueDescription_1);
result += `\`${toMarkdownCodeBlock(enumValue)}\`: ${markdownEnumValueDescription}`;
}

@@ -112,9 +111,8 @@ return createHover([result]);

});
};
return JSONHover;
}());
}
}
exports.JSONHover = JSONHover;
function toMarkdown(plain) {
if (plain) {
var res = plain.replace(/([^\n\r])(\r?\n)([^\n\r])/gm, '$1\n\n$3'); // single new lines to \n\n (Markdown paragraph)
const res = plain.replace(/([^\n\r])(\r?\n)([^\n\r])/gm, '$1\n\n$3'); // single new lines to \n\n (Markdown paragraph)
return res.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&"); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash

@@ -121,0 +119,0 @@ }

@@ -17,14 +17,13 @@ /*---------------------------------------------------------------------------------------------

exports.findLinks = void 0;
var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
const jsonLanguageTypes_1 = require("../jsonLanguageTypes");
function findLinks(document, doc) {
var links = [];
doc.visit(function (node) {
var _a;
if (node.type === "property" && node.keyNode.value === "$ref" && ((_a = node.valueNode) === null || _a === void 0 ? void 0 : _a.type) === 'string') {
var path = node.valueNode.value;
var targetNode = findTargetNode(doc, path);
const links = [];
doc.visit(node => {
if (node.type === "property" && node.keyNode.value === "$ref" && node.valueNode?.type === 'string') {
const path = node.valueNode.value;
const targetNode = findTargetNode(doc, path);
if (targetNode) {
var targetPos = document.positionAt(targetNode.offset);
const targetPos = document.positionAt(targetNode.offset);
links.push({
target: "".concat(document.uri, "#").concat(targetPos.line + 1, ",").concat(targetPos.character + 1),
target: `${document.uri}#${targetPos.line + 1},${targetPos.character + 1}`,
range: createRange(document, node.valueNode)

@@ -43,3 +42,3 @@ });

function findTargetNode(doc, path) {
var tokens = parseJSONPointer(path);
const tokens = parseJSONPointer(path);
if (!tokens) {

@@ -57,5 +56,5 @@ return null;

}
var token = pointer.shift();
const token = pointer.shift();
if (node && node.type === 'object') {
var propertyNode = node.properties.find(function (propertyNode) { return propertyNode.keyNode.value === token; });
const propertyNode = node.properties.find((propertyNode) => propertyNode.keyNode.value === token);
if (!propertyNode) {

@@ -68,4 +67,4 @@ return null;

if (token.match(/^(0|[1-9][0-9]*)$/)) {
var index = Number.parseInt(token);
var arrayItem = node.items[index];
const index = Number.parseInt(token);
const arrayItem = node.items[index];
if (!arrayItem) {

@@ -72,0 +71,0 @@ return null;

@@ -11,3 +11,3 @@ /*---------------------------------------------------------------------------------------------

else if (typeof define === "function" && define.amd) {
define(["require", "exports", "jsonc-parser", "vscode-uri", "../utils/strings", "../parser/jsonParser", "vscode-nls", "../utils/glob"], factory);
define(["require", "exports", "jsonc-parser", "vscode-uri", "../utils/strings", "../parser/jsonParser", "vscode-nls", "../utils/glob", "../utils/objects"], factory);
}

@@ -18,18 +18,18 @@ })(function (require, exports) {

exports.JSONSchemaService = exports.ResolvedSchema = exports.UnresolvedSchema = void 0;
var Json = require("jsonc-parser");
var vscode_uri_1 = require("vscode-uri");
var Strings = require("../utils/strings");
var Parser = require("../parser/jsonParser");
var nls = require("vscode-nls");
var glob_1 = require("../utils/glob");
var localize = nls.loadMessageBundle();
var BANG = '!';
var PATH_SEP = '/';
var FilePatternAssociation = /** @class */ (function () {
function FilePatternAssociation(pattern, uris) {
const Json = require("jsonc-parser");
const vscode_uri_1 = require("vscode-uri");
const Strings = require("../utils/strings");
const Parser = require("../parser/jsonParser");
const nls = require("vscode-nls");
const glob_1 = require("../utils/glob");
const objects_1 = require("../utils/objects");
const localize = nls.loadMessageBundle();
const BANG = '!';
const PATH_SEP = '/';
class FilePatternAssociation {
constructor(pattern, uris) {
this.globWrappers = [];
try {
for (var _i = 0, pattern_1 = pattern; _i < pattern_1.length; _i++) {
var patternString = pattern_1[_i];
var include = patternString[0] !== BANG;
for (let patternString of pattern) {
const include = patternString[0] !== BANG;
if (!include) {

@@ -56,6 +56,5 @@ patternString = patternString.substring(1);

}
FilePatternAssociation.prototype.matchesPattern = function (fileName) {
var match = false;
for (var _i = 0, _a = this.globWrappers; _i < _a.length; _i++) {
var _b = _a[_i], regexp = _b.regexp, include = _b.include;
matchesPattern(fileName) {
let match = false;
for (const { regexp, include } of this.globWrappers) {
if (regexp.test(fileName)) {

@@ -66,10 +65,9 @@ match = include;

return match;
};
FilePatternAssociation.prototype.getURIs = function () {
}
getURIs() {
return this.uris;
};
return FilePatternAssociation;
}());
var SchemaHandle = /** @class */ (function () {
function SchemaHandle(service, uri, unresolvedSchemaContent) {
}
}
class SchemaHandle {
constructor(service, uri, unresolvedSchemaContent) {
this.service = service;

@@ -83,3 +81,3 @@ this.uri = uri;

}
SchemaHandle.prototype.getUnresolvedSchema = function () {
getUnresolvedSchema() {
if (!this.unresolvedSchema) {

@@ -89,14 +87,13 @@ this.unresolvedSchema = this.service.loadSchema(this.uri);

return this.unresolvedSchema;
};
SchemaHandle.prototype.getResolvedSchema = function () {
var _this = this;
}
getResolvedSchema() {
if (!this.resolvedSchema) {
this.resolvedSchema = this.getUnresolvedSchema().then(function (unresolved) {
return _this.service.resolveSchemaContent(unresolved, _this);
this.resolvedSchema = this.getUnresolvedSchema().then(unresolved => {
return this.service.resolveSchemaContent(unresolved, this);
});
}
return this.resolvedSchema;
};
SchemaHandle.prototype.clearSchema = function () {
var hasChanges = !!this.unresolvedSchema;
}
clearSchema() {
const hasChanges = !!this.unresolvedSchema;
this.resolvedSchema = undefined;

@@ -107,22 +104,20 @@ this.unresolvedSchema = undefined;

return hasChanges;
};
return SchemaHandle;
}());
var UnresolvedSchema = /** @class */ (function () {
function UnresolvedSchema(schema, errors) {
if (errors === void 0) { errors = []; }
}
}
class UnresolvedSchema {
constructor(schema, errors = []) {
this.schema = schema;
this.errors = errors;
}
return UnresolvedSchema;
}());
}
exports.UnresolvedSchema = UnresolvedSchema;
var ResolvedSchema = /** @class */ (function () {
function ResolvedSchema(schema, errors) {
if (errors === void 0) { errors = []; }
class ResolvedSchema {
constructor(schema, errors = [], warnings = [], schemaDraft) {
this.schema = schema;
this.errors = errors;
this.warnings = warnings;
this.schemaDraft = schemaDraft;
}
ResolvedSchema.prototype.getSection = function (path) {
var schemaRef = this.getSectionRecursive(path, this.schema);
getSection(path) {
const schemaRef = this.getSectionRecursive(path, this.schema);
if (schemaRef) {

@@ -132,8 +127,8 @@ return Parser.asSchema(schemaRef);

return undefined;
};
ResolvedSchema.prototype.getSectionRecursive = function (path, schema) {
}
getSectionRecursive(path, schema) {
if (!schema || typeof schema === 'boolean' || path.length === 0) {
return schema;
}
var next = path.shift();
const next = path.shift();
if (schema.properties && typeof schema.properties[next]) {

@@ -143,6 +138,5 @@ return this.getSectionRecursive(path, schema.properties[next]);

else if (schema.patternProperties) {
for (var _i = 0, _a = Object.keys(schema.patternProperties); _i < _a.length; _i++) {
var pattern = _a[_i];
var regex = Strings.extendedRegExp(pattern);
if (regex === null || regex === void 0 ? void 0 : regex.test(next)) {
for (const pattern of Object.keys(schema.patternProperties)) {
const regex = Strings.extendedRegExp(pattern);
if (regex?.test(next)) {
return this.getSectionRecursive(path, schema.patternProperties[pattern]);

@@ -157,3 +151,3 @@ }

if (Array.isArray(schema.items)) {
var index = parseInt(next, 10);
const index = parseInt(next, 10);
if (!isNaN(index) && schema.items[index]) {

@@ -168,8 +162,7 @@ return this.getSectionRecursive(path, schema.items[index]);

return undefined;
};
return ResolvedSchema;
}());
}
}
exports.ResolvedSchema = ResolvedSchema;
var JSONSchemaService = /** @class */ (function () {
function JSONSchemaService(requestService, contextService, promiseConstructor) {
class JSONSchemaService {
constructor(requestService, contextService, promiseConstructor) {
this.contextService = contextService;

@@ -185,32 +178,27 @@ this.requestService = requestService;

}
JSONSchemaService.prototype.getRegisteredSchemaIds = function (filter) {
return Object.keys(this.registeredSchemasIds).filter(function (id) {
var scheme = vscode_uri_1.URI.parse(id).scheme;
getRegisteredSchemaIds(filter) {
return Object.keys(this.registeredSchemasIds).filter(id => {
const scheme = vscode_uri_1.URI.parse(id).scheme;
return scheme !== 'schemaservice' && (!filter || filter(scheme));
});
};
Object.defineProperty(JSONSchemaService.prototype, "promise", {
get: function () {
return this.promiseConstructor;
},
enumerable: false,
configurable: true
});
JSONSchemaService.prototype.dispose = function () {
}
get promise() {
return this.promiseConstructor;
}
dispose() {
while (this.callOnDispose.length > 0) {
this.callOnDispose.pop()();
}
};
JSONSchemaService.prototype.onResourceChange = function (uri) {
var _this = this;
}
onResourceChange(uri) {
// always clear this local cache when a resource changes
this.cachedSchemaForResource = undefined;
var hasChanges = false;
let hasChanges = false;
uri = normalizeId(uri);
var toWalk = [uri];
var all = Object.keys(this.schemasById).map(function (key) { return _this.schemasById[key]; });
const toWalk = [uri];
const all = Object.keys(this.schemasById).map(key => this.schemasById[key]);
while (toWalk.length) {
var curr = toWalk.pop();
for (var i = 0; i < all.length; i++) {
var handle = all[i];
const curr = toWalk.pop();
for (let i = 0; i < all.length; i++) {
const handle = all[i];
if (handle && (handle.uri === curr || handle.dependencies.has(curr))) {

@@ -228,8 +216,8 @@ if (handle.uri !== curr) {

return hasChanges;
};
JSONSchemaService.prototype.setSchemaContributions = function (schemaContributions) {
}
setSchemaContributions(schemaContributions) {
if (schemaContributions.schemas) {
var schemas = schemaContributions.schemas;
for (var id in schemas) {
var normalizedId = normalizeId(id);
const schemas = schemaContributions.schemas;
for (const id in schemas) {
const normalizedId = normalizeId(id);
this.contributionSchemas[normalizedId] = this.addSchemaHandle(normalizedId, schemas[id]);

@@ -239,26 +227,25 @@ }

if (Array.isArray(schemaContributions.schemaAssociations)) {
var schemaAssociations = schemaContributions.schemaAssociations;
for (var _i = 0, schemaAssociations_1 = schemaAssociations; _i < schemaAssociations_1.length; _i++) {
var schemaAssociation = schemaAssociations_1[_i];
var uris = schemaAssociation.uris.map(normalizeId);
var association = this.addFilePatternAssociation(schemaAssociation.pattern, uris);
const schemaAssociations = schemaContributions.schemaAssociations;
for (let schemaAssociation of schemaAssociations) {
const uris = schemaAssociation.uris.map(normalizeId);
const association = this.addFilePatternAssociation(schemaAssociation.pattern, uris);
this.contributionAssociations.push(association);
}
}
};
JSONSchemaService.prototype.addSchemaHandle = function (id, unresolvedSchemaContent) {
var schemaHandle = new SchemaHandle(this, id, unresolvedSchemaContent);
}
addSchemaHandle(id, unresolvedSchemaContent) {
const schemaHandle = new SchemaHandle(this, id, unresolvedSchemaContent);
this.schemasById[id] = schemaHandle;
return schemaHandle;
};
JSONSchemaService.prototype.getOrAddSchemaHandle = function (id, unresolvedSchemaContent) {
}
getOrAddSchemaHandle(id, unresolvedSchemaContent) {
return this.schemasById[id] || this.addSchemaHandle(id, unresolvedSchemaContent);
};
JSONSchemaService.prototype.addFilePatternAssociation = function (pattern, uris) {
var fpa = new FilePatternAssociation(pattern, uris);
}
addFilePatternAssociation(pattern, uris) {
const fpa = new FilePatternAssociation(pattern, uris);
this.filePatternAssociations.push(fpa);
return fpa;
};
JSONSchemaService.prototype.registerExternalSchema = function (uri, filePatterns, unresolvedSchemaContent) {
var id = normalizeId(uri);
}
registerExternalSchema(uri, filePatterns, unresolvedSchemaContent) {
const id = normalizeId(uri);
this.registeredSchemasIds[id] = true;

@@ -270,4 +257,4 @@ this.cachedSchemaForResource = undefined;

return unresolvedSchemaContent ? this.addSchemaHandle(id, unresolvedSchemaContent) : this.getOrAddSchemaHandle(id);
};
JSONSchemaService.prototype.clearExternalSchemas = function () {
}
clearExternalSchemas() {
this.schemasById = {};

@@ -277,14 +264,13 @@ this.filePatternAssociations = [];

this.cachedSchemaForResource = undefined;
for (var id in this.contributionSchemas) {
for (const id in this.contributionSchemas) {
this.schemasById[id] = this.contributionSchemas[id];
this.registeredSchemasIds[id] = true;
}
for (var _i = 0, _a = this.contributionAssociations; _i < _a.length; _i++) {
var contributionAssociation = _a[_i];
for (const contributionAssociation of this.contributionAssociations) {
this.filePatternAssociations.push(contributionAssociation);
}
};
JSONSchemaService.prototype.getResolvedSchema = function (schemaId) {
var id = normalizeId(schemaId);
var schemaHandle = this.schemasById[id];
}
getResolvedSchema(schemaId) {
const id = normalizeId(schemaId);
const schemaHandle = this.schemasById[id];
if (schemaHandle) {

@@ -294,21 +280,21 @@ return schemaHandle.getResolvedSchema();

return this.promise.resolve(undefined);
};
JSONSchemaService.prototype.loadSchema = function (url) {
}
loadSchema(url) {
if (!this.requestService) {
var errorMessage = localize('json.schema.norequestservice', 'Unable to load schema from \'{0}\'. No schema request service available', toDisplayString(url));
const errorMessage = localize('json.schema.norequestservice', 'Unable to load schema from \'{0}\'. No schema request service available', toDisplayString(url));
return this.promise.resolve(new UnresolvedSchema({}, [errorMessage]));
}
return this.requestService(url).then(function (content) {
return this.requestService(url).then(content => {
if (!content) {
var errorMessage = localize('json.schema.nocontent', 'Unable to load schema from \'{0}\': No content.', toDisplayString(url));
const errorMessage = localize('json.schema.nocontent', 'Unable to load schema from \'{0}\': No content.', toDisplayString(url));
return new UnresolvedSchema({}, [errorMessage]);
}
var schemaContent = {};
var jsonErrors = [];
let schemaContent = {};
const jsonErrors = [];
schemaContent = Json.parse(content, jsonErrors);
var errors = jsonErrors.length ? [localize('json.schema.invalidFormat', 'Unable to parse content from \'{0}\': Parse error at offset {1}.', toDisplayString(url), jsonErrors[0].offset)] : [];
const errors = jsonErrors.length ? [localize('json.schema.invalidFormat', 'Unable to parse content from \'{0}\': Parse error at offset {1}.', toDisplayString(url), jsonErrors[0].offset)] : [];
return new UnresolvedSchema(schemaContent, errors);
}, function (error) {
var errorMessage = error.toString();
var errorSplit = error.toString().split('Error: ');
}, (error) => {
let errorMessage = error.toString();
const errorSplit = error.toString().split('Error: ');
if (errorSplit.length > 1) {

@@ -323,27 +309,19 @@ // more concise error message, URL and context are attached by caller anyways

});
};
JSONSchemaService.prototype.resolveSchemaContent = function (schemaToResolve, handle) {
var _this = this;
var resolveErrors = schemaToResolve.errors.slice(0);
var schema = schemaToResolve.schema;
if (schema.$schema) {
var id = normalizeId(schema.$schema);
if (id === 'http://json-schema.org/draft-03/schema') {
return this.promise.resolve(new ResolvedSchema({}, [localize('json.schema.draft03.notsupported', "Draft-03 schemas are not supported.")]));
}
else if (id === 'https://json-schema.org/draft/2019-09/schema') {
resolveErrors.push(localize('json.schema.draft201909.notsupported', "Draft 2019-09 schemas are not yet fully supported."));
}
else if (id === 'https://json-schema.org/draft/2020-12/schema') {
resolveErrors.push(localize('json.schema.draft202012.notsupported', "Draft 2020-12 schemas are not yet fully supported."));
}
}
resolveSchemaContent(schemaToResolve, handle) {
const resolveErrors = schemaToResolve.errors.slice(0);
const schema = schemaToResolve.schema;
let schemaDraft = schema.$schema ? normalizeId(schema.$schema) : undefined;
if (schemaDraft === 'http://json-schema.org/draft-03/schema') {
return this.promise.resolve(new ResolvedSchema({}, [localize('json.schema.draft03.notsupported', "Draft-03 schemas are not supported.")], [], schemaDraft));
}
var contextService = this.contextService;
var findSectionByJSONPointer = function (schema, path) {
let usesUnsupportedFeatures = new Set();
const contextService = this.contextService;
const findSectionByJSONPointer = (schema, path) => {
path = decodeURIComponent(path);
var current = schema;
let current = schema;
if (path[0] === '/') {
path = path.substring(1);
}
path.split('/').some(function (part) {
path.split('/').some((part) => {
part = part.replace(/~1/g, '/').replace(/~0/g, '~');

@@ -355,3 +333,3 @@ current = current[part];

};
var findSchemaById = function (schema, handle, id) {
const findSchemaById = (schema, handle, id) => {
if (!handle.anchors) {

@@ -362,4 +340,4 @@ handle.anchors = collectAnchors(schema);

};
var merge = function (target, section) {
for (var key in section) {
const merge = (target, section) => {
for (const key in section) {
if (section.hasOwnProperty(key) && !target.hasOwnProperty(key) && key !== 'id' && key !== '$id') {

@@ -370,4 +348,4 @@ target[key] = section[key];

};
var mergeRef = function (target, sourceRoot, sourceHandle, refSegment) {
var section;
const mergeRef = (target, sourceRoot, sourceHandle, refSegment) => {
let section;
if (refSegment === undefined || refSegment.length === 0) {

@@ -391,3 +369,3 @@ section = sourceRoot;

};
var resolveExternalLink = function (node, uri, refSegment, parentHandle) {
const resolveExternalLink = (node, uri, refSegment, parentHandle) => {
if (contextService && !/^[A-Za-z][A-Za-z0-9+\-.+]*:\/\/.*/.test(uri)) {

@@ -397,7 +375,7 @@ uri = contextService.resolveRelativePath(uri, parentHandle.uri);

uri = normalizeId(uri);
var referencedHandle = _this.getOrAddSchemaHandle(uri);
return referencedHandle.getUnresolvedSchema().then(function (unresolvedSchema) {
const referencedHandle = this.getOrAddSchemaHandle(uri);
return referencedHandle.getUnresolvedSchema().then(unresolvedSchema => {
parentHandle.dependencies.add(uri);
if (unresolvedSchema.errors.length) {
var loc = refSegment ? uri + '#' + refSegment : uri;
const loc = refSegment ? uri + '#' + refSegment : uri;
resolveErrors.push(localize('json.schema.problemloadingref', 'Problems loading reference \'{0}\': {1}', loc, unresolvedSchema.errors[0]));

@@ -409,9 +387,9 @@ }

};
var resolveRefs = function (node, parentSchema, parentHandle) {
var openPromises = [];
_this.traverseNodes(node, function (next) {
var seenRefs = new Set();
const resolveRefs = (node, parentSchema, parentHandle) => {
const openPromises = [];
this.traverseNodes(node, next => {
const seenRefs = new Set();
while (next.$ref) {
var ref = next.$ref;
var segments = ref.split('#', 2);
const ref = next.$ref;
const segments = ref.split('#', 2);
delete next.$ref;

@@ -426,3 +404,3 @@ if (segments[0].length > 0) {

if (!seenRefs.has(ref)) {
var id = segments[1];
const id = segments[1];
mergeRef(next, parentSchema, parentHandle, id);

@@ -433,15 +411,19 @@ seenRefs.add(ref);

}
if (next.$recursiveRef) {
usesUnsupportedFeatures.add('$recursiveRef');
}
if (next.$dynamicRef) {
usesUnsupportedFeatures.add('$dynamicRef');
}
});
return _this.promise.all(openPromises);
return this.promise.all(openPromises);
};
var collectAnchors = function (root) {
var result = new Map();
_this.traverseNodes(root, function (next) {
var id = next.$id || next.id;
if (typeof id === 'string' && id.charAt(0) === '#') {
// delete next.$id;
// delete next.id;
var anchor = id.substring(1);
const collectAnchors = (root) => {
const result = new Map();
this.traverseNodes(root, next => {
const id = next.$id || next.id;
const anchor = (0, objects_1.isString)(id) && id.charAt(0) === '#' ? id.substring(1) : next.$anchor;
if (anchor) {
if (result.has(anchor)) {
resolveErrors.push(localize('json.schema.duplicateid', 'Duplicate id declaration: \'{0}\'', id));
resolveErrors.push(localize('json.schema.duplicateid', 'Duplicate anchor declaration: \'{0}\'', anchor));
}

@@ -452,22 +434,27 @@ else {

}
if (next.$recursiveAnchor) {
usesUnsupportedFeatures.add('$recursiveAnchor');
}
if (next.$dynamicAnchor) {
usesUnsupportedFeatures.add('$dynamicAnchor');
}
});
return result;
};
return resolveRefs(schema, schema, handle).then(function (_) {
return new ResolvedSchema(schema, resolveErrors);
return resolveRefs(schema, schema, handle).then(_ => {
let resolveWarnings = [];
if (usesUnsupportedFeatures.size) {
resolveWarnings.push(localize('json.schema.warnings', 'The schema uses meta-schema features ({0}) that are not yet supported by the validator.', Array.from(usesUnsupportedFeatures.keys()).join(', ')));
}
return new ResolvedSchema(schema, resolveErrors, resolveWarnings, schemaDraft);
});
};
JSONSchemaService.prototype.traverseNodes = function (root, handle) {
}
traverseNodes(root, handle) {
if (!root || typeof root !== 'object') {
return Promise.resolve(null);
}
var seen = new Set();
var collectEntries = function () {
var entries = [];
for (var _i = 0; _i < arguments.length; _i++) {
entries[_i] = arguments[_i];
}
for (var _a = 0, entries_1 = entries; _a < entries_1.length; _a++) {
var entry = entries_1[_a];
if (typeof entry === 'object') {
const seen = new Set();
const collectEntries = (...entries) => {
for (const entry of entries) {
if ((0, objects_1.isObject)(entry)) {
toWalk.push(entry);

@@ -477,14 +464,9 @@ }

};
var collectMapEntries = function () {
var maps = [];
for (var _i = 0; _i < arguments.length; _i++) {
maps[_i] = arguments[_i];
}
for (var _a = 0, maps_1 = maps; _a < maps_1.length; _a++) {
var map = maps_1[_a];
if (typeof map === 'object') {
for (var k in map) {
var key = k;
var entry = map[key];
if (typeof entry === 'object') {
const collectMapEntries = (...maps) => {
for (const map of maps) {
if ((0, objects_1.isObject)(map)) {
for (const k in map) {
const key = k;
const entry = map[key];
if ((0, objects_1.isObject)(entry)) {
toWalk.push(entry);

@@ -496,13 +478,7 @@ }

};
var collectArrayEntries = function () {
var arrays = [];
for (var _i = 0; _i < arguments.length; _i++) {
arrays[_i] = arguments[_i];
}
for (var _a = 0, arrays_1 = arrays; _a < arrays_1.length; _a++) {
var array = arrays_1[_a];
const collectArrayEntries = (...arrays) => {
for (const array of arrays) {
if (Array.isArray(array)) {
for (var _b = 0, array_1 = array; _b < array_1.length; _b++) {
var entry = array_1[_b];
if (typeof entry === 'object') {
for (const entry of array) {
if ((0, objects_1.isObject)(entry)) {
toWalk.push(entry);

@@ -514,4 +490,16 @@ }

};
var toWalk = [root];
var next = toWalk.pop();
const collectEntryOrArrayEntries = (items) => {
if (Array.isArray(items)) {
for (const entry of items) {
if ((0, objects_1.isObject)(entry)) {
toWalk.push(entry);
}
}
}
else if ((0, objects_1.isObject)(items)) {
toWalk.push(items);
}
};
const toWalk = [root];
let next = toWalk.pop();
while (next) {

@@ -521,17 +509,16 @@ if (!seen.has(next)) {

handle(next);
collectEntries(next.items, next.additionalItems, next.additionalProperties, next.not, next.contains, next.propertyNames, next.if, next.then, next.else);
collectMapEntries(next.definitions, next.properties, next.patternProperties, next.dependencies);
collectArrayEntries(next.anyOf, next.allOf, next.oneOf, next.items);
collectEntries(next.additionalItems, next.additionalProperties, next.not, next.contains, next.propertyNames, next.if, next.then, next.else, next.unevaluatedItems, next.unevaluatedProperties);
collectMapEntries(next.definitions, next.$defs, next.properties, next.patternProperties, next.dependencies, next.dependentSchemas);
collectArrayEntries(next.anyOf, next.allOf, next.oneOf, next.prefixItems);
collectEntryOrArrayEntries(next.items);
}
next = toWalk.pop();
}
};
}
;
JSONSchemaService.prototype.getSchemaFromProperty = function (resource, document) {
var _a, _b;
if (((_a = document.root) === null || _a === void 0 ? void 0 : _a.type) === 'object') {
for (var _i = 0, _c = document.root.properties; _i < _c.length; _i++) {
var p = _c[_i];
if (p.keyNode.value === '$schema' && ((_b = p.valueNode) === null || _b === void 0 ? void 0 : _b.type) === 'string') {
var schemaId = p.valueNode.value;
getSchemaFromProperty(resource, document) {
if (document.root?.type === 'object') {
for (const p of document.root.properties) {
if (p.keyNode.value === '$schema' && p.valueNode?.type === 'string') {
let schemaId = p.valueNode.value;
if (this.contextService && !/^\w[\w\d+.-]*:/.test(schemaId)) { // has scheme

@@ -545,12 +532,10 @@ schemaId = this.contextService.resolveRelativePath(schemaId, resource);

return undefined;
};
JSONSchemaService.prototype.getAssociatedSchemas = function (resource) {
var seen = Object.create(null);
var schemas = [];
var normalizedResource = normalizeResourceForMatching(resource);
for (var _i = 0, _a = this.filePatternAssociations; _i < _a.length; _i++) {
var entry = _a[_i];
}
getAssociatedSchemas(resource) {
const seen = Object.create(null);
const schemas = [];
const normalizedResource = normalizeResourceForMatching(resource);
for (const entry of this.filePatternAssociations) {
if (entry.matchesPattern(normalizedResource)) {
for (var _b = 0, _c = entry.getURIs(); _b < _c.length; _b++) {
var schemaId = _c[_b];
for (const schemaId of entry.getURIs()) {
if (!seen[schemaId]) {

@@ -564,5 +549,5 @@ schemas.push(schemaId);

return schemas;
};
JSONSchemaService.prototype.getSchemaURIsForResource = function (resource, document) {
var schemeId = document && this.getSchemaFromProperty(resource, document);
}
getSchemaURIsForResource(resource, document) {
let schemeId = document && this.getSchemaFromProperty(resource, document);
if (schemeId) {

@@ -572,9 +557,9 @@ return [schemeId];

return this.getAssociatedSchemas(resource);
};
JSONSchemaService.prototype.getSchemaForResource = function (resource, document) {
}
getSchemaForResource(resource, document) {
if (document) {
// first use $schema if present
var schemeId = this.getSchemaFromProperty(resource, document);
let schemeId = this.getSchemaFromProperty(resource, document);
if (schemeId) {
var id = normalizeId(schemeId);
const id = normalizeId(schemeId);
return this.getOrAddSchemaHandle(id).getResolvedSchema();

@@ -586,8 +571,8 @@ }

}
var schemas = this.getAssociatedSchemas(resource);
var resolvedSchema = schemas.length > 0 ? this.createCombinedSchema(resource, schemas).getResolvedSchema() : this.promise.resolve(undefined);
this.cachedSchemaForResource = { resource: resource, resolvedSchema: resolvedSchema };
const schemas = this.getAssociatedSchemas(resource);
const resolvedSchema = schemas.length > 0 ? this.createCombinedSchema(resource, schemas).getResolvedSchema() : this.promise.resolve(undefined);
this.cachedSchemaForResource = { resource, resolvedSchema };
return resolvedSchema;
};
JSONSchemaService.prototype.createCombinedSchema = function (resource, schemaIds) {
}
createCombinedSchema(resource, schemaIds) {
if (schemaIds.length === 1) {

@@ -597,28 +582,27 @@ return this.getOrAddSchemaHandle(schemaIds[0]);

else {
var combinedSchemaId = 'schemaservice://combinedSchema/' + encodeURIComponent(resource);
var combinedSchema = {
allOf: schemaIds.map(function (schemaId) { return ({ $ref: schemaId }); })
const combinedSchemaId = 'schemaservice://combinedSchema/' + encodeURIComponent(resource);
const combinedSchema = {
allOf: schemaIds.map(schemaId => ({ $ref: schemaId }))
};
return this.addSchemaHandle(combinedSchemaId, combinedSchema);
}
};
JSONSchemaService.prototype.getMatchingSchemas = function (document, jsonDocument, schema) {
}
getMatchingSchemas(document, jsonDocument, schema) {
if (schema) {
var id = schema.id || ('schemaservice://untitled/matchingSchemas/' + idCounter++);
var handle = this.addSchemaHandle(id, schema);
return handle.getResolvedSchema().then(function (resolvedSchema) {
return jsonDocument.getMatchingSchemas(resolvedSchema.schema).filter(function (s) { return !s.inverted; });
const id = schema.id || ('schemaservice://untitled/matchingSchemas/' + idCounter++);
const handle = this.addSchemaHandle(id, schema);
return handle.getResolvedSchema().then(resolvedSchema => {
return jsonDocument.getMatchingSchemas(resolvedSchema.schema).filter(s => !s.inverted);
});
}
return this.getSchemaForResource(document.uri, jsonDocument).then(function (schema) {
return this.getSchemaForResource(document.uri, jsonDocument).then(schema => {
if (schema) {
return jsonDocument.getMatchingSchemas(schema.schema).filter(function (s) { return !s.inverted; });
return jsonDocument.getMatchingSchemas(schema.schema).filter(s => !s.inverted);
}
return [];
});
};
return JSONSchemaService;
}());
}
}
exports.JSONSchemaService = JSONSchemaService;
var idCounter = 0;
let idCounter = 0;
function normalizeId(id) {

@@ -644,3 +628,3 @@ // remove trailing '#', normalize drive capitalization

try {
var uri = vscode_uri_1.URI.parse(url);
const uri = vscode_uri_1.URI.parse(url);
if (uri.scheme === 'file') {

@@ -647,0 +631,0 @@ return uri.fsPath;

@@ -17,9 +17,9 @@ /*---------------------------------------------------------------------------------------------

exports.getSelectionRanges = void 0;
var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
var jsonc_parser_1 = require("jsonc-parser");
const jsonLanguageTypes_1 = require("../jsonLanguageTypes");
const jsonc_parser_1 = require("jsonc-parser");
function getSelectionRanges(document, positions, doc) {
function getSelectionRange(position) {
var offset = document.offsetAt(position);
var node = doc.getNodeFromOffset(offset, true);
var result = [];
let offset = document.offsetAt(position);
let node = doc.getNodeFromOffset(offset, true);
const result = [];
while (node) {

@@ -31,3 +31,3 @@ switch (node.type) {

// range without ", [ or {
var cStart = node.offset + 1, cEnd = node.offset + node.length - 1;
const cStart = node.offset + 1, cEnd = node.offset + node.length - 1;
if (cStart < cEnd && offset >= cStart && offset <= cEnd) {

@@ -46,3 +46,3 @@ result.push(newRange(cStart, cEnd));

if (node.type === 'property' || node.parent && node.parent.type === 'array') {
var afterCommaOffset = getOffsetAfterNextToken(node.offset + node.length, 5 /* CommaToken */);
const afterCommaOffset = getOffsetAfterNextToken(node.offset + node.length, 5 /* CommaToken */);
if (afterCommaOffset !== -1) {

@@ -54,4 +54,4 @@ result.push(newRange(node.offset, afterCommaOffset));

}
var current = undefined;
for (var index = result.length - 1; index >= 0; index--) {
let current = undefined;
for (let index = result.length - 1; index >= 0; index--) {
current = jsonLanguageTypes_1.SelectionRange.create(result[index], current);

@@ -67,6 +67,6 @@ }

}
var scanner = (0, jsonc_parser_1.createScanner)(document.getText(), true);
const scanner = (0, jsonc_parser_1.createScanner)(document.getText(), true);
function getOffsetAfterNextToken(offset, expectedToken) {
scanner.setPosition(offset);
var token = scanner.scan();
let token = scanner.scan();
if (token === expectedToken) {

@@ -73,0 +73,0 @@ return scanner.getTokenOffset() + scanner.getTokenLength();

@@ -17,8 +17,8 @@ /*---------------------------------------------------------------------------------------------

exports.JSONValidation = void 0;
var jsonLanguageTypes_1 = require("../jsonLanguageTypes");
var nls = require("vscode-nls");
var objects_1 = require("../utils/objects");
var localize = nls.loadMessageBundle();
var JSONValidation = /** @class */ (function () {
function JSONValidation(jsonSchemaService, promiseConstructor) {
const jsonLanguageTypes_1 = require("../jsonLanguageTypes");
const nls = require("vscode-nls");
const objects_1 = require("../utils/objects");
const localize = nls.loadMessageBundle();
class JSONValidation {
constructor(jsonSchemaService, promiseConstructor) {
this.jsonSchemaService = jsonSchemaService;

@@ -28,3 +28,3 @@ this.promise = promiseConstructor;

}
JSONValidation.prototype.configure = function (raw) {
configure(raw) {
if (raw) {

@@ -34,13 +34,12 @@ this.validationEnabled = raw.validate !== false;

}
};
JSONValidation.prototype.doValidation = function (textDocument, jsonDocument, documentSettings, schema) {
var _this = this;
}
doValidation(textDocument, jsonDocument, documentSettings, schema) {
if (!this.validationEnabled) {
return this.promise.resolve([]);
}
var diagnostics = [];
var added = {};
var addProblem = function (problem) {
const diagnostics = [];
const added = {};
const addProblem = (problem) => {
// remove duplicated messages
var signature = problem.range.start.line + ' ' + problem.range.start.character + ' ' + problem.message;
const signature = problem.range.start.line + ' ' + problem.range.start.character + ' ' + problem.message;
if (!added[signature]) {

@@ -51,23 +50,31 @@ added[signature] = true;

};
var getDiagnostics = function (schema) {
var trailingCommaSeverity = (documentSettings === null || documentSettings === void 0 ? void 0 : documentSettings.trailingCommas) ? toDiagnosticSeverity(documentSettings.trailingCommas) : jsonLanguageTypes_1.DiagnosticSeverity.Error;
var commentSeverity = (documentSettings === null || documentSettings === void 0 ? void 0 : documentSettings.comments) ? toDiagnosticSeverity(documentSettings.comments) : _this.commentSeverity;
var schemaValidation = (documentSettings === null || documentSettings === void 0 ? void 0 : documentSettings.schemaValidation) ? toDiagnosticSeverity(documentSettings.schemaValidation) : jsonLanguageTypes_1.DiagnosticSeverity.Warning;
var schemaRequest = (documentSettings === null || documentSettings === void 0 ? void 0 : documentSettings.schemaRequest) ? toDiagnosticSeverity(documentSettings.schemaRequest) : jsonLanguageTypes_1.DiagnosticSeverity.Warning;
const getDiagnostics = (schema) => {
let trailingCommaSeverity = documentSettings?.trailingCommas ? toDiagnosticSeverity(documentSettings.trailingCommas) : jsonLanguageTypes_1.DiagnosticSeverity.Error;
let commentSeverity = documentSettings?.comments ? toDiagnosticSeverity(documentSettings.comments) : this.commentSeverity;
let schemaValidation = documentSettings?.schemaValidation ? toDiagnosticSeverity(documentSettings.schemaValidation) : jsonLanguageTypes_1.DiagnosticSeverity.Warning;
let schemaRequest = documentSettings?.schemaRequest ? toDiagnosticSeverity(documentSettings.schemaRequest) : jsonLanguageTypes_1.DiagnosticSeverity.Warning;
if (schema) {
if (schema.errors.length && jsonDocument.root && schemaRequest) {
var astRoot = jsonDocument.root;
var property = astRoot.type === 'object' ? astRoot.properties[0] : undefined;
if (property && property.keyNode.value === '$schema') {
var node = property.valueNode || property;
var range = jsonLanguageTypes_1.Range.create(textDocument.positionAt(node.offset), textDocument.positionAt(node.offset + node.length));
addProblem(jsonLanguageTypes_1.Diagnostic.create(range, schema.errors[0], schemaRequest, jsonLanguageTypes_1.ErrorCode.SchemaResolveError));
const addSchemaProblem = (errorMessage, errorCode) => {
if (jsonDocument.root && schemaRequest) {
const astRoot = jsonDocument.root;
const property = astRoot.type === 'object' ? astRoot.properties[0] : undefined;
if (property && property.keyNode.value === '$schema') {
const node = property.valueNode || property;
const range = jsonLanguageTypes_1.Range.create(textDocument.positionAt(node.offset), textDocument.positionAt(node.offset + node.length));
addProblem(jsonLanguageTypes_1.Diagnostic.create(range, errorMessage, schemaRequest, errorCode));
}
else {
const range = jsonLanguageTypes_1.Range.create(textDocument.positionAt(astRoot.offset), textDocument.positionAt(astRoot.offset + 1));
addProblem(jsonLanguageTypes_1.Diagnostic.create(range, errorMessage, schemaRequest, errorCode));
}
}
else {
var range = jsonLanguageTypes_1.Range.create(textDocument.positionAt(astRoot.offset), textDocument.positionAt(astRoot.offset + 1));
addProblem(jsonLanguageTypes_1.Diagnostic.create(range, schema.errors[0], schemaRequest, jsonLanguageTypes_1.ErrorCode.SchemaResolveError));
}
};
if (schema.errors.length) {
addSchemaProblem(schema.errors[0], jsonLanguageTypes_1.ErrorCode.SchemaResolveError);
}
else if (schemaValidation) {
var semanticErrors = jsonDocument.validate(textDocument, schema.schema, schemaValidation);
for (const warning of schema.warnings) {
addSchemaProblem(warning, jsonLanguageTypes_1.ErrorCode.SchemaUnsupportedFeature);
}
const semanticErrors = jsonDocument.validate(textDocument, schema.schema, schemaValidation);
if (semanticErrors) {

@@ -84,4 +91,3 @@ semanticErrors.forEach(addProblem);

}
for (var _i = 0, _a = jsonDocument.syntaxErrors; _i < _a.length; _i++) {
var p = _a[_i];
for (const p of jsonDocument.syntaxErrors) {
if (p.code === jsonLanguageTypes_1.ErrorCode.TrailingComma) {

@@ -96,5 +102,5 @@ if (typeof trailingCommaSeverity !== 'number') {

if (typeof commentSeverity === 'number') {
var message_1 = localize('InvalidCommentToken', 'Comments are not permitted in JSON.');
jsonDocument.comments.forEach(function (c) {
addProblem(jsonLanguageTypes_1.Diagnostic.create(c, message_1, commentSeverity, jsonLanguageTypes_1.ErrorCode.CommentNotPermitted));
const message = localize('InvalidCommentToken', 'Comments are not permitted in JSON.');
jsonDocument.comments.forEach(c => {
addProblem(jsonLanguageTypes_1.Diagnostic.create(c, message, commentSeverity, jsonLanguageTypes_1.ErrorCode.CommentNotPermitted));
});

@@ -105,19 +111,18 @@ }

if (schema) {
var id = schema.id || ('schemaservice://untitled/' + idCounter++);
var handle = this.jsonSchemaService.registerExternalSchema(id, [], schema);
return handle.getResolvedSchema().then(function (resolvedSchema) {
const id = schema.id || ('schemaservice://untitled/' + idCounter++);
const handle = this.jsonSchemaService.registerExternalSchema(id, [], schema);
return handle.getResolvedSchema().then(resolvedSchema => {
return getDiagnostics(resolvedSchema);
});
}
return this.jsonSchemaService.getSchemaForResource(textDocument.uri, jsonDocument).then(function (schema) {
return this.jsonSchemaService.getSchemaForResource(textDocument.uri, jsonDocument).then(schema => {
return getDiagnostics(schema);
});
};
JSONValidation.prototype.getLanguageStatus = function (textDocument, jsonDocument) {
}
getLanguageStatus(textDocument, jsonDocument) {
return { schemas: this.jsonSchemaService.getSchemaURIsForResource(textDocument.uri, jsonDocument) };
};
return JSONValidation;
}());
}
}
exports.JSONValidation = JSONValidation;
var idCounter = 0;
let idCounter = 0;
function schemaAllowsComments(schemaRef) {

@@ -129,5 +134,4 @@ if (schemaRef && typeof schemaRef === 'object') {

if (schemaRef.allOf) {
for (var _i = 0, _a = schemaRef.allOf; _i < _a.length; _i++) {
var schema = _a[_i];
var allow = schemaAllowsComments(schema);
for (const schema of schemaRef.allOf) {
const allow = schemaAllowsComments(schema);
if ((0, objects_1.isBoolean)(allow)) {

@@ -146,3 +150,3 @@ return allow;

}
var deprSchemaRef = schemaRef;
const deprSchemaRef = schemaRef;
if ((0, objects_1.isBoolean)(deprSchemaRef['allowsTrailingCommas'])) { // deprecated

@@ -152,5 +156,4 @@ return deprSchemaRef['allowsTrailingCommas'];

if (schemaRef.allOf) {
for (var _i = 0, _a = schemaRef.allOf; _i < _a.length; _i++) {
var schema = _a[_i];
var allow = schemaAllowsTrailingCommas(schema);
for (const schema of schemaRef.allOf) {
const allow = schemaAllowsTrailingCommas(schema);
if ((0, objects_1.isBoolean)(allow)) {

@@ -157,0 +160,0 @@ return allow;

@@ -17,7 +17,7 @@ /*---------------------------------------------------------------------------------------------

exports.colorFrom256RGB = exports.colorFromHex = exports.hexDigit = void 0;
var Digit0 = 48;
var Digit9 = 57;
var A = 65;
var a = 97;
var f = 102;
const Digit0 = 48;
const Digit9 = 57;
const A = 65;
const a = 97;
const f = 102;
function hexDigit(charCode) {

@@ -76,4 +76,3 @@ if (charCode < Digit0) {

exports.colorFromHex = colorFromHex;
function colorFrom256RGB(red, green, blue, alpha) {
if (alpha === void 0) { alpha = 1.0; }
function colorFrom256RGB(red, green, blue, alpha = 1.0) {
return {

@@ -83,3 +82,3 @@ red: red / 255.0,

blue: blue / 255.0,
alpha: alpha
alpha
};

@@ -86,0 +85,0 @@ }

@@ -22,9 +22,9 @@ (function (factory) {

}
var str = String(glob);
const str = String(glob);
// The regexp we are building, as a string.
var reStr = "";
let reStr = "";
// Whether we are matching so called "extended" globs (like bash) and should
// support single character matching, matching ranges of characters, group
// matching, etc.
var extended = opts ? !!opts.extended : false;
const extended = opts ? !!opts.extended : false;
// When globstar is _false_ (default), '/foo/*' is translated a regexp like

@@ -39,10 +39,10 @@ // '^\/foo\/.*$' which will match any string beginning with '/foo/'

// globstar is _false_
var globstar = opts ? !!opts.globstar : false;
const globstar = opts ? !!opts.globstar : false;
// If we are doing extended matching, this boolean is true when we are inside
// a group (eg {*.html,*.js}), and false otherwise.
var inGroup = false;
let inGroup = false;
// RegExp flags (eg "i" ) to pass in to RegExp constructor.
var flags = opts && typeof (opts.flags) === "string" ? opts.flags : "";
var c;
for (var i = 0, len = str.length; i < len; i++) {
const flags = opts && typeof (opts.flags) === "string" ? opts.flags : "";
let c;
for (let i = 0, len = str.length; i < len; i++) {
c = str[i];

@@ -95,4 +95,4 @@ switch (c) {

// Also store the previous and next characters
var prevChar = str[i - 1];
var starCount = 1;
const prevChar = str[i - 1];
let starCount = 1;
while (str[i + 1] === "*") {

@@ -102,3 +102,3 @@ starCount++;

}
var nextChar = str[i + 1];
const nextChar = str[i + 1];
if (!globstar) {

@@ -110,3 +110,3 @@ // globstar is disabled, so treat any number of "*" as one

// globstar is enabled, so determine if this is a globstar segment
var isGlobstar = starCount > 1 // multiple "*"'s
const isGlobstar = starCount > 1 // multiple "*"'s
&& (prevChar === "/" || prevChar === undefined || prevChar === '{' || prevChar === ',') // from the start of the segment

@@ -113,0 +113,0 @@ && (nextChar === "/" || nextChar === undefined || nextChar === ',' || nextChar === '}'); // to the end of the segment

@@ -19,3 +19,3 @@ /*---------------------------------------------------------------------------------------------

if (obj !== null && typeof obj === 'object') {
var newIndent = indent + '\t';
const newIndent = indent + '\t';
if (Array.isArray(obj)) {

@@ -25,4 +25,4 @@ if (obj.length === 0) {

}
var result = '[\n';
for (var i = 0; i < obj.length; i++) {
let result = '[\n';
for (let i = 0; i < obj.length; i++) {
result += newIndent + stringifyObject(obj[i], newIndent, stringifyLiteral);

@@ -38,9 +38,9 @@ if (i < obj.length - 1) {

else {
var keys = Object.keys(obj);
const keys = Object.keys(obj);
if (keys.length === 0) {
return '{}';
}
var result = '{\n';
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
let result = '{\n';
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
result += newIndent + JSON.stringify(key) + ': ' + stringifyObject(obj[key], newIndent, stringifyLiteral);

@@ -47,0 +47,0 @@ if (i < keys.length - 1) {

@@ -16,3 +16,3 @@ /*---------------------------------------------------------------------------------------------

Object.defineProperty(exports, "__esModule", { value: true });
exports.isString = exports.isBoolean = exports.isDefined = exports.isNumber = exports.equals = void 0;
exports.isObject = exports.isString = exports.isBoolean = exports.isDefined = exports.isNumber = exports.equals = void 0;
function equals(one, other) {

@@ -84,2 +84,6 @@ if (one === other) {

exports.isString = isString;
function isObject(val) {
return typeof val === 'object' && val !== null && !Array.isArray(val);
}
exports.isObject = isObject;
});

@@ -21,3 +21,3 @@ /*---------------------------------------------------------------------------------------------

}
for (var i = 0; i < needle.length; i++) {
for (let i = 0; i < needle.length; i++) {
if (haystack[i] !== needle[i]) {

@@ -34,3 +34,3 @@ return false;

function endsWith(haystack, needle) {
var diff = haystack.length - needle.length;
const diff = haystack.length - needle.length;
if (diff > 0) {

@@ -64,3 +64,3 @@ return haystack.lastIndexOf(needle) === diff;

function extendedRegExp(pattern) {
var flags = '';
let flags = '';
if (startsWith(pattern, '(?i)')) {

@@ -67,0 +67,0 @@ pattern = pattern.substring(4);

{
"name": "vscode-json-languageservice",
"version": "4.2.1",
"version": "5.0.0",
"description": "Language service for JSON",

@@ -18,8 +18,8 @@ "main": "./lib/umd/jsonLanguageService.js",

"devDependencies": {
"@types/mocha": "^9.1.0",
"@types/node": "^10.12.21",
"@typescript-eslint/eslint-plugin": "^5.15.0",
"@typescript-eslint/parser": "^5.15.0",
"eslint": "^8.11.0",
"mocha": "^9.2.2",
"@types/mocha": "^9.1.1",
"@types/node": "16.x",
"@typescript-eslint/eslint-plugin": "^5.24.0",
"@typescript-eslint/parser": "^5.24.0",
"eslint": "^8.15.0",
"mocha": "^10.0.0",
"rimraf": "^3.0.2",

@@ -30,5 +30,5 @@ "typescript": "^4.5.5"

"jsonc-parser": "^3.0.0",
"vscode-languageserver-textdocument": "^1.0.3",
"vscode-languageserver-types": "^3.16.0",
"vscode-nls": "^5.0.0",
"vscode-languageserver-textdocument": "^1.0.4",
"vscode-languageserver-types": "^3.17.1",
"vscode-nls": "^5.0.1",
"vscode-uri": "^3.0.3"

@@ -35,0 +35,0 @@ },

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc