"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Red Hat. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
const sinon = __importStar(require("sinon"));
const chai = __importStar(require("chai"));
const sinon_chai_1 = __importDefault(require("sinon-chai"));
const path = __importStar(require("path"));
const url = __importStar(require("url"));
const SchemaService = __importStar(require("../src/languageservice/services/yamlSchemaService"));
const yamlParser07_1 = require("../src/languageservice/parser/yamlParser07");
const yamlSettings_1 = require("../src/yamlSettings");
const schemaUrls_1 = require("../src/languageservice/utils/schemaUrls");
const BASE_KUBERNETES_SCHEMA_URL = `https://raw.githubusercontent.com/yannh/kubernetes-json-schema/master/${schemaUrls_1.DEFAULT_KUBERNETES_SCHEMA_VERSION}-standalone-strict/`;
const KUBERNETES_SCHEMA_URL = BASE_KUBERNETES_SCHEMA_URL + 'all.json';
const expect = chai.expect;
chai.use(sinon_chai_1.default);
const workspaceContext = {
    resolveRelativePath: (relativePath, resource) => {
        return url.resolve(resource, relativePath);
    },
};
describe('YAML Schema Service', () => {
    const sandbox = sinon.createSandbox();
    afterEach(() => {
        sandbox.restore();
    });
    describe('Schema for resource', () => {
        let requestServiceMock;
        beforeEach(() => {
            requestServiceMock = sandbox.fake.resolves(undefined);
        });
        it('should handle inline schema http url', () => {
            const documentContent = `# yaml-language-server: $schema=http://json-schema.org/draft-07/schema# anothermodeline=value\n`;
            const content = `${documentContent}\n---\n- `;
            const yamlDock = (0, yamlParser07_1.parse)(content);
            const service = new SchemaService.YAMLSchemaService(requestServiceMock);
            service.getSchemaForResource('', yamlDock.documents[0]);
            expect(requestServiceMock).calledOnceWith('http://json-schema.org/draft-07/schema#');
        });
        it('should handle inline schema https url', () => {
            const documentContent = `# yaml-language-server: $schema=https://json-schema.org/draft-07/schema# anothermodeline=value\n`;
            const content = `${documentContent}\n---\n- `;
            const yamlDock = (0, yamlParser07_1.parse)(content);
            const service = new SchemaService.YAMLSchemaService(requestServiceMock);
            service.getSchemaForResource('', yamlDock.documents[0]);
            expect(requestServiceMock).calledOnceWith('https://json-schema.org/draft-07/schema#');
        });
        it('should handle url with fragments', async () => {
            const content = `# yaml-language-server: $schema=https://json-schema.org/draft-07/schema#/definitions/schemaArray\nfoo: bar`;
            const yamlDock = (0, yamlParser07_1.parse)(content);
            requestServiceMock = sandbox.fake.resolves(`{"definitions": {"schemaArray": {
        "type": "array",
        "minItems": 1,
        "items": { "$ref": "#" }
    }}, "properties": {}}`);
            const service = new SchemaService.YAMLSchemaService(requestServiceMock);
            const schema = await service.getSchemaForResource('', yamlDock.documents[0]);
            expect(requestServiceMock).calledTwice;
            expect(requestServiceMock).calledWithExactly('https://json-schema.org/draft-07/schema');
            expect(requestServiceMock).calledWithExactly('https://json-schema.org/draft-07/schema#/definitions/schemaArray');
            expect(schema.schema.type).eqls('array');
        });
        it('should handle url with fragments when root object is schema', async () => {
            const content = `# yaml-language-server: $schema=https://json-schema.org/draft-07/schema#/definitions/schemaArray`;
            const yamlDock = (0, yamlParser07_1.parse)(content);
            requestServiceMock = sandbox.fake.resolves(`{"definitions": {"schemaArray": {
        "type": "array",
        "minItems": 1,
        "items": { "$ref": "#" }
    },
    "bar": {
      "type": "string"
    }
  }, "properties": {"foo": {"type": "boolean"}}, "required": ["foo"]}`);
            const service = new SchemaService.YAMLSchemaService(requestServiceMock);
            const schema = await service.getSchemaForResource('', yamlDock.documents[0]);
            expect(requestServiceMock).calledTwice;
            expect(requestServiceMock).calledWithExactly('https://json-schema.org/draft-07/schema');
            expect(requestServiceMock).calledWithExactly('https://json-schema.org/draft-07/schema#/definitions/schemaArray');
            expect(schema.schema.type).eqls('array');
            expect(schema.schema.required).is.undefined;
            expect(schema.schema.definitions.bar.type).eqls('string');
        });
        it('should handle file path with fragments', async () => {
            const content = `# yaml-language-server: $schema=schema.json#/definitions/schemaArray\nfoo: bar`;
            const yamlDock = (0, yamlParser07_1.parse)(content);
            requestServiceMock = sandbox.fake.resolves(`{"definitions": {"schemaArray": {
        "type": "array",
        "minItems": 1,
        "items": { "$ref": "#" }
    }}, "properties": {}}`);
            const service = new SchemaService.YAMLSchemaService(requestServiceMock);
            const schema = await service.getSchemaForResource('', yamlDock.documents[0]);
            expect(requestServiceMock).calledTwice;
            if (process.platform === 'win32') {
                const driveLetter = path.parse(__dirname).root.split(':')[0].toLowerCase();
                expect(requestServiceMock).calledWithExactly(`file:///${driveLetter}:/schema.json`);
                expect(requestServiceMock).calledWithExactly(`file:///${driveLetter}%3A/schema.json#/definitions/schemaArray`);
            }
            else {
                expect(requestServiceMock).calledWithExactly('file:///schema.json');
                expect(requestServiceMock).calledWithExactly('file:///schema.json#/definitions/schemaArray');
            }
            expect(schema.schema.type).eqls('array');
        });
        it('should use local sibling schema path before remote $id ref', async () => {
            const content = `# yaml-language-server: $schema=file:///schemas/primary.json\nmode: stage`;
            const yamlDock = (0, yamlParser07_1.parse)(content);
            const primarySchema = {
                $id: 'https://example.com/schemas/primary.json',
                type: 'object',
                properties: {
                    mode: { $ref: 'secondary.json' },
                },
                required: ['mode'],
            };
            const secondarySchema = {
                $id: 'https://example.com/schemas/secondary.json',
                type: 'string',
                enum: ['dev', 'prod'],
            };
            requestServiceMock = sandbox.fake((uri) => {
                if (uri === 'file:///schemas/primary.json') {
                    return Promise.resolve(JSON.stringify(primarySchema));
                }
                if (uri === 'file:///schemas/secondary.json') {
                    return Promise.resolve(JSON.stringify(secondarySchema));
                }
                return Promise.reject(`Resource ${uri} not found.`);
            });
            const service = new SchemaService.YAMLSchemaService(requestServiceMock, workspaceContext);
            await service.getSchemaForResource('', yamlDock.documents[0]);
            const requestedUris = requestServiceMock.getCalls().map((call) => call.args[0]);
            expect(requestedUris).to.include('file:///schemas/primary.json');
            expect(requestedUris).to.include('file:///schemas/secondary.json');
            expect(requestedUris).to.not.include('https://example.com/schemas/secondary.json');
        });
        it('should resolve relative local sibling refs when the root $id basename differs from the local filename', async () => {
            const content = `# yaml-language-server: $schema=file:///schemas/repro_main_schema.json\n` +
                `members:\n` +
                `  - name: Alice\n` +
                `    age: 30`;
            const yamlDock = (0, yamlParser07_1.parse)(content);
            const primarySchema = {
                $id: 'https://example.com/schemas/repro-main-v1',
                type: 'object',
                properties: {
                    members: {
                        type: 'array',
                        items: {
                            $ref: './repro_defs.json#/$defs/Person',
                        },
                    },
                },
                required: ['members'],
            };
            const defsSchema = {
                $id: 'https://example.com/schemas/repro-defs-v1',
                $defs: {
                    Person: {
                        type: 'object',
                        properties: {
                            name: { type: 'string' },
                            age: { type: 'integer' },
                        },
                        required: ['name'],
                    },
                },
            };
            requestServiceMock = sandbox.fake((uri) => {
                if (uri === 'file:///schemas/repro_main_schema.json') {
                    return Promise.resolve(JSON.stringify(primarySchema));
                }
                if (uri === 'file:///schemas/repro_defs.json') {
                    return Promise.resolve(JSON.stringify(defsSchema));
                }
                return Promise.reject(`Resource ${uri} not found.`);
            });
            const service = new SchemaService.YAMLSchemaService(requestServiceMock, workspaceContext);
            const schema = await service.getSchemaForResource('', yamlDock.documents[0]);
            const requestedUris = requestServiceMock.getCalls().map((call) => call.args[0]);
            expect(requestedUris).to.include('file:///schemas/repro_main_schema.json');
            expect(requestedUris).to.include('file:///schemas/repro_defs.json');
            expect(requestedUris).to.not.include('https://example.com/schemas/repro_defs.json');
            expect(schema.errors).to.eql([]);
            expect(schema.schema.properties.members.items).to.deep.include({
                type: 'object',
                url: 'file:///schemas/repro_defs.json',
            });
        });
        it('should resolve nested local sibling refs relative to the loaded sibling schema file', async () => {
            const content = `# yaml-language-server: $schema=file:///schemas/primary.json\nitem: ok`;
            const yamlDock = (0, yamlParser07_1.parse)(content);
            const primarySchema = {
                $schema: 'https://json-schema.org/draft/2020-12/schema',
                $id: 'https://example.com/schemas/primary-v1',
                $ref: './secondary.json',
            };
            const secondarySchema = {
                $schema: 'https://json-schema.org/draft/2020-12/schema',
                $id: 'https://example.com/schemas/secondary-v1',
                type: 'object',
                properties: {
                    item: {
                        $ref: './third.json',
                    },
                },
                required: ['item'],
            };
            const thirdSchema = {
                $schema: 'https://json-schema.org/draft/2020-12/schema',
                $id: 'https://example.com/schemas/third-v1',
                type: 'string',
                enum: ['ok'],
            };
            requestServiceMock = sandbox.fake((uri) => {
                if (uri === 'file:///schemas/primary.json') {
                    return Promise.resolve(JSON.stringify(primarySchema));
                }
                if (uri === 'file:///schemas/secondary.json') {
                    return Promise.resolve(JSON.stringify(secondarySchema));
                }
                if (uri === 'file:///schemas/third.json') {
                    return Promise.resolve(JSON.stringify(thirdSchema));
                }
                return Promise.reject(`Resource ${uri} not found.`);
            });
            const service = new SchemaService.YAMLSchemaService(requestServiceMock, workspaceContext);
            const schema = await service.getSchemaForResource('', yamlDock.documents[0]);
            const requestedUris = requestServiceMock.getCalls().map((call) => call.args[0]);
            expect(requestedUris).to.include('file:///schemas/primary.json');
            expect(requestedUris).to.include('file:///schemas/secondary.json');
            expect(requestedUris).to.include('file:///schemas/third.json');
            expect(requestedUris).to.not.include('https://example.com/schemas/secondary.json');
            expect(requestedUris).to.not.include('https://example.com/schemas/third.json');
            expect(schema.errors).to.eql([]);
            expect(schema.schema.properties.item).to.deep.include({
                type: 'string',
                url: 'file:///schemas/third.json',
            });
        });
        it('should resolve absolute $ref via remote base and mapped local sibling path', async () => {
            const content = `# yaml-language-server: $schema=file:///dir/primary.json\nname: John\nage: -1`;
            const yamlDock = (0, yamlParser07_1.parse)(content);
            const primarySchema = {
                $id: 'https://example.com/schemas/primary.json',
                $ref: '/schemas/secondary.json',
            };
            const secondarySchema = {
                $id: 'https://example.com/schemas/secondary.json',
                type: 'object',
                properties: {
                    name: { type: 'string' },
                    age: { type: 'integer', minimum: 0 },
                },
                required: ['name', 'age'],
            };
            requestServiceMock = sandbox.fake((uri) => {
                if (uri === 'file:///dir/primary.json') {
                    return Promise.resolve(JSON.stringify(primarySchema));
                }
                if (uri === 'file:///dir/secondary.json') {
                    return Promise.resolve(JSON.stringify(secondarySchema));
                }
                return Promise.reject(`Resource ${uri} not found.`);
            });
            const service = new SchemaService.YAMLSchemaService(requestServiceMock, workspaceContext);
            await service.getSchemaForResource('', yamlDock.documents[0]);
            const requestedUris = requestServiceMock.getCalls().map((call) => call.args[0]);
            expect(requestedUris).to.include('file:///dir/primary.json');
            expect(requestedUris).to.include('file:///dir/secondary.json');
            expect(requestedUris).to.not.include('file:///schemas/secondary.json');
            expect(requestedUris).to.not.include('https://example.com/schemas/secondary.json');
        });
        it('should fallback to remote $id target for absolute $ref when mapped local target is missing', async () => {
            const content = `# yaml-language-server: $schema=file:///dir/primary.json\nname: John\nage: -1`;
            const yamlDock = (0, yamlParser07_1.parse)(content);
            const primarySchema = {
                $id: 'https://example.com/schemas/primary.json',
                $ref: '/schemas/secondary.json',
            };
            const secondarySchema = {
                $id: 'https://example.com/schemas/secondary.json',
                type: 'object',
                properties: {
                    name: { type: 'string' },
                    age: { type: 'integer', minimum: 0 },
                },
                required: ['name', 'age'],
            };
            requestServiceMock = sandbox.fake((uri) => {
                if (uri === 'file:///dir/primary.json') {
                    return Promise.resolve(JSON.stringify(primarySchema));
                }
                if (uri === 'https://example.com/schemas/secondary.json') {
                    return Promise.resolve(JSON.stringify(secondarySchema));
                }
                return Promise.reject(`Resource ${uri} not found.`);
            });
            const service = new SchemaService.YAMLSchemaService(requestServiceMock, workspaceContext);
            await service.getSchemaForResource('', yamlDock.documents[0]);
            const requestedUris = requestServiceMock.getCalls().map((call) => call.args[0]);
            expect(requestedUris).to.include('file:///dir/primary.json');
            expect(requestedUris).to.include('file:///dir/secondary.json');
            expect(requestedUris).to.include('https://example.com/schemas/secondary.json');
            expect(requestedUris).to.not.include('file:///schemas/secondary.json');
            expect(requestedUris.indexOf('file:///dir/secondary.json')).to.be.lessThan(requestedUris.indexOf('https://example.com/schemas/secondary.json'));
        });
        it('should reload local schema after local file change when resolving via local sibling path instead of remote $id', async () => {
            const content = `# yaml-language-server: $schema=file:///schemas/primary.json\nmode: stage`;
            const yamlDock = (0, yamlParser07_1.parse)(content);
            const primarySchema = {
                $id: 'https://example.com/schemas/primary.json',
                type: 'object',
                properties: {
                    mode: { $ref: 'secondary.json' },
                },
                required: ['mode'],
            };
            let secondarySchema = {
                $id: 'https://example.com/schemas/secondary.json',
                type: 'string',
                enum: ['dev', 'prod'],
            };
            requestServiceMock = sandbox.fake((uri) => {
                if (uri === 'file:///schemas/primary.json') {
                    return Promise.resolve(JSON.stringify(primarySchema));
                }
                if (uri === 'file:///schemas/secondary.json') {
                    return Promise.resolve(JSON.stringify(secondarySchema));
                }
                return Promise.reject(`Resource ${uri} not found.`);
            });
            const service = new SchemaService.YAMLSchemaService(requestServiceMock, workspaceContext);
            await service.getSchemaForResource('', yamlDock.documents[0]);
            const requestedSecondaryUrisAfterFirstLoad = requestServiceMock
                .getCalls()
                .map((call) => call.args[0])
                .filter((uri) => uri === 'file:///schemas/secondary.json');
            expect(requestedSecondaryUrisAfterFirstLoad).to.have.length(1);
            secondarySchema = { ...secondarySchema, enum: ['dev', 'prod', 'stage'] };
            service.onResourceChange('file:///schemas/secondary.json');
            await service.getSchemaForResource('', yamlDock.documents[0]);
            const requestedSecondaryUrisAfterChange = requestServiceMock
                .getCalls()
                .map((call) => call.args[0])
                .filter((uri) => uri === 'file:///schemas/secondary.json');
            expect(requestedSecondaryUrisAfterChange).to.have.length(2);
        });
        it('should not probe local sibling paths when schema is loaded from https://', async () => {
            const content = `# yaml-language-server: $schema=https://example.com/schemas/openapi-extensions.json\nopenapi: '3.1.0'\ninfo:\n  title: Test\n  version: '1.0'`;
            const yamlDock = (0, yamlParser07_1.parse)(content);
            const extensionsSchema = {
                $id: 'https://example.com/schemas/openapi-extensions.json',
                $schema: 'http://json-schema.org/draft-04/schema#',
                allOf: [{ $ref: './openapi.v3.1.json' }],
            };
            const openapiSchema = {
                $id: 'https://github.com/OAI/OpenAPI-Specification/blob/main/schemas/v3.1/schema.json',
                $schema: 'https://json-schema.org/draft/2020-12/schema',
                type: 'object',
                properties: {
                    openapi: { type: 'string', pattern: '^3\\.1\\.\\d+(-.+)?$' },
                    info: {
                        type: 'object',
                        properties: { title: { type: 'string' }, version: { type: 'string' } },
                        required: ['title', 'version'],
                    },
                },
                required: ['openapi', 'info'],
            };
            requestServiceMock = sandbox.fake((uri) => {
                if (uri === 'https://example.com/schemas/openapi-extensions.json') {
                    return Promise.resolve(JSON.stringify(extensionsSchema));
                }
                if (uri === 'https://example.com/schemas/openapi.v3.1.json') {
                    return Promise.resolve(JSON.stringify(openapiSchema));
                }
                return Promise.reject(`Resource ${uri} not found.`);
            });
            const service = new SchemaService.YAMLSchemaService(requestServiceMock, workspaceContext);
            await service.getSchemaForResource('', yamlDock.documents[0]);
            const requestedUris = requestServiceMock.getCalls().map((call) => call.args[0]);
            expect(requestedUris).to.include('https://example.com/schemas/openapi-extensions.json');
            expect(requestedUris).to.include('https://example.com/schemas/openapi.v3.1.json');
            // _preferLocalBaseForRemoteId should NOT probe for the $id basename as a local sibling
            // when the parent schema was loaded from https:// (not file://)
            expect(requestedUris).to.not.include('https://example.com/schemas/schema.json');
        });
        it('should resolve and expose multiple local file schemas with absolute local paths', async () => {
            const content = `foo: bar`;
            const yamlDock = (0, yamlParser07_1.parse)(content);
            const schemaOneUri = 'file:///Users/test/schemas/schema1.json';
            const schemaTwoUri = 'file:///Users/test/schemas/schema2.json';
            requestServiceMock = sandbox.fake((uri) => {
                if (uri === schemaOneUri) {
                    return Promise.resolve(JSON.stringify({ title: 'Schema 1', type: 'object' }));
                }
                if (uri === schemaTwoUri) {
                    return Promise.resolve(JSON.stringify({ title: 'Schema 2', type: 'object' }));
                }
                return Promise.reject(`Resource ${uri} not found.`);
            });
            const service = new SchemaService.YAMLSchemaService(requestServiceMock, workspaceContext);
            service.registerExternalSchema(schemaOneUri, ['test.yaml']);
            service.registerExternalSchema(schemaTwoUri, ['test.yaml']);
            const schema = await service.getSchemaForResource('test.yaml', yamlDock.documents[0]);
            const requestedUris = requestServiceMock.getCalls().map((call) => call.args[0]);
            expect(requestedUris).to.include(schemaOneUri);
            expect(requestedUris).to.include(schemaTwoUri);
            expect(requestedUris.some((uri) => uri.startsWith('schemaservice:///'))).to.be.false;
            expect(schema.errors).to.eql([]);
            expect(schema.schema.url).to.equal('schemaservice://combinedSchema/test.yaml');
            expect(schema.schema.allOf.map((item) => item.url)).to.have.members([schemaOneUri, schemaTwoUri]);
            const schemaUris = Array.from((0, schemaUrls_1.getSchemaUrls)(schema.schema).keys());
            expect(schemaUris).to.have.members([schemaOneUri, schemaTwoUri]);
            expect(schemaUris.some((uri) => uri.startsWith('schemaservice:///'))).to.be.false;
        });
        it('should ignore modeline schema comment in the middle of file after yaml content', async () => {
            const documentContent = `foo:\n  bar\n# yaml-language-server: $schema=https://json-schema.org/draft-07/schema#\naa:bbb\n`;
            const content = `${documentContent}`;
            const yamlDock = (0, yamlParser07_1.parse)(content);
            const service = new SchemaService.YAMLSchemaService(requestServiceMock);
            await service.getSchemaForResource('', yamlDock.documents[0]);
            expect(requestServiceMock).not.called;
        });
        it('should ignore modeline schema comment using $schema in the middle of file after yaml content', async () => {
            const documentContent = `foo:\n  bar\n# $schema=https://json-schema.org/draft-07/schema#\naa:bbb\n`;
            const content = `${documentContent}`;
            const yamlDock = (0, yamlParser07_1.parse)(content);
            const service = new SchemaService.YAMLSchemaService(requestServiceMock);
            await service.getSchemaForResource('', yamlDock.documents[0]);
            expect(requestServiceMock).not.called;
        });
        it('should handle modeline schema comment in multiline comments at document header', async () => {
            const documentContent = `#first comment\n# second comment\n\n# yaml-language-server: $schema=https://json-schema.org/draft-07/schema#\naa:bbb\n`;
            const content = `${documentContent}`;
            const yamlDock = (0, yamlParser07_1.parse)(content);
            const service = new SchemaService.YAMLSchemaService(requestServiceMock);
            await service.getSchemaForResource('', yamlDock.documents[0]);
            expect(requestServiceMock).calledOnceWith('https://json-schema.org/draft-07/schema#');
        });
        it('should ignore modeline schema comment in multiline comments after yaml content', async () => {
            const documentContent = `foo:\n  bar\n#first comment\n# yaml-language-server: $schema=https://json-schema.org/draft-07/schema#\naa:bbb\n`;
            const content = `${documentContent}`;
            const yamlDock = (0, yamlParser07_1.parse)(content);
            const service = new SchemaService.YAMLSchemaService(requestServiceMock);
            await service.getSchemaForResource('', yamlDock.documents[0]);
            expect(requestServiceMock).not.called;
        });
        it('should handle modeline schema comment after document separator', () => {
            const documentContent = `foo:\n  bar\n---\n# yaml-language-server: $schema=https://json-schema.org/draft-07/schema#\naa:bbb\n`;
            const yamlDock = (0, yamlParser07_1.parse)(documentContent);
            const service = new SchemaService.YAMLSchemaService(requestServiceMock);
            service.getSchemaForResource('', yamlDock.documents[1]);
            expect(requestServiceMock).calledOnceWith('https://json-schema.org/draft-07/schema#');
        });
        it('should handle crd catalog for crd', async () => {
            const documentContent = 'apiVersion: argoproj.io/v1alpha1\nkind: Application';
            const content = `${documentContent}`;
            const yamlDock = (0, yamlParser07_1.parse)(content);
            const settings = new yamlSettings_1.SettingsState();
            settings.schemaAssociations = {
                kubernetes: ['*.yaml'],
            };
            settings.kubernetesCRDStoreEnabled = true;
            requestServiceMock = sandbox.fake.resolves(`
        {
          "oneOf": [ {
              "$ref": "_definitions.json#/definitions/io.k8s.api.admissionregistration.v1.MutatingWebhook"
            }
          ]
        }
        `);
            const service = new SchemaService.YAMLSchemaService(requestServiceMock, undefined, undefined, settings);
            service.registerExternalSchema(KUBERNETES_SCHEMA_URL, ['*.yaml']);
            const resolvedeSchema = await service.getSchemaForResource('test.yaml', yamlDock.documents[0]);
            expect(resolvedeSchema.schema.url).eqls('https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/argoproj.io/application_v1alpha1.json');
            expect(requestServiceMock).calledWithExactly(KUBERNETES_SCHEMA_URL);
            expect(requestServiceMock).calledWithExactly('file:///_definitions.json');
            expect(requestServiceMock).calledWithExactly('https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/argoproj.io/application_v1alpha1.json');
            expect(requestServiceMock).calledThrice;
        });
        it('should handle nonstandard location for OpenShift crd', async () => {
            const documentContent = `apiVersion: route.openshift.io/v1
kind: Route
spec:
  to:
    kind: Service
    name: MyFirstService
    weight: 100`;
            const content = `${documentContent}`;
            const yamlDock = (0, yamlParser07_1.parse)(content);
            const settings = new yamlSettings_1.SettingsState();
            settings.schemaAssociations = {
                kubernetes: ['*.yaml'],
            };
            settings.kubernetesCRDStoreEnabled = true;
            requestServiceMock = sandbox.fake.resolves(`
        {
          "oneOf": [ {
              "$ref": "_definitions.json#/definitions/io.k8s.api.admissionregistration.v1.MutatingWebhook"
            }
          ]
        }
        `);
            const service = new SchemaService.YAMLSchemaService(requestServiceMock, undefined, undefined, settings);
            service.registerExternalSchema(KUBERNETES_SCHEMA_URL, ['*.yaml']);
            const resolvedeSchema = await service.getSchemaForResource('test.yaml', yamlDock.documents[0]);
            expect(resolvedeSchema.schema.url).eqls('https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/openshift/v4.15-strict/route_route.openshift.io_v1.json');
            expect(requestServiceMock).calledWithExactly(KUBERNETES_SCHEMA_URL);
            expect(requestServiceMock).calledWithExactly('file:///_definitions.json');
            expect(requestServiceMock).calledWithExactly('https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/openshift/v4.15-strict/route_route.openshift.io_v1.json');
            expect(requestServiceMock).calledThrice;
        });
        it('should not get schema from crd catalog if definition in kubernetes schema', async () => {
            const documentContent = 'apiVersion: admissionregistration.k8s.io/v1\nkind: MutatingWebhook';
            const content = `${documentContent}`;
            const yamlDock = (0, yamlParser07_1.parse)(content);
            const settings = new yamlSettings_1.SettingsState();
            settings.schemaAssociations = {
                kubernetes: ['*.yaml'],
            };
            settings.kubernetesCRDStoreEnabled = true;
            requestServiceMock = sandbox.fake.resolves(`
        {
          "oneOf": [ {
              "$ref": "_definitions.json#/definitions/io.k8s.api.admissionregistration.v1.MutatingWebhook"
            }
          ]
        }
        `);
            const service = new SchemaService.YAMLSchemaService(requestServiceMock, undefined, undefined, settings);
            service.registerExternalSchema(KUBERNETES_SCHEMA_URL, ['*.yaml']);
            const resolvedSchema = await service.getSchemaForResource('test.yaml', yamlDock.documents[0]);
            expect(resolvedSchema.schema.url).eqls(BASE_KUBERNETES_SCHEMA_URL + '_definitions.json#/definitions/io.k8s.api.admissionregistration.v1.MutatingWebhook');
            expect(requestServiceMock).calledWithExactly(KUBERNETES_SCHEMA_URL);
            expect(requestServiceMock).calledWithExactly('file:///_definitions.json');
            expect(requestServiceMock).calledWithExactly(BASE_KUBERNETES_SCHEMA_URL + '_definitions.json#/definitions/io.k8s.api.admissionregistration.v1.MutatingWebhook');
            expect(requestServiceMock).calledWithExactly(BASE_KUBERNETES_SCHEMA_URL + '_definitions.json');
            expect(requestServiceMock.callCount).equals(4);
        });
        it('should not get schema from crd catalog if definition in kubernetes schema (multiple oneOf)', async () => {
            const documentContent = 'apiVersion: apps/v1\nkind: Deployment';
            const content = `${documentContent}`;
            const yamlDock = (0, yamlParser07_1.parse)(content);
            const settings = new yamlSettings_1.SettingsState();
            settings.schemaAssociations = {
                kubernetes: ['*.yaml'],
            };
            settings.kubernetesCRDStoreEnabled = true;
            requestServiceMock = sandbox.fake.resolves(`
        {
          "oneOf": [
            {
              "$ref": "_definitions.json#/definitions/io.k8s.api.apps.v1.Deployment"
            },
            {
              "$ref": "_definitions.json#/definitions/io.k8s.api.apps.v1.DeploymentCondition"
            }
          ]
        }
        `);
            const service = new SchemaService.YAMLSchemaService(requestServiceMock, undefined, undefined, settings);
            service.registerExternalSchema(KUBERNETES_SCHEMA_URL, ['*.yaml']);
            const resolvedSchema = await service.getSchemaForResource('test.yaml', yamlDock.documents[0]);
            expect(resolvedSchema.schema.url).eqls(BASE_KUBERNETES_SCHEMA_URL + '_definitions.json#/definitions/io.k8s.api.apps.v1.Deployment');
            expect(requestServiceMock).calledWithExactly(KUBERNETES_SCHEMA_URL);
            expect(requestServiceMock).calledWithExactly('file:///_definitions.json');
            expect(requestServiceMock).calledWithExactly(BASE_KUBERNETES_SCHEMA_URL + '_definitions.json#/definitions/io.k8s.api.apps.v1.Deployment');
            expect(requestServiceMock).calledWithExactly(BASE_KUBERNETES_SCHEMA_URL + '_definitions.json');
            expect(requestServiceMock.callCount).equals(4);
        });
        it('should not get schema from crd catalog for RBAC-related resources', async () => {
            const documentContent = 'apiVersion: rbac.authorization.k8s.io/v1\nkind: RoleBinding';
            const content = `${documentContent}`;
            const yamlDock = (0, yamlParser07_1.parse)(content);
            const settings = new yamlSettings_1.SettingsState();
            settings.schemaAssociations = {
                kubernetes: ['*.yaml'],
            };
            settings.kubernetesCRDStoreEnabled = true;
            requestServiceMock = sandbox.fake.resolves(`
        {
          "oneOf": [
            {
              "$ref": "_definitions.json#/definitions/io.k8s.api.rbac.v1.RoleBinding"
            }
          ]
        }
        `);
            const service = new SchemaService.YAMLSchemaService(requestServiceMock, undefined, undefined, settings);
            service.registerExternalSchema(KUBERNETES_SCHEMA_URL, ['*.yaml']);
            const resolvedSchema = await service.getSchemaForResource('test.yaml', yamlDock.documents[0]);
            expect(resolvedSchema.schema.url).eqls(BASE_KUBERNETES_SCHEMA_URL + '_definitions.json#/definitions/io.k8s.api.rbac.v1.RoleBinding');
            expect(requestServiceMock).calledWithExactly(KUBERNETES_SCHEMA_URL);
            expect(requestServiceMock).calledWithExactly('file:///_definitions.json');
            expect(requestServiceMock).calledWithExactly(BASE_KUBERNETES_SCHEMA_URL + '_definitions.json#/definitions/io.k8s.api.rbac.v1.RoleBinding');
            expect(requestServiceMock).calledWithExactly(BASE_KUBERNETES_SCHEMA_URL + '_definitions.json');
            expect(requestServiceMock.callCount).equals(4);
        });
        it('should use GVK to get correct schema', async () => {
            const documentContent = `
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: foo
spec:
  foo: bar
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: foo
  minReplicas: 2
  maxReplicas: 3
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 80`;
            const content = `${documentContent}`;
            const yamlDock = (0, yamlParser07_1.parse)(content);
            const settings = new yamlSettings_1.SettingsState();
            settings.schemaAssociations = {
                kubernetes: ['*.yaml'],
            };
            settings.kubernetesCRDStoreEnabled = true;
            requestServiceMock = sandbox.fake((uri) => {
                if (uri === KUBERNETES_SCHEMA_URL) {
                    return Promise.resolve(`
{
  "oneOf": [
    {
      "$ref": "_definitions.json#/definitions/io.k8s.api.autoscaling.v1.HorizontalPodAutoscaler"
    },
    {
      "$ref": "_definitions.json#/definitions/io.k8s.api.autoscaling.v2.HorizontalPodAutoscaler"
    }
  ]
}
`);
                }
                else {
                    return Promise.resolve(`
{
  "io.k8s.api.autoscaling.v1.HorizontalPodAutoscaler": {
    "description": "configuration of a horizontal pod autoscaler.",
    "properties": {
      "apiVersion": {
        "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources",
        "type": "string"
      },
      "kind": {
        "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds",
        "type": "string",
        "enum": [
          "HorizontalPodAutoscaler"
        ]
      },
      "metadata": {
        "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta",
        "description": "Standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata"
      },
      "spec": {
        "$ref": "#/definitions/io.k8s.api.autoscaling.v1.HorizontalPodAutoscalerSpec",
        "description": "spec defines the behaviour of autoscaler. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status."
      },
      "status": {
        "$ref": "#/definitions/io.k8s.api.autoscaling.v1.HorizontalPodAutoscalerStatus",
        "description": "status is the current information about the autoscaler."
      }
    },
    "type": "object",
    "x-kubernetes-group-version-kind": [
      {
        "group": "autoscaling",
        "kind": "HorizontalPodAutoscaler",
        "version": "v1"
      }
    ]
  },
  "io.k8s.api.autoscaling.v2.HorizontalPodAutoscaler": {
    "description": "HorizontalPodAutoscaler is the configuration for a horizontal pod autoscaler, which automatically manages the replica count of any resource implementing the scale subresource based on the metrics specified.",
    "properties": {
      "apiVersion": {
        "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources",
        "type": "string"
      },
      "kind": {
        "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds",
        "type": "string",
        "enum": [
          "HorizontalPodAutoscaler"
        ]
      },
      "metadata": {
        "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta",
        "description": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata"
      },
      "spec": {
        "$ref": "#/definitions/io.k8s.api.autoscaling.v2.HorizontalPodAutoscalerSpec",
        "description": "spec is the specification for the behaviour of the autoscaler. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status."
      },
      "status": {
        "$ref": "#/definitions/io.k8s.api.autoscaling.v2.HorizontalPodAutoscalerStatus",
        "description": "status is the current information about the autoscaler."
      }
    },
    "type": "object",
    "x-kubernetes-group-version-kind": [
      {
        "group": "autoscaling",
        "kind": "HorizontalPodAutoscaler",
        "version": "v2"
      }
    ]
  }
}`);
                }
            });
            const service = new SchemaService.YAMLSchemaService(requestServiceMock, undefined, undefined, settings);
            service.registerExternalSchema(KUBERNETES_SCHEMA_URL, ['*.yaml']);
            const resolvedSchema = await service.getSchemaForResource('test.yaml', yamlDock.documents[0]);
            expect(resolvedSchema.schema.url).eqls(BASE_KUBERNETES_SCHEMA_URL + '_definitions.json#/definitions/io.k8s.api.autoscaling.v2.HorizontalPodAutoscaler');
        });
        it('should support extglob !(config) pattern', () => {
            const service = new SchemaService.YAMLSchemaService(requestServiceMock);
            const issueFormSchema = {
                $schema: 'http://json-schema.org/draft-07/schema#',
                type: 'object',
                properties: {
                    name: { type: 'string' },
                    description: { type: 'string' },
                },
                required: ['name'],
            };
            service.registerExternalSchema('https://json.schemastore.org/github-issue-forms.json', ['**/.github/ISSUE_TEMPLATE/!(config).yml', '**/.github/ISSUE_TEMPLATE/!(config).yaml'], issueFormSchema);
            const bugReportUris = service.getSchemaURIsForResource('.github/ISSUE_TEMPLATE/bug_report.yml');
            expect(bugReportUris).to.include('https://json.schemastore.org/github-issue-forms.json');
            const featureUris = service.getSchemaURIsForResource('.github/ISSUE_TEMPLATE/feature_request.yaml');
            expect(featureUris).to.include('https://json.schemastore.org/github-issue-forms.json');
            const customUris = service.getSchemaURIsForResource('project/.github/ISSUE_TEMPLATE/custom.yml');
            expect(customUris).to.include('https://json.schemastore.org/github-issue-forms.json');
            const configYmlUris = service.getSchemaURIsForResource('.github/ISSUE_TEMPLATE/config.yml');
            expect(configYmlUris).to.not.include('https://json.schemastore.org/github-issue-forms.json');
            const configYamlUris = service.getSchemaURIsForResource('.github/ISSUE_TEMPLATE/config.yaml');
            expect(configYamlUris).to.not.include('https://json.schemastore.org/github-issue-forms.json');
            const nestedConfigUris = service.getSchemaURIsForResource('nested/repo/.github/ISSUE_TEMPLATE/config.yml');
            expect(nestedConfigUris).to.not.include('https://json.schemastore.org/github-issue-forms.json');
        });
    });
});
//# sourceMappingURL=yamlSchemaService.test.js.map