forked from redhat-developer/yaml-language-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathyamlSchemaService.ts
More file actions
1466 lines (1325 loc) · 53.4 KB
/
yamlSchemaService.ts
File metadata and controls
1466 lines (1325 loc) · 53.4 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
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat, Inc. All rights reserved.
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import {
ISchemaContributions,
JSONSchemaService,
ResolvedSchema,
SchemaDependencies,
SchemaHandle,
UnresolvedSchema,
} from 'vscode-json-languageservice/lib/umd/services/jsonSchemaService';
import { SettingsState } from '../../yamlSettings';
import { JSONSchema, JSONSchemaMap, JSONSchemaRef, SchemaDialect } from '../jsonSchema';
import { SchemaPriority, SchemaRequestService, WorkspaceContextService } from '../yamlLanguageService';
import * as l10n from '@vscode/l10n';
import * as path from 'path';
import { URI } from 'vscode-uri';
import { JSONSchemaDescriptionExt } from '../../requestTypes';
import { JSONDocument } from '../parser/jsonDocument';
import { SingleYAMLDocument } from '../parser/yamlParser07';
import { SchemaVersions } from '../yamlTypes';
import { getSchemaFromModeline } from './modelineUtil';
import Ajv, { DefinedError, type AnySchemaObject, type ValidateFunction } from 'ajv';
import Ajv4 from 'ajv-draft-04';
import Ajv2019 from 'ajv/dist/2019';
import Ajv2020 from 'ajv/dist/2020';
import * as Json from 'jsonc-parser';
import { parse } from 'yaml';
import { CRD_CATALOG_URL, KUBERNETES_SCHEMA_URL } from '../utils/schemaUrls';
import { autoDetectKubernetesSchema } from './k8sSchemaUtil';
const ajv4 = new Ajv4({ allErrors: true });
const ajv7 = new Ajv({ allErrors: true });
const ajv2019 = new Ajv2019({ allErrors: true });
const ajv2020 = new Ajv2020({ allErrors: true });
// eslint-disable-next-line @typescript-eslint/no-var-requires
const jsonSchema04 = require('ajv-draft-04/dist/refs/json-schema-draft-04.json');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const jsonSchema07 = require('ajv/dist/refs/json-schema-draft-07.json');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const jsonSchema2019 = require('ajv/dist/refs/json-schema-2019-09/schema.json');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const jsonSchema2020 = require('ajv/dist/refs/json-schema-2020-12/schema.json');
const schema04Validator = ajv4.compile(jsonSchema04);
const schema07Validator = ajv7.compile(jsonSchema07);
const schema2019Validator = ajv2019.compile(jsonSchema2019);
const schema2020Validator = ajv2020.compile(jsonSchema2020);
const schemaDialectCache = new Map<string, SchemaDialect>();
const schemaDialectInFlight = new Map<string, Promise<SchemaDialect>>();
// metadata/keywords that don't add constraints and thus don't count as $ref siblings
const REF_SIBLING_NONCONSTRAINT_KEYS = new Set([
'$ref',
'_$ref',
'$schema',
'$id',
'id',
'_baseUrl',
'_dialect',
'$anchor',
'$dynamicAnchor',
'$dynamicRef',
'$recursiveAnchor',
'$recursiveRef',
'definitions',
'$defs',
'$comment',
'title',
'description',
'markdownDescription',
'$vocabulary',
'examples',
'default',
'url',
'closestTitle',
'unevaluatedProperties',
'unevaluatedItems',
]);
export declare type CustomSchemaProvider = (uri: string) => Promise<string | string[]>;
export enum MODIFICATION_ACTIONS {
'delete',
'add',
'deleteAll',
}
export interface SchemaAdditions {
schema: string;
action: MODIFICATION_ACTIONS.add;
path: string;
key: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
content: any;
}
export interface SchemaDeletions {
schema: string;
action: MODIFICATION_ACTIONS.delete;
path: string;
key: string;
}
export interface SchemaDeletionsAll {
schemas: string[];
action: MODIFICATION_ACTIONS.deleteAll;
}
interface SchemaStoreSchema {
name: string;
description: string;
versions?: SchemaVersions;
}
export class YAMLSchemaService extends JSONSchemaService {
// To allow to use schemasById from super.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[x: string]: any;
private customSchemaProvider: CustomSchemaProvider | undefined;
private filePatternAssociations: JSONSchemaService.FilePatternAssociation[];
private contextService: WorkspaceContextService;
private requestService: SchemaRequestService;
private yamlSettings: SettingsState;
public schemaPriorityMapping: Map<string, Set<SchemaPriority>>;
private schemaUriToNameAndDescription = new Map<string, SchemaStoreSchema>();
constructor(
requestService: SchemaRequestService,
contextService?: WorkspaceContextService,
promiseConstructor?: PromiseConstructor,
yamlSettings?: SettingsState
) {
super(requestService, contextService, promiseConstructor);
this.customSchemaProvider = undefined;
this.requestService = requestService;
this.schemaPriorityMapping = new Map();
this.yamlSettings = yamlSettings;
}
registerCustomSchemaProvider(customSchemaProvider: CustomSchemaProvider): void {
this.customSchemaProvider = customSchemaProvider;
}
getAllSchemas(): JSONSchemaDescriptionExt[] {
const result: JSONSchemaDescriptionExt[] = [];
const schemaUris = new Set<string>();
for (const filePattern of this.filePatternAssociations) {
const schemaUri = filePattern.uris[0];
if (schemaUris.has(schemaUri)) {
continue;
}
schemaUris.add(schemaUri);
const schemaHandle: JSONSchemaDescriptionExt = {
uri: schemaUri,
fromStore: false,
usedForCurrentFile: false,
};
if (this.schemaUriToNameAndDescription.has(schemaUri)) {
const { name, description, versions } = this.schemaUriToNameAndDescription.get(schemaUri);
schemaHandle.name = name;
schemaHandle.description = description;
schemaHandle.fromStore = true;
schemaHandle.versions = versions;
}
result.push(schemaHandle);
}
return result;
}
private collectSchemaNodes(push: (node: JSONSchema) => void, ...values: unknown[]): void {
const collect = (value: unknown): void => {
if (!value || typeof value !== 'object') return;
if (Array.isArray(value)) {
for (const entry of value) {
collect(entry);
}
return;
}
push(value as JSONSchema);
};
for (const value of values) {
collect(value);
}
}
private schemaMapValues(map?: JSONSchemaMap): JSONSchemaRef[] | undefined {
if (!map || typeof map !== 'object') return undefined;
return Object.values(map);
}
async resolveSchemaContent(
schemaToResolve: UnresolvedSchema,
schemaURL: string,
dependencies: SchemaDependencies
): Promise<ResolvedSchema> {
const resolveErrors: string[] = schemaToResolve.errors.slice(0);
const loc = toDisplayString(schemaURL);
const raw: unknown = schemaToResolve.schema;
if (raw === null || Array.isArray(raw) || (typeof raw !== 'object' && typeof raw !== 'boolean')) {
const got = raw === null ? 'null' : Array.isArray(raw) ? 'array' : typeof raw;
resolveErrors.push(
l10n.t("Schema '{0}' is not valid: {1}", loc, `expected a JSON Schema object or boolean, got "${got}".`)
);
return new ResolvedSchema({}, resolveErrors);
}
const _cloneSchema = (
value: unknown,
seen: Map<object, unknown>,
stopCondition?: (val: unknown, seenSize: number) => unknown | undefined
): unknown => {
// primitives and null
if (value === null || typeof value !== 'object') return value;
if (stopCondition) {
const replacement = stopCondition(value, seen.size);
if (replacement !== undefined) return replacement;
}
// already cloned
if (seen.has(value)) return seen.get(value);
// clone arrays
if (Array.isArray(value)) {
const arr = [];
seen.set(value, arr);
for (const item of value) {
arr.push(_cloneSchema(item, seen, stopCondition));
}
return arr;
}
// clone objects
const result = {};
seen.set(value, result);
for (const prop in value) {
result[prop] = _cloneSchema(value[prop], seen, stopCondition);
}
return result;
};
/**
* ----------------------------
* Meta-validate a schema node against its dialect's meta-schema
* ----------------------------
*/
const _loadSchema = this.loadSchema.bind(this);
async function _metaValidateSchemaNode(node: JSONSchema, hasNestedSchema: boolean): Promise<void> {
if (!node || typeof node !== 'object') return;
const dialect = await pickSchemaDialect(node.$schema, _loadSchema);
dialect && (node._dialect = dialect);
const validator = pickMetaValidator(dialect);
if (!validator) return;
let toValidate = node;
if (hasNestedSchema) {
// clone for meta-validation: stop at dialect boundaries abd replace with {}
const stopAtDialectBoundary = (val: JSONSchema, seenSize: number): JSONSchema | undefined => {
if (seenSize !== 0 && val && typeof val === 'object' && val.$schema) return {};
return undefined;
};
toValidate = _cloneSchema(node, new Map(), stopAtDialectBoundary) as JSONSchema;
}
if (!validator(toValidate)) {
const errs: string[] = [];
for (const err of validator.errors as DefinedError[]) {
errs.push(`${err.instancePath} : ${err.message}`);
}
resolveErrors.push(l10n.t("Schema '{0}' is not valid: {1}", loc, `\n${errs.join('\n')}`));
}
}
/**
* ----------------------------
* Schema resource and fragment resolution
* ----------------------------
* Manages two types of schema identification:
* 1. Embedded resources ($id without fragment):
* Creates a new resource scope that can be referenced by other schemas, e.g. "$id": "other.json"
* 2. Plain-name fragments/anchors:
* Creates named anchors within a resource for direct reference.
*
* Cache per resource URI in resourceIndexByUri:
* - root: schema node for the resource
* - fragments: map of plain-name anchors to their schema nodes + dynamic flag
*/
type FragmentEntry = { node: JSONSchema; dynamic?: boolean };
type PlainNameFragmentMap = Map<string, FragmentEntry>;
type ResourceIndex = { root?: JSONSchema; fragments: PlainNameFragmentMap };
const resourceIndexByUri = new Map<string, ResourceIndex>();
const _getResourceIndex = (resourceUri: string): ResourceIndex => {
let entry = resourceIndexByUri.get(resourceUri);
if (!entry) {
entry = { fragments: new Map<string, FragmentEntry>() };
resourceIndexByUri.set(resourceUri, entry);
}
return entry;
};
/**
* Adds a resource's dynamic anchors to the inherited scope from parent resources
*
* Draft 2020-12: For $dynamicRef resolution, when schema A references schema B,
* B's dynamic anchors are added to A's scope. This builds a chain where $dynamicRef
* looks for the outermost (first) matching anchor.
*/
const _addResourceDynamicAnchors = (
scope: Map<string, JSONSchema[]> | undefined,
resourceUri: string | undefined
): Map<string, JSONSchema[]> | undefined => {
const entry = resourceIndexByUri.get(resourceUri);
if (!entry || entry.fragments.size === 0) return scope;
let result = scope;
for (const [name, entryItem] of entry.fragments) {
if (!entryItem.dynamic) continue;
const current = result?.get(name) ?? [];
if (current.some((existing) => existing._baseUrl === resourceUri)) continue;
// clone map on first modification
if (result === scope) result = scope ? new Map(scope) : new Map<string, JSONSchema[]>();
result.set(name, current.concat(entryItem.node));
}
return result;
};
// resolve relative URI against base URI
// e.g. resolve "./foo.json" against "http://example.com/bar.json" => "http://example.com/foo.json"
const _resolveAgainstBase = (baseUri: string, ref: string): string => {
if (this.contextService) return this.contextService.resolveRelativePath(ref, baseUri);
return this.normalizeId(ref);
};
const _preferLocalBaseForRemoteId = async (currentBase: string, id: string): Promise<string> => {
try {
const currentBaseUri = URI.parse(currentBase);
const idUri = URI.parse(id);
const localFileName = path.posix.basename(idUri.path);
const localDir = path.posix.dirname(currentBaseUri.path);
const localPath = path.posix.join(localDir, localFileName);
const localUriStr = currentBaseUri.with({ path: localPath, query: idUri.query, fragment: idUri.fragment }).toString();
if (localUriStr === currentBase) return localUriStr;
const content = await this.requestService(localUriStr);
return content ? localUriStr : _resolveAgainstBase(currentBase, id);
} catch {
return _resolveAgainstBase(currentBase, id);
}
};
const _indexSchemaResources = async (root: JSONSchema, initialBaseUri: string): Promise<void> => {
type WorkItem = { node: JSONSchema; baseUri: string };
const preOrderStack: WorkItem[] = [{ node: root, baseUri: initialBaseUri }];
const postOrderStack: JSONSchema[] = [];
const childListByNode = new WeakMap<JSONSchema, JSONSchema[]>();
const seen = new Set<JSONSchema>();
while (preOrderStack.length) {
const current = preOrderStack.pop();
if (!current) continue;
const node = current.node;
if (!node || typeof node !== 'object' || seen.has(node)) continue;
seen.add(node);
let baseUri = current.baseUri;
const id = node.$id || node.id;
if (id) {
const preferredBaseUri = await _preferLocalBaseForRemoteId(baseUri, id);
node._baseUrl = preferredBaseUri;
const hashIndex = preferredBaseUri.indexOf('#');
if (hashIndex !== -1 && hashIndex < preferredBaseUri.length - 1) {
// Draft-07 and earlier: $id with fragment defines a plain-name anchor scoped to the resolved base
const frag = preferredBaseUri.slice(hashIndex + 1);
_getResourceIndex(baseUri).fragments.set(frag, { node });
} else {
// $id without fragment creates a new embedded resource scope
baseUri = preferredBaseUri;
const entry = _getResourceIndex(preferredBaseUri);
if (!entry.root) {
entry.root = node;
}
}
}
// Draft 2019-09+: $anchor keyword
if (node.$anchor) {
_getResourceIndex(baseUri).fragments.set(node.$anchor, { node });
}
// Draft 2020-12+: $dynamicAnchor keyword
if (node.$dynamicAnchor) {
node._baseUrl = baseUri;
_getResourceIndex(baseUri).fragments.set(node.$dynamicAnchor, { node, dynamic: true });
}
const children: JSONSchema[] = [];
childListByNode.set(node, children);
// collect all child schemas
this.collectSchemaNodes(
(entry) => {
children.push(entry);
preOrderStack.push({ node: entry, baseUri });
},
node.not,
node.if,
node.then,
node.else,
node.contains,
node.propertyNames,
node.additionalProperties as JSONSchema,
node.items,
node.additionalItems,
node.prefixItems,
this.schemaMapValues(node.properties),
this.schemaMapValues(node.patternProperties),
this.schemaMapValues(node.definitions),
this.schemaMapValues(node.$defs),
this.schemaMapValues(node.dependentSchemas),
this.schemaMapValues(node.dependencies as JSONSchemaMap),
node.allOf,
node.anyOf,
node.oneOf,
node.schemaSequence
);
postOrderStack.push(node);
}
const hasNestedSchema = new WeakMap<JSONSchema, boolean>();
while (postOrderStack.length) {
const node = postOrderStack.pop();
let hasNested = false;
for (const child of childListByNode.get(node)) {
if (child.$schema || hasNestedSchema.get(child)) {
hasNested = true;
break;
}
}
hasNestedSchema.set(node, hasNested);
if (node === root || node.$schema) await _metaValidateSchemaNode(node, hasNested);
}
};
let schema = raw as JSONSchema;
const schemaBaseURL = schemaToResolve.uri ?? schemaURL;
await _indexSchemaResources(schema, schemaBaseURL);
const _findSection = (schemaRoot: JSONSchema, refPath: string, sourceURI: string): JSONSchema => {
if (!refPath) {
return schemaRoot;
}
// JSON pointer style
if (refPath[0] === '/') {
let current = schemaRoot;
const parts = refPath.substr(1).split('/');
for (const part of parts) {
// in JSON Pointer: ~ must be escaped as ~0, / must be escaped as ~1
current = current?.[part.replace(/~1/g, '/').replace(/~0/g, '~')];
if (current === null) return undefined;
}
return current as JSONSchema;
}
// plain-name fragment ($anchor or $id#fragment) -> lookup in collected fragments
return _getResourceIndex(sourceURI).fragments.get(refPath).node;
};
const _merge = (target: JSONSchema, sourceRoot: JSONSchema, sourceURI: string, refPath: string, clone = false): void => {
const section = _findSection(sourceRoot, refPath, sourceURI);
if (typeof section === 'boolean') {
if (!section) target.not = {};
return;
}
if (typeof section === 'object' && section) {
const source = clone ? (_cloneSchema(section, new Map()) as JSONSchema) : section;
for (const key in source) {
if (Object.prototype.hasOwnProperty.call(source, key) && !Object.prototype.hasOwnProperty.call(target, key)) {
target[key] = source[key];
}
}
return;
} else {
resolveErrors.push(l10n.t("$ref '{0}' in '{1}' cannot be resolved.", refPath, sourceURI));
}
};
const _resolveRefUri = (parentSchemaURL: string, refUri: string): string => {
const resolvedAgainstParent = _resolveAgainstBase(parentSchemaURL, refUri);
if (!refUri.startsWith('/')) return resolvedAgainstParent;
const parentResource = resourceIndexByUri.get(parentSchemaURL)?.root;
const parentResourceId = parentResource?.$id || parentResource?.id;
const resolvedParentId = _resolveAgainstBase(parentSchemaURL, parentResourceId);
if (!resolvedParentId.startsWith('http://') && !resolvedParentId.startsWith('https://')) return resolvedAgainstParent;
return _resolveAgainstBase(resolvedParentId, refUri);
};
const _resolveLocalSiblingFromRemoteUri = (parentSchemaURL: string, resolvedRefUri: string): string | undefined => {
try {
const parentUri = URI.parse(parentSchemaURL);
const targetUri = URI.parse(resolvedRefUri);
if (parentUri.scheme !== 'file') return undefined;
if (targetUri.scheme !== 'http' && targetUri.scheme !== 'https') return undefined;
const localFileName = path.posix.basename(targetUri.path);
if (!localFileName) return undefined;
const localDir = path.posix.dirname(parentUri.path);
const localPath = path.posix.join(localDir, localFileName);
return parentUri.with({ path: localPath, query: targetUri.query, fragment: targetUri.fragment }).toString();
} catch {
return undefined;
}
};
const resolveExternalLink = (
node: JSONSchema,
uri: string,
linkPath: string,
parentSchemaURL: string,
parentSchemaDependencies: SchemaDependencies,
resolutionStack: Set<string>,
recursiveAnchorBase: string,
inheritedDynamicScope: Map<string, JSONSchema[]>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): Promise<any> => {
const _attachResolvedSchema = (
node: JSONSchema,
schemaRoot: JSONSchema,
schemaUri: string,
linkPath: string,
parentSchemaDependencies: SchemaDependencies,
resolveRefDependencies: SchemaDependencies,
resolutionStack: Set<string>,
recursiveAnchorBase: string,
inheritedDynamicScope: Map<string, JSONSchema[]>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): Promise<any> => {
parentSchemaDependencies[schemaUri] = true;
_merge(node, schemaRoot, schemaUri, linkPath, !!inheritedDynamicScope || !!recursiveAnchorBase);
if (!recursiveAnchorBase || !node._baseUrl) node._baseUrl = schemaUri;
node.url = schemaUri;
const nextStack = new Set(resolutionStack);
nextStack.add(schemaUri);
// eslint-disable-next-line @typescript-eslint/no-use-before-define
return resolveRefs(
node,
schemaRoot,
schemaUri,
resolveRefDependencies,
nextStack,
recursiveAnchorBase,
inheritedDynamicScope
);
};
const _resolveByUri = (targetUris: string[], index = 0): Promise<unknown> => {
const targetUri = targetUris[index];
const embeddedSchema = resourceIndexByUri.get(targetUri)?.root;
if (embeddedSchema) {
return _attachResolvedSchema(
node,
embeddedSchema,
targetUri,
linkPath,
parentSchemaDependencies,
parentSchemaDependencies,
resolutionStack,
recursiveAnchorBase,
inheritedDynamicScope
);
}
const referencedHandle = this.getOrAddSchemaHandle(targetUri);
return referencedHandle.getUnresolvedSchema().then(async (unresolvedSchema) => {
if (
unresolvedSchema.errors?.some((error) => error.toLowerCase().includes('unable to load schema from')) &&
index + 1 < targetUris.length
) {
return _resolveByUri(targetUris, index + 1);
}
if (unresolvedSchema.errors.length) {
const loc = linkPath ? targetUri + '#' + linkPath : targetUri;
resolveErrors.push(l10n.t("Problems loading reference '{0}': {1}", loc, unresolvedSchema.errors[0]));
}
// index resources for the newly loaded schema
await _indexSchemaResources(unresolvedSchema.schema, targetUri);
return _attachResolvedSchema(
node,
unresolvedSchema.schema,
targetUri,
linkPath,
parentSchemaDependencies,
referencedHandle.dependencies,
resolutionStack,
recursiveAnchorBase,
inheritedDynamicScope
);
});
};
const resolvedUri = _resolveRefUri(parentSchemaURL, uri);
const localSiblingUri = _resolveLocalSiblingFromRemoteUri(parentSchemaURL, resolvedUri);
const targetUris = localSiblingUri && localSiblingUri !== resolvedUri ? [localSiblingUri, resolvedUri] : [resolvedUri];
return _resolveByUri(targetUris);
};
const resolveRefs = async (
node: JSONSchema,
parentSchema: JSONSchema,
parentSchemaURL: string,
parentSchemaDependencies: SchemaDependencies,
resolutionStack: Set<string>,
recursiveAnchorBase?: string,
inheritedDynamicScope?: Map<string, JSONSchema[]>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): Promise<any> => {
if (!node || typeof node !== 'object') {
return null;
}
// track nodes with their base URL for $id resolution
type WalkItem = {
node: JSONSchema;
baseURL?: string;
dialect?: SchemaDialect;
recursiveAnchorBase?: string;
inheritedDynamicScope?: Map<string, JSONSchema[]>;
siblingRefCycleKeys?: Set<string>;
};
const toWalk: WalkItem[] = [{ node, baseURL: parentSchemaURL, recursiveAnchorBase, inheritedDynamicScope }];
const seen = new WeakSet<JSONSchema>(); // prevents re-walking the same schema object graph
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const openPromises: Promise<any>[] = [];
// handle $ref with siblings based on dialect
const _handleRef = (
next: JSONSchema,
nodeBaseURL: string,
nodeDialect: SchemaDialect,
recursiveAnchorBase?: string,
inheritedDynamicScope?: Map<string, JSONSchema[]>,
siblingRefCycleKeys?: Set<string>
): void => {
const currentDynamicScope = _addResourceDynamicAnchors(inheritedDynamicScope, nodeBaseURL);
this.collectSchemaNodes(
(entry) =>
toWalk.push({ node: entry, baseURL: nodeBaseURL, recursiveAnchorBase, inheritedDynamicScope: currentDynamicScope }),
this.schemaMapValues(next.definitions || next.$defs)
);
// checks if a node with $ref has other constraint keywords
const _hasRefSiblings = (node: JSONSchema): boolean => {
for (const k of Object.keys(node)) {
if (REF_SIBLING_NONCONSTRAINT_KEYS.has(k)) continue;
return true;
}
return false;
};
/**
* For Draft-2019+:
* { $ref: "...", <siblings...> }
* becomes
* { allOf: [ { $ref: "..." }, <siblings...> ] }
*/
const _rewriteRefWithSiblingsToAllOf = (node: JSONSchema): void => {
const siblings: JSONSchema = {};
for (const k of Object.keys(node)) {
if (!REF_SIBLING_NONCONSTRAINT_KEYS.has(k)) {
siblings[k] = node[k];
delete node[k];
}
}
const refValue = node.$dynamicRef ?? node.$recursiveRef ?? node.$ref;
if (typeof refValue !== 'string') return;
node.allOf = [
{ [node.$dynamicRef ? '$dynamicRef' : node.$recursiveRef ? '$recursiveRef' : '$ref']: refValue } as JSONSchema,
siblings,
];
delete node.$dynamicRef;
delete node.$recursiveRef;
delete node.$ref;
};
const _stripRefSiblings = (node: JSONSchema): void => {
for (const k of Object.keys(node)) {
if (!REF_SIBLING_NONCONSTRAINT_KEYS.has(k)) delete node[k];
}
};
const seenRefs = new Set<string>();
const _mergeIfResourceAlreadyInResolutionStack = (ref: string, resolvedResource: string, frag: string): boolean => {
if (!resolutionStack.has(resolvedResource)) return false;
if (!seenRefs.has(ref)) {
const source = resourceIndexByUri.get(resolvedResource)?.root;
if (source && typeof source === 'object') {
_merge(next, source, resolvedResource, frag, !!recursiveAnchorBase);
}
seenRefs.add(ref);
}
return true;
};
while (next.$dynamicRef || next.$recursiveRef || next.$ref) {
const isDynamicRef = typeof next.$dynamicRef === 'string';
const isRecursiveRef = !isDynamicRef && typeof next.$recursiveRef === 'string';
const rawRef = next.$dynamicRef ?? next.$recursiveRef ?? next.$ref;
if (typeof rawRef !== 'string') break;
next._$ref = rawRef;
// parse ref into base URI and fragment
const ref = decodeURIComponent(rawRef);
const segments = ref.split('#', 2);
const baseUri = segments[0];
const frag = segments.length > 1 ? segments[1] : '';
const resolvedRefKey = `${baseUri ? _resolveAgainstBase(nodeBaseURL, baseUri) : nodeBaseURL}#${frag}`;
if (_hasRefSiblings(next)) {
// Draft-07 and earlier: ignore siblings
if (nodeDialect === SchemaDialect.draft04 || nodeDialect === SchemaDialect.draft07) {
_stripRefSiblings(next);
} else {
if (siblingRefCycleKeys?.has(resolvedRefKey)) break;
// Draft-2019+: support sibling keywords
_rewriteRefWithSiblingsToAllOf(next);
if (Array.isArray(next.allOf)) {
for (let i = 0; i < next.allOf.length; i++) {
const entry = next.allOf[i];
if (entry && typeof entry === 'object') {
let nextSiblingRefCycleKeys: Set<string> | undefined;
if (i === 0) {
nextSiblingRefCycleKeys = new Set(siblingRefCycleKeys);
nextSiblingRefCycleKeys.add(resolvedRefKey);
}
toWalk.push({
node: entry as JSONSchema,
baseURL: nodeBaseURL,
recursiveAnchorBase,
inheritedDynamicScope: currentDynamicScope,
siblingRefCycleKeys: nextSiblingRefCycleKeys,
});
}
}
}
return;
}
}
delete next.$dynamicRef;
delete next.$recursiveRef;
delete next.$ref;
// Draft-2019+: $recursiveRef
if (isRecursiveRef && (ref === '#' || ref === '')) {
const targetRoot = resourceIndexByUri.get(nodeBaseURL)?.root;
const recursiveBase = targetRoot?.$recursiveAnchor && recursiveAnchorBase ? recursiveAnchorBase : nodeBaseURL;
if (recursiveBase.length > 0) {
if (resolutionStack?.has(recursiveBase) || recursiveBase === nodeBaseURL) {
const sourceRoot = resourceIndexByUri.get(recursiveBase)?.root ?? parentSchema;
if (!seenRefs.has(ref)) {
_merge(next, sourceRoot, recursiveBase, '', false);
seenRefs.add(ref);
}
continue;
}
openPromises.push(
resolveExternalLink(
next,
recursiveBase,
'',
nodeBaseURL,
parentSchemaDependencies,
resolutionStack,
recursiveAnchorBase,
currentDynamicScope
)
);
return;
}
continue;
}
// Draft-2020+: $dynamicRef
else if (isDynamicRef) {
const targetResource = baseUri.length > 0 ? _resolveAgainstBase(nodeBaseURL, baseUri) : nodeBaseURL;
const targetFragments = resourceIndexByUri.get(targetResource)?.fragments;
const targetHasDynamicAnchor = frag.length > 0 && targetFragments?.get(frag)?.dynamic;
const dynamicTarget = targetHasDynamicAnchor ? currentDynamicScope?.get(frag)?.[0] : undefined;
const resolveResource = dynamicTarget ? dynamicTarget._baseUrl : targetResource;
if (dynamicTarget && (resolveResource === nodeBaseURL || resolutionStack.has(resolveResource))) {
if (!seenRefs.has(ref)) {
_merge(next, dynamicTarget, resolveResource, '', false);
seenRefs.add(ref);
}
continue;
}
if (baseUri.length > 0 || targetHasDynamicAnchor) {
if (_mergeIfResourceAlreadyInResolutionStack(ref, resolveResource, frag)) continue;
openPromises.push(
resolveExternalLink(
next,
resolveResource,
frag,
nodeBaseURL,
parentSchemaDependencies,
resolutionStack,
recursiveAnchorBase,
currentDynamicScope
)
);
return;
}
}
// normal $ref with external baseUri
else if (baseUri.length > 0) {
const resolvedBaseUri = _resolveAgainstBase(nodeBaseURL, baseUri);
if (_mergeIfResourceAlreadyInResolutionStack(ref, resolvedBaseUri, frag)) continue;
// resolve relative to this node's base URL
openPromises.push(
resolveExternalLink(
next,
baseUri,
frag,
nodeBaseURL,
parentSchemaDependencies,
resolutionStack,
recursiveAnchorBase,
currentDynamicScope
)
);
return;
}
// local $ref or $dynamicRef
if (!seenRefs.has(ref)) {
_merge(next, parentSchema, nodeBaseURL, frag, isDynamicRef && !!currentDynamicScope);
seenRefs.add(ref);
}
}
// recursively process children
this.collectSchemaNodes(
(entry) =>
toWalk.push({
node: entry,
baseURL: next._baseUrl || nodeBaseURL,
dialect: nodeDialect,
recursiveAnchorBase,
inheritedDynamicScope: currentDynamicScope,
}),
next.not,
next.if,
next.then,
next.else,
next.contains,
next.propertyNames,
next.additionalProperties as JSONSchema,
next.items,
next.additionalItems,
next.prefixItems,
this.schemaMapValues(next.properties),
this.schemaMapValues(next.patternProperties),
this.schemaMapValues(next.dependentSchemas),
this.schemaMapValues(next.dependencies as JSONSchemaMap),
next.allOf,
next.anyOf,
next.oneOf,
next.schemaSequence
);
};
// handle file path with fragments
if (parentSchemaURL.indexOf('#') > 0) {
const segments = parentSchemaURL.split('#', 2);
if (segments[0].length > 0 && segments[1].length > 0) {
const newSchema = {};
await resolveExternalLink(
newSchema,
segments[0],
segments[1],
parentSchemaURL,
parentSchemaDependencies,
resolutionStack,
recursiveAnchorBase,
inheritedDynamicScope
);
for (const key in schema) {
if (key === 'required') {
continue;
}
if (Object.prototype.hasOwnProperty.call(schema, key) && !Object.prototype.hasOwnProperty.call(newSchema, key)) {
newSchema[key] = schema[key];
}
}
schema = newSchema;
}
}
while (toWalk.length) {
const item = toWalk.pop();
const next = item.node;
const nodeBaseURL = next._baseUrl || item.baseURL;
const nodeDialect = next._dialect || item.dialect;
const nodeRecursiveAnchorBase = item.recursiveAnchorBase ?? (next.$recursiveAnchor ? nodeBaseURL : undefined);
if (seen.has(next)) continue;
seen.add(next);
_handleRef(next, nodeBaseURL, nodeDialect, nodeRecursiveAnchorBase, item.inheritedDynamicScope, item.siblingRefCycleKeys);
}
return Promise.all(openPromises);
};
const resolutionStack = new Set<string>(); // prevents $ref/$recursiveRef/$dynamicRef loops across schema URIs
const rootResource = schema._baseUrl || schemaURL;
if (rootResource) resolutionStack.add(rootResource);
await resolveRefs(schema, schema, schemaURL, dependencies, resolutionStack);
return new ResolvedSchema(schema, resolveErrors);
}
public getSchemaForResource(resource: string, doc: JSONDocument): Promise<ResolvedSchema> {
const resolveModelineSchema = (): string | undefined => {
let schemaFromModeline = getSchemaFromModeline(doc);
if (schemaFromModeline !== undefined) {
if (!schemaFromModeline.startsWith('file:') && !schemaFromModeline.startsWith('http')) {
// If path contains a fragment and it is left intact, "#" will be
// considered part of the filename and converted to "%23" by
// path.resolve() -> take it out and add back after path.resolve
let appendix = '';
if (schemaFromModeline.indexOf('#') > 0) {
const segments = schemaFromModeline.split('#', 2);
schemaFromModeline = segments[0];
appendix = segments[1];
}
if (!path.isAbsolute(schemaFromModeline)) {
const resUri = URI.parse(resource);
schemaFromModeline = URI.file(path.resolve(path.parse(resUri.fsPath).dir, schemaFromModeline)).toString();
} else {
schemaFromModeline = URI.file(schemaFromModeline).toString();
}
if (appendix.length > 0) {
schemaFromModeline += '#' + appendix;
}
}
return schemaFromModeline;
}
};
const resolveSchemaForResource = (schemas: string[]): Promise<ResolvedSchema> => {
const schemaHandle = super.createCombinedSchema(resource, schemas);
return schemaHandle.getResolvedSchema().then((schema) => {
return this.finalizeResolvedSchema(schema, schemaHandle.url, doc, false);
});
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const resolveSchema = async (): Promise<any> => {
const seen: { [schemaId: string]: boolean } = Object.create(null);
const schemas: string[] = [];
let k8sAllSchema: ResolvedSchema = undefined;
for (const entry of this.filePatternAssociations) {
if (entry.matchesPattern(resource)) {
for (const schemaId of entry.getURIs()) {
if (!seen[schemaId]) {
if (this.yamlSettings?.kubernetesCRDStoreEnabled && schemaId === KUBERNETES_SCHEMA_URL) {
if (!k8sAllSchema) {
k8sAllSchema = await this.getResolvedSchema(KUBERNETES_SCHEMA_URL);
}
const kubeSchema = autoDetectKubernetesSchema(
doc,
k8sAllSchema,
this.yamlSettings.kubernetesCRDStoreUrl ?? CRD_CATALOG_URL
);
if (kubeSchema) {