forked from microsoft/vscode-json-languageservice
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjsonSchemaService.ts
More file actions
739 lines (637 loc) · 24.7 KB
/
Copy pathjsonSchemaService.ts
File metadata and controls
739 lines (637 loc) · 24.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as Json from 'jsonc-parser';
import { JSONSchema, JSONSchemaMap, JSONSchemaRef } from '../jsonSchema';
import { URI } from 'vscode-uri';
import * as Strings from '../utils/strings';
import * as Parser from '../parser/jsonParser';
import { SchemaRequestService, WorkspaceContextService, PromiseConstructor, Thenable, MatchingSchema, TextDocument } from '../jsonLanguageTypes';
import * as nls from 'vscode-nls';
import { createRegex } from '../utils/glob';
const localize = nls.loadMessageBundle();
export interface IJSONSchemaService {
/**
* Registers a schema file in the current workspace to be applicable to files that match the pattern
*/
registerExternalSchema(uri: string, filePatterns?: string[], unresolvedSchema?: JSONSchema): ISchemaHandle;
/**
* Clears all cached schema files
*/
clearExternalSchemas(): void;
/**
* Registers contributed schemas
*/
setSchemaContributions(schemaContributions: ISchemaContributions): void;
/**
* Looks up the appropriate schema for the given URI
*/
getSchemaForResource(resource: string, document?: Parser.JSONDocument): Thenable<ResolvedSchema | undefined>;
/**
* Returns all registered schema ids
*/
getRegisteredSchemaIds(filter?: (scheme: string) => boolean): string[];
}
export interface SchemaAssociation {
pattern: string[];
uris: string[];
}
export interface ISchemaContributions {
schemas?: { [id: string]: JSONSchema };
schemaAssociations?: SchemaAssociation[];
}
export interface ISchemaHandle {
/**
* The schema id
*/
url: string;
/**
* The schema from the file, with potential $ref references
*/
getUnresolvedSchema(): Thenable<UnresolvedSchema>;
/**
* The schema from the file, with references resolved
*/
getResolvedSchema(): Thenable<ResolvedSchema>;
}
const BANG = '!';
const PATH_SEP = '/';
interface IGlobWrapper {
regexp: RegExp;
include: boolean;
}
class FilePatternAssociation {
private readonly uris: string[];
private readonly globWrappers: IGlobWrapper[];
constructor(pattern: string[], uris: string[]) {
this.globWrappers = [];
try {
for (let patternString of pattern) {
const include = patternString[0] !== BANG;
if (!include) {
patternString = patternString.substring(1);
}
if (patternString.length > 0) {
if (patternString[0] === PATH_SEP) {
patternString = patternString.substring(1);
}
this.globWrappers.push({
regexp: createRegex('**/' + patternString, { extended: true, globstar: true }),
include: include,
});
}
};
this.uris = uris;
} catch (e) {
this.globWrappers.length = 0;
this.uris = [];
}
}
public matchesPattern(fileName: string): boolean {
let match = false;
for (const { regexp, include } of this.globWrappers) {
if (regexp.test(fileName)) {
match = include;
}
}
return match;
}
public getURIs() {
return this.uris;
}
}
type SchemaDependencies = { [uri: string]: true };
class SchemaHandle implements ISchemaHandle {
public url: string;
public dependencies: SchemaDependencies;
private resolvedSchema: Thenable<ResolvedSchema> | undefined;
private unresolvedSchema: Thenable<UnresolvedSchema> | undefined;
private service: JSONSchemaService;
constructor(service: JSONSchemaService, url: string, unresolvedSchemaContent?: JSONSchema) {
this.service = service;
this.url = url;
this.dependencies = {};
if (unresolvedSchemaContent) {
this.unresolvedSchema = this.service.promise.resolve(new UnresolvedSchema(unresolvedSchemaContent));
}
}
public getUnresolvedSchema(): Thenable<UnresolvedSchema> {
if (!this.unresolvedSchema) {
this.unresolvedSchema = this.service.loadSchema(this.url);
}
return this.unresolvedSchema;
}
public getResolvedSchema(): Thenable<ResolvedSchema> {
if (!this.resolvedSchema) {
this.resolvedSchema = this.getUnresolvedSchema().then(unresolved => {
return this.service.resolveSchemaContent(unresolved, this.url, this.dependencies);
});
}
return this.resolvedSchema;
}
public clearSchema() {
this.resolvedSchema = undefined;
this.unresolvedSchema = undefined;
this.dependencies = {};
}
}
export class UnresolvedSchema {
public schema: JSONSchema;
public errors: string[];
constructor(schema: JSONSchema, errors: string[] = []) {
this.schema = schema;
this.errors = errors;
}
}
export class ResolvedSchema {
public schema: JSONSchema;
public errors: string[];
constructor(schema: JSONSchema, errors: string[] = []) {
this.schema = schema;
this.errors = errors;
}
public getSection(path: string[]): JSONSchema | undefined {
const schemaRef = this.getSectionRecursive(path, this.schema);
if (schemaRef) {
return Parser.asSchema(schemaRef);
}
return undefined;
}
private getSectionRecursive(path: string[], schema: JSONSchemaRef): JSONSchemaRef | undefined {
if (!schema || typeof schema === 'boolean' || path.length === 0) {
return schema;
}
const next = path.shift()!;
if (schema.properties && typeof schema.properties[next]) {
return this.getSectionRecursive(path, schema.properties[next]);
} else if (schema.patternProperties) {
for (const pattern of Object.keys(schema.patternProperties)) {
const regex = Strings.extendedRegExp(pattern);
if (regex.test(next)) {
return this.getSectionRecursive(path, schema.patternProperties[pattern]);
}
}
} else if (typeof schema.additionalProperties === 'object') {
return this.getSectionRecursive(path, schema.additionalProperties);
} else if (next.match('[0-9]+')) {
if (Array.isArray(schema.items)) {
const index = parseInt(next, 10);
if (!isNaN(index) && schema.items[index]) {
return this.getSectionRecursive(path, schema.items[index]);
}
} else if (schema.items) {
return this.getSectionRecursive(path, schema.items);
}
}
return undefined;
}
}
export class JSONSchemaService implements IJSONSchemaService {
private contributionSchemas: { [id: string]: SchemaHandle };
private contributionAssociations: FilePatternAssociation[];
private schemasById: { [id: string]: SchemaHandle };
private filePatternAssociations: FilePatternAssociation[];
private registeredSchemasIds: { [id: string]: boolean };
private contextService: WorkspaceContextService | undefined;
private callOnDispose: Function[];
private requestService: SchemaRequestService | undefined;
private promiseConstructor: PromiseConstructor;
private cachedSchemaForResource: { resource: string; resolvedSchema: Thenable<ResolvedSchema | undefined> } | undefined;
constructor(requestService?: SchemaRequestService, contextService?: WorkspaceContextService, promiseConstructor?: PromiseConstructor) {
this.contextService = contextService;
this.requestService = requestService;
this.promiseConstructor = promiseConstructor || Promise;
this.callOnDispose = [];
this.contributionSchemas = {};
this.contributionAssociations = [];
this.schemasById = {};
this.filePatternAssociations = [];
this.registeredSchemasIds = {};
}
public getRegisteredSchemaIds(filter?: (scheme: string) => boolean): string[] {
return Object.keys(this.registeredSchemasIds).filter(id => {
const scheme = URI.parse(id).scheme;
return scheme !== 'schemaservice' && (!filter || filter(scheme));
});
}
public get promise() {
return this.promiseConstructor;
}
public dispose(): void {
while (this.callOnDispose.length > 0) {
this.callOnDispose.pop()!();
}
}
public onResourceChange(uri: string): boolean {
// always clear this local cache when a resource changes
this.cachedSchemaForResource = undefined;
let hasChanges = false;
uri = normalizeId(uri);
const toWalk = [uri];
const all: (SchemaHandle | undefined)[] = Object.keys(this.schemasById).map(key => this.schemasById[key]);
while (toWalk.length) {
const curr = toWalk.pop()!;
for (let i = 0; i < all.length; i++) {
const handle = all[i];
if (handle && (handle.url === curr || handle.dependencies[curr])) {
if (handle.url !== curr) {
toWalk.push(handle.url);
}
handle.clearSchema();
all[i] = undefined;
hasChanges = true;
}
}
}
return hasChanges;
}
public setSchemaContributions(schemaContributions: ISchemaContributions): void {
if (schemaContributions.schemas) {
const schemas = schemaContributions.schemas;
for (const id in schemas) {
const normalizedId = normalizeId(id);
this.contributionSchemas[normalizedId] = this.addSchemaHandle(normalizedId, schemas[id]);
}
}
if (Array.isArray(schemaContributions.schemaAssociations)) {
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);
}
}
}
private addSchemaHandle(id: string, unresolvedSchemaContent?: JSONSchema): SchemaHandle {
const schemaHandle = new SchemaHandle(this, id, unresolvedSchemaContent);
this.schemasById[id] = schemaHandle;
return schemaHandle;
}
private getOrAddSchemaHandle(id: string, unresolvedSchemaContent?: JSONSchema): SchemaHandle {
return this.schemasById[id] || this.addSchemaHandle(id, unresolvedSchemaContent);
}
private addFilePatternAssociation(pattern: string[], uris: string[]): FilePatternAssociation {
const fpa = new FilePatternAssociation(pattern, uris);
this.filePatternAssociations.push(fpa);
return fpa;
}
public registerExternalSchema(uri: string, filePatterns?: string[], unresolvedSchemaContent?: JSONSchema): ISchemaHandle {
const id = normalizeId(uri);
this.registeredSchemasIds[id] = true;
this.cachedSchemaForResource = undefined;
if (filePatterns) {
this.addFilePatternAssociation(filePatterns, [uri]);
}
return unresolvedSchemaContent ? this.addSchemaHandle(id, unresolvedSchemaContent) : this.getOrAddSchemaHandle(id);
}
public clearExternalSchemas(): void {
this.schemasById = {};
this.filePatternAssociations = [];
this.registeredSchemasIds = {};
this.cachedSchemaForResource = undefined;
for (const id in this.contributionSchemas) {
this.schemasById[id] = this.contributionSchemas[id];
this.registeredSchemasIds[id] = true;
}
for (const contributionAssociation of this.contributionAssociations) {
this.filePatternAssociations.push(contributionAssociation);
}
}
public getResolvedSchema(schemaId: string): Thenable<ResolvedSchema | undefined> {
const id = normalizeId(schemaId);
const schemaHandle = this.schemasById[id];
if (schemaHandle) {
return schemaHandle.getResolvedSchema();
}
return this.promise.resolve(undefined);
}
public loadSchema(url: string): Thenable<UnresolvedSchema> {
if (!this.requestService) {
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(<JSONSchema>{}, [errorMessage]));
}
return this.requestService(url).then(
content => {
if (!content) {
const errorMessage = localize('json.schema.nocontent', 'Unable to load schema from \'{0}\': No content.', toDisplayString(url));
return new UnresolvedSchema(<JSONSchema>{}, [errorMessage]);
}
let schemaContent: JSONSchema = {};
const jsonErrors: Json.ParseError[] = [];
schemaContent = Json.parse(content, jsonErrors);
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);
},
(error: any) => {
let errorMessage = error.toString() as string;
const errorSplit = error.toString().split('Error: ');
if (errorSplit.length > 1) {
// more concise error message, URL and context are attached by caller anyways
errorMessage = errorSplit[1];
}
if (Strings.endsWith(errorMessage, '.')) {
errorMessage = errorMessage.substr(0, errorMessage.length - 1);
}
return new UnresolvedSchema(<JSONSchema>{}, [localize('json.schema.nocontent', 'Unable to load schema from \'{0}\': {1}.', toDisplayString(url), errorMessage)]);
}
);
}
public resolveSchemaContent(schemaToResolve: UnresolvedSchema, schemaURL: string, dependencies: SchemaDependencies): Thenable<ResolvedSchema> {
const resolveErrors: string[] = schemaToResolve.errors.slice(0);
const schema = schemaToResolve.schema;
if (schema.$schema) {
const 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."));
}
}
const contextService = this.contextService;
const findSection = (schema: JSONSchema, path: string | undefined): any => {
if (!path) {
return schema;
}
let current: any = schema;
if (path[0] === '/') {
path = path.substr(1);
}
path.split('/').some((part) => {
part = part.replace(/~1/g, '/').replace(/~0/g, '~');
current = current[part];
return !current;
});
return current;
};
const merge = (target: JSONSchema, section: any): void => {
for (const key in section) {
if (section.hasOwnProperty(key) && !target.hasOwnProperty(key)) {
(<any>target)[key] = section[key];
}
}
};
const mergeByJsonPointer = (target: JSONSchema, sourceRoot: JSONSchema, sourceURI: string, refSegment: string | undefined): void => {
const path = refSegment ? decodeURIComponent(refSegment) : undefined;
const section = findSection(sourceRoot, path);
if (section) {
merge(target, section);
} else {
resolveErrors.push(localize('json.schema.invalidref', '$ref \'{0}\' in \'{1}\' can not be resolved.', path, sourceURI));
}
};
const isSubSchemaRef = (refSegment?: string): boolean => {
// Check if the first character is not '/' to determine whether it's a sub schema reference or a JSON Pointer
return !!refSegment && refSegment.charAt(0) !== '/';
};
const reconstructRefURI = (uri: string, fragment?: string, separator: string = '#'): string => {
return normalizeId(`${uri}${separator}${fragment}`);
};
// To find which $refs point to which $ids we'll keep two maps:
// One for '$id' we expect to encounter (if they exist)
// and one for '$id' we have encountered
const pendingSubSchemas: Record<string, JSONSchema[]> = {};
const resolvedSubSchemas: Record<string, JSONSchema> = {};
const tryMergeSubSchema = (uri: string, target: JSONSchema) : boolean => {
if (resolvedSubSchemas[uri]) { // subschema is resolved, merge it to the target
merge(target, resolvedSubSchemas[uri]);
return true; // return success
} else { // This subschema has not been resolved yet
if (!pendingSubSchemas[uri]) {
pendingSubSchemas[uri] = [];
}
// Remember the target to merge later once resolved
pendingSubSchemas[uri].push(target);
return false; // return failure - merge didn't occur
}
};
const resolveExternalLink = (node: JSONSchema, uri: string, refSegment: string | undefined, parentSchemaURL: string, parentSchemaDependencies: SchemaDependencies): Thenable<any> => {
if (contextService && !/^[A-Za-z][A-Za-z0-9+\-.+]*:\/\/.*/.test(uri)) {
uri = contextService.resolveRelativePath(uri, parentSchemaURL);
}
uri = normalizeId(uri);
const referencedHandle = this.getOrAddSchemaHandle(uri);
return referencedHandle.getUnresolvedSchema().then(unresolvedSchema => {
parentSchemaDependencies[uri] = true;
if (unresolvedSchema.errors.length) {
const loc = refSegment ? uri + '#' + refSegment : uri;
resolveErrors.push(localize('json.schema.problemloadingref', 'Problems loading reference \'{0}\': {1}', loc, unresolvedSchema.errors[0]));
}
// A placeholder promise that might execute later a ref resolution for the newly resolved schema
let externalLinkPromise: Thenable<any> = Promise.resolve(true);
if(!isSubSchemaRef(refSegment)) {
// This is not a sub schema, merge the regular way
mergeByJsonPointer(node, unresolvedSchema.schema, uri, refSegment);
} else {
// This is a reference to a subschema
const fullId = reconstructRefURI(uri, refSegment);
if (!tryMergeSubSchema(fullId, node)) {
// We weren't able to merge currently so we'll try to resolve this schema first to obtain subschemas
// that could be missed
externalLinkPromise = resolveRefs(unresolvedSchema.schema, unresolvedSchema.schema, uri, referencedHandle.dependencies);
}
}
return externalLinkPromise.then(() => resolveRefs(node, unresolvedSchema.schema, uri, referencedHandle.dependencies));
});
};
const resolveRefs = (node: JSONSchema, parentSchema: JSONSchema, parentSchemaURL: string, parentSchemaDependencies: SchemaDependencies): Thenable<any> => {
if (!node || typeof node !== 'object') {
return Promise.resolve(null);
}
const toWalk: JSONSchema[] = [node];
const seen: JSONSchema[] = [];
const openPromises: Thenable<any>[] = [];
const collectEntries = (...entries: (JSONSchemaRef | undefined)[]) => {
for (const entry of entries) {
if (typeof entry === 'object') {
toWalk.push(entry);
}
}
};
const collectMapEntries = (...maps: (JSONSchemaMap | undefined)[]) => {
for (const map of maps) {
if (typeof map === 'object') {
for (const k in map) {
const key = k as keyof JSONSchemaMap;
const entry = map[key];
if (typeof entry === 'object') {
toWalk.push(entry);
}
}
}
}
};
const collectArrayEntries = (...arrays: (JSONSchemaRef[] | undefined)[]) => {
for (const array of arrays) {
if (Array.isArray(array)) {
for (const entry of array) {
if (typeof entry === 'object') {
toWalk.push(entry);
}
}
}
}
};
const handleRef = (next: JSONSchema) => {
const seenRefs = [];
while (next.$ref) {
const ref = next.$ref;
const segments = ref.split('#', 2);
delete next.$ref;
if (segments[0].length > 0) {
// This is a reference to an external schema
openPromises.push(resolveExternalLink(next, segments[0], segments[1], parentSchemaURL, parentSchemaDependencies));
return;
} else {
// This is a reference inside the current schema
if (seenRefs.indexOf(ref) === -1) {
if (isSubSchemaRef(segments[1])) { // A $ref to a sub-schema with an $id (i.e #hello)
// Get the full URI for the current schema to avoid matching schema1#hello and schema2#hello to the same
// reference by accident
const fullId = reconstructRefURI(parentSchemaURL, segments[1]);
tryMergeSubSchema(fullId, next);
} else { // A $ref to a JSON Pointer (i.e #/definitions/foo)
mergeByJsonPointer(next, parentSchema, parentSchemaURL, segments[1]); // can set next.$ref again, use seenRefs to avoid circle
}
seenRefs.push(ref);
}
}
}
collectEntries(<JSONSchema>next.items, next.additionalItems, <JSONSchema>next.additionalProperties, next.not, next.contains, next.propertyNames, next.if, next.then, next.else);
collectMapEntries(next.definitions, next.properties, next.patternProperties, <JSONSchemaMap>next.dependencies);
collectArrayEntries(next.anyOf, next.allOf, next.oneOf, <JSONSchema[]>next.items);
};
const handleId = (next: JSONSchema) => {
// TODO figure out should loops be preventse
const id = next.$id || next.id;
if (typeof id === 'string' && id.charAt(0) === '#') {
delete next.$id;
delete next.id;
// Use a blank separator, as the $id already has the '#'
const fullId = reconstructRefURI(parentSchemaURL, id, '');
if (!resolvedSubSchemas[fullId]) {
// This is the place we fill the blanks in
resolvedSubSchemas[fullId] = next;
} else if (resolvedSubSchemas[fullId] !== next) {
// Duplicate may occur in recursive $refs, but as long as they are the same object
// it's ok, otherwise report and error
resolveErrors.push(localize('json.schema.duplicateid', 'Duplicate id declaration: \'{0}\'', id));
}
// Resolve all pending requests and cleanup the queue list
if (pendingSubSchemas[fullId]) {
while (pendingSubSchemas[fullId].length) {
const target = pendingSubSchemas[fullId].shift();
merge(target!, next);
}
delete pendingSubSchemas[fullId];
}
}
};
while (toWalk.length) {
const next = toWalk.pop()!;
if (seen.indexOf(next) >= 0) {
continue;
}
seen.push(next);
handleRef(next);
handleId(next);
}
return this.promise.all(openPromises);
};
for(const unresolvedSubschemaId in pendingSubSchemas) {
resolveErrors.push(localize('json.schema.idnotfound', 'Subschema with id \'{0}\' was not found', unresolvedSubschemaId));
}
return resolveRefs(schema, schema, schemaURL, dependencies).then(_ => new ResolvedSchema(schema, resolveErrors));
}
public getSchemaForResource(resource: string, document?: Parser.JSONDocument): Thenable<ResolvedSchema | undefined> {
// first use $schema if present
if (document && document.root && document.root.type === 'object') {
const schemaProperties = document.root.properties.filter(p => (p.keyNode.value === '$schema') && p.valueNode && p.valueNode.type === 'string');
if (schemaProperties.length > 0) {
const valueNode = schemaProperties[0].valueNode;
if (valueNode && valueNode.type === 'string') {
let schemeId = <string>Parser.getNodeValue(valueNode);
if (schemeId && Strings.startsWith(schemeId, '.') && this.contextService) {
schemeId = this.contextService.resolveRelativePath(schemeId, resource);
}
if (schemeId) {
const id = normalizeId(schemeId);
return this.getOrAddSchemaHandle(id).getResolvedSchema();
}
}
}
}
if (this.cachedSchemaForResource && this.cachedSchemaForResource.resource === resource) {
return this.cachedSchemaForResource.resolvedSchema;
}
const seen: { [schemaId: string]: boolean } = Object.create(null);
const schemas: string[] = [];
const normalizedResource = normalizeResourceForMatching(resource);
for (const entry of this.filePatternAssociations) {
if (entry.matchesPattern(normalizedResource)) {
for (const schemaId of entry.getURIs()) {
if (!seen[schemaId]) {
schemas.push(schemaId);
seen[schemaId] = true;
}
}
}
}
const resolvedSchema = schemas.length > 0 ? this.createCombinedSchema(resource, schemas).getResolvedSchema() : this.promise.resolve(undefined);
this.cachedSchemaForResource = { resource, resolvedSchema };
return resolvedSchema;
}
private createCombinedSchema(resource: string, schemaIds: string[]): ISchemaHandle {
if (schemaIds.length === 1) {
return this.getOrAddSchemaHandle(schemaIds[0]);
} else {
const combinedSchemaId = 'schemaservice://combinedSchema/' + encodeURIComponent(resource);
const combinedSchema: JSONSchema = {
allOf: schemaIds.map(schemaId => ({ $ref: schemaId }))
};
return this.addSchemaHandle(combinedSchemaId, combinedSchema);
}
}
public getMatchingSchemas(document: TextDocument, jsonDocument: Parser.JSONDocument, schema?: JSONSchema): Thenable<MatchingSchema[]> {
if (schema) {
const id = schema.id || ('schemaservice://untitled/matchingSchemas/' + idCounter++);
return this.resolveSchemaContent(new UnresolvedSchema(schema), id, {}).then(resolvedSchema => {
return jsonDocument.getMatchingSchemas(resolvedSchema.schema).filter(s => !s.inverted);
});
}
return this.getSchemaForResource(document.uri, jsonDocument).then(schema => {
if (schema) {
return jsonDocument.getMatchingSchemas(schema.schema).filter(s => !s.inverted);
}
return [];
});
}
}
let idCounter = 0;
function normalizeId(id: string): string {
// remove trailing '#', normalize drive capitalization
try {
return URI.parse(id).toString();
} catch (e) {
return id;
}
}
function normalizeResourceForMatching(resource: string): string {
// remove queries and fragments, normalize drive capitalization
try {
return URI.parse(resource).with({ fragment: null, query: null }).toString();
} catch (e) {
return resource;
}
}
function toDisplayString(url: string) {
try {
const uri = URI.parse(url);
if (uri.scheme === 'file') {
return uri.fsPath;
}
} catch (e) {
// ignore
}
return url;
}