### Running YAML Language Server as CLI Source: https://context7.com/redhat-developer/yaml-language-server/llms.txt Provides instructions on how to install and run the YAML Language Server as a command-line interface (CLI) tool using npm. It covers global installation and starting the server with standard input/output communication. ```bash # Install globally npm install -g yaml-language-server # Run with stdio communication yaml-language-server --stdio ``` -------------------------------- ### YAML Language Server Client Integration Example (Node.js) Source: https://context7.com/redhat-developer/yaml-language-server/llms.txt An example demonstrating how to integrate the YAML Language Server as a client in a Node.js application using the VS Code Language Server Protocol library. It shows spawning the server process and establishing an LSP connection. ```typescript import { spawn } from 'child_process'; import { createConnection, StreamMessageReader, StreamMessageWriter } from 'vscode-languageserver/node'; // Spawn the language server process const serverProcess = spawn('yaml-language-server', ['--stdio']); // Create LSP connection const reader = new StreamMessageReader(serverProcess.stdout); const writer = new StreamMessageWriter(serverProcess.stdin); const connection = createConnection(reader, writer); // Initialize the connection connection.listen(); connection.onInitialize((params) => { return { capabilities: { textDocumentSync: 1, // Full sync completionProvider: { resolveProvider: true }, hoverProvider: true, documentSymbolProvider: true, definitionProvider: true, codeActionProvider: true, documentFormattingProvider: true } }; }); // Send requests to the server connection.sendRequest('textDocument/completion', { textDocument: { uri: 'file:///test.yaml' }, position: { line: 0, character: 0 } }).then(completions => { console.log('Completions:', completions); }); ``` -------------------------------- ### Install Node.js Dependencies for YAML Language Server Source: https://github.com/redhat-developer/yaml-language-server/blob/main/README.md This command installs the necessary Node.js dependencies for the YAML language server project. It assumes the project has been cloned and the user is in the project's root directory. The `npm install` command downloads and installs all packages listed in `package.json`. ```bash cd yaml-language-server $ npm install ``` -------------------------------- ### Single Root Schema Association Examples Source: https://github.com/redhat-developer/yaml-language-server/blob/main/README.md Provides examples of associating a single schema with different glob patterns. This is useful for applying a specific schema to all or a subset of YAML files. ```yaml yaml.schemas: { "https://json.schemastore.org/composer": "/*" } ``` ```yaml yaml.schemas: { "kubernetes": "/myYamlFile.yaml" } ``` ```yaml yaml.schemas: { "https://json.schemastore.org/composer": "/*", "kubernetes": "/myYamlFile.yaml" } ``` ```yaml yaml.schemas: { "C:\\Users\\user\\Documents\\custom_schema.json": "someFilePattern.yaml" } ``` ```yaml yaml.schemas: { "/home/user/custom_schema.json": "someFilePattern.yaml" } ``` ```yaml "/home/user/custom_schema.yaml": "someFilePattern.yaml" ``` -------------------------------- ### YAML Language Server Docker Container Usage Source: https://context7.com/redhat-developer/yaml-language-server/llms.txt Examples demonstrating how to pull, run, and use the YAML Language Server within Docker containers. Includes interactive usage, mounting workspace directories, and integration into Dockerfiles. ```bash # Pull the official image docker pull quay.io/redhat-developer/yaml-language-server:latest # Run interactively with stdio docker run -it quay.io/redhat-developer/yaml-language-server:latest # Mount workspace directory for file access docker run -it \ -v /path/to/workspace:/workspace \ quay.io/redhat-developer/yaml-language-server:latest # Use in a Dockerfile FROM quay.io/redhat-developer/yaml-language-server:latest COPY config.yaml /workspace/ CMD ["yaml-language-server", "--stdio"] ``` -------------------------------- ### Run YAML Language Server Locally Source: https://context7.com/redhat-developer/yaml-language-server/llms.txt Instructions to build and run the YAML Language Server locally from source. This involves installing dependencies, building the project, and executing the server with stdio communication. ```bash cd yaml-language-server npm install npm run build node ./out/server/src/server.js --stdio ``` -------------------------------- ### YAML Hover Documentation with Schemas Source: https://context7.com/redhat-developer/yaml-language-server/llms.txt Provides inline documentation and type information when hovering over YAML elements. It utilizes JSON schemas for context and requires the `yaml-language-server` and `vscode-languageserver-textdocument` libraries. Inputs are the document and cursor position, outputting hover details. ```typescript import { getLanguageService } from 'yaml-language-server'; import { TextDocument, Position } from 'vscode-languageserver-textdocument'; const languageService = getLanguageService({ schemaRequestService: async (uri) => { return JSON.stringify({ "type": "object", "properties": { "timeout": { "type": "integer", "description": "Maximum time in seconds to wait for the operation", "default": 30, "minimum": 1, "maximum": 300 } } }); }, workspaceContext: { resolveRelativePath: (rel, res) => rel } }); languageService.configure({ hover: true, schemas: [{ uri: 'http://example.com/config-schema.json', fileMatch: ['config.yaml'] }] }); const document = TextDocument.create( 'file:///config.yaml', 'yaml', 1, 'timeout: 60' ); // Hover over "timeout" (line 0, character 3) const position = Position.create(0, 3); const hover = await languageService.doHover(document, position); if (hover) { console.log('Hover info:', { contents: hover.contents, range: hover.range }); // Expected: // { // contents: { // kind: "markdown", // value: "Maximum time in seconds to wait for the operation\n\nDefault: `30`\n\nConstraints:\n- minimum: 1\n- maximum: 300" // }, // range: { start: { line: 0, character: 0 }, end: { line: 0, character: 7 } } // } } ``` -------------------------------- ### Build YAML Language Server Source: https://github.com/redhat-developer/yaml-language-server/blob/main/README.md This command builds the YAML language server project, compiling the TypeScript code into JavaScript. The output is typically placed in the `./out/server/src` directory, making the server ready for execution. This is a crucial step for developers. ```bash $ npm run build ``` -------------------------------- ### Run Built YAML Language Server via stdio Source: https://github.com/redhat-developer/yaml-language-server/blob/main/README.md This command executes the built YAML language server using Node.js. The `--stdio` flag indicates that the server should communicate over standard input and output, which is common for language server integrations. The path to the server executable needs to be correct. ```bash node (Yaml Language Server Location)/out/server/src/server.js [--stdio] ``` -------------------------------- ### Run YAML Language Server Docker Container Source: https://github.com/redhat-developer/yaml-language-server/blob/main/README.md This command demonstrates how to run the YAML language server as a Docker container. It pulls the latest image from quay.io and runs it in interactive mode. No specific inputs are required, and the output is the server's standard output. ```sh docker run -it quay.io/redhat-developer/yaml-language-server:latest ``` -------------------------------- ### Create and Configure YAML Language Service (TypeScript) Source: https://context7.com/redhat-developer/yaml-language-server/llms.txt Demonstrates how to create an instance of the YAML Language Service using `getLanguageService` and configure its behavior, including validation, completion, and schema associations. It requires dependencies like `schemaRequestService` and `workspaceContext`. ```typescript import { getLanguageService } from 'yaml-language-server'; import { TextDocument } from 'vscode-languageserver-textdocument'; // Create language service with required dependencies const languageService = getLanguageService({ // Schema fetching function schemaRequestService: async (uri: string): Promise => { const response = await fetch(uri); return await response.text(); }, // Workspace path resolution workspaceContext: { resolveRelativePath: (relativePath: string, resource: string) => { const path = require('path'); const resourceDir = path.dirname(resource); return path.resolve(resourceDir, relativePath); } }, // Optional: LSP connection for advanced features connection: undefined, // Optional: telemetry for error tracking telemetry: undefined, // Optional: YAML settings state yamlSettings: undefined, // Optional: client capabilities clientCapabilities: undefined }); // Configure the service languageService.configure({ validate: true, hover: true, completion: true, format: true, schemas: [ { uri: 'https://json.schemastore.org/github-workflow', fileMatch: ['.github/workflows/*.yml', '.github/workflows/*.yaml'] } ], customTags: ['!Ref', '!Sub', '!GetAtt'], yamlVersion: '1.2' }); // Use validation const document = TextDocument.create( 'file:///workspace/.github/workflows/ci.yml', 'yaml', 1, 'name: CI\non: push\njobs:\n build:\n runs-on: ubuntu-latest' ); const diagnostics = await languageService.doValidation(document, false); console.log('Validation errors:', diagnostics); ``` -------------------------------- ### YAML Auto-completion with JSON Schemas Source: https://context7.com/redhat-developer/yaml-language-server/llms.txt Provides context-aware auto-completion suggestions for YAML files based on provided JSON schemas. It requires the `yaml-language-server` and `vscode-languageserver-textdocument` libraries. Inputs include the document content and cursor position, and outputs are completion items. ```typescript import { getLanguageService } from 'yaml-language-server'; import { TextDocument, Position } from 'vscode-languageserver-textdocument'; const languageService = getLanguageService({ schemaRequestService: async (uri) => { return JSON.stringify({ "type": "object", "properties": { "apiVersion": { "type": "string", "enum": ["v1", "v2", "v3"], "description": "API version to use" }, "kind": { "type": "string", "enum": ["Deployment", "Service", "Pod"], "description": "Resource kind" }, "metadata": { "type": "object", "properties": { "name": { "type": "string" }, "namespace": { "type": "string", "default": "default" } } } } }); }, workspaceContext: { resolveRelativePath: (rel, res) => rel } }); languageService.configure({ completion: true, schemas: [{ uri: 'http://example.com/k8s-schema.json', fileMatch: ['*.k8s.yaml'] }] }); // Get completions at cursor position const document = TextDocument.create( 'file:///deployment.k8s.yaml', 'yaml', 1, 'apiVersion: v1\nkind: ' ); // Position after "kind: " (line 1, character 6) const position = Position.create(1, 6); const completions = await languageService.doComplete(document, position, false); console.log('Completions:', completions.items.map(item => ({ label: item.label, kind: item.kind, documentation: item.documentation, insertText: item.insertText }))); // Expected completions: // [ // { label: "Deployment", kind: Value, documentation: "Resource kind", insertText: "Deployment" }, // { label: "Service", kind: Value, documentation: "Resource kind", insertText: "Service" }, // { label: "Pod", kind: Value, documentation: "Resource kind", insertText: "Pod" } // ] ``` -------------------------------- ### Multi-Root Workspace Schema Association Source: https://github.com/redhat-developer/yaml-language-server/blob/main/README.md Demonstrates how to associate schemas in a multi-root workspace environment. Schema paths must be relative to the root of each individual project within the workspace. ```yaml yaml.schemas: { "My_first_project/my_schema.json": "test.yaml", "My_second_project/my_schema2.json": "test2.yaml" } ``` -------------------------------- ### Use Custom YAML Tags in a File Source: https://github.com/redhat-developer/yaml-language-server/blob/main/README.md Demonstrates the usage of custom-defined tags within a YAML file. These tags are applied to specific values, sequences, or mappings, extending YAML's capabilities. ```yaml some_key: !Scalar-example some_value some_sequence: !Seq-example - some_seq_key_1: some_seq_value_1 - some_seq_key_2: some_seq_value_2 some_mapping: !Mapping-example some_mapping_key_1: some_mapping_value_1 some_mapping_key_2: some_mapping_value_2 ``` -------------------------------- ### Multiple Schema Associations with Glob Patterns Source: https://github.com/redhat-developer/yaml-language-server/blob/main/README.md Illustrates associating multiple schemas with different glob patterns, including local and remote schema URLs, relative paths, and platform-specific absolute paths. ```yaml "yaml.schemas": { "http://json.schemastore.org/composer": ["/*"], "file:///home/johnd/some-schema.json": ["some.yaml"], "../relative/path/schema.json": ["/config*.yaml"], "/Users/johnd/some-schema.json": ["some.yaml"] } ``` ```yaml "yaml.schemas": { "kubernetes": ["/myYamlFile.yaml"] } ``` ```yaml "yaml.schemas": { "http://json.schemastore.org/composer": ["/*"], "kubernetes": ["/myYamlFile.yaml"] } ``` -------------------------------- ### Code Actions and Quick Fixes for YAML Language Server Source: https://context7.com/redhat-developer/yaml-language-server/llms.txt Illustrates how to obtain and apply code actions and quick fixes for validation errors detected by the YAML Language Server. It shows fetching diagnostics and then requesting applicable code actions for a given range in a document. ```typescript import { getLanguageService } from 'yaml-language-server'; import { TextDocument, CodeActionParams, Range } from 'vscode-languageserver-textdocument'; const languageService = getLanguageService({ schemaRequestService: async (uri) => '', workspaceContext: { resolveRelativePath: (rel, res) => rel } }); languageService.configure({ validate: true }); const document = TextDocument.create( 'file:///config.yaml', 'yaml', 1, 'key: value\n indented_wrong: test' ); // First get diagnostics const diagnostics = await languageService.doValidation(document, false); // Request code actions for a specific range const params: CodeActionParams = { textDocument: { uri: document.uri }, range: Range.create(1, 0, 1, 20), context: { diagnostics: diagnostics } }; const codeActions = languageService.getCodeAction(document, params); if (codeActions && codeActions.length > 0) { console.log('Available code actions:', codeActions.map(action => ({ title: action.title, kind: action.kind, edit: action.edit }))); // Apply the first code action const firstAction = codeActions[0]; if (firstAction.edit) { console.log('Applying fix:', firstAction.title); // Apply workspace edits to fix the issue } } ``` -------------------------------- ### Dynamic Schema Management - TypeScript Source: https://context7.com/redhat-developer/yaml-language-server/llms.txt Demonstrates runtime schema management including adding new schemas, modifying schema content, and deleting schemas or schema properties. Shows how to dynamically update validation rules for YAML documents without restarting the language service. Includes schema property modifications and bulk schema deletion operations. ```typescript import { getLanguageService } from 'yaml-language-server'; import { TextDocument } from 'vscode-languageserver-textdocument'; const languageService = getLanguageService({ schemaRequestService: async (uri) => { // This won't be called for dynamically added schemas return '{}'; }, workspaceContext: { resolveRelativePath: (rel, res) => rel } }); // Add a new schema dynamically languageService.addSchema('http://example.com/my-schema', { type: 'object', properties: { name: { type: 'string' }, version: { type: 'number' } }, required: ['name'] }); languageService.configure({ validate: true, schemas: [{ uri: 'http://example.com/my-schema', fileMatch: ['myconfig.yaml'] }] }); // Modify schema by adding properties languageService.modifySchemaContent({ schema: 'http://example.com/my-schema', action: 0, // MODIFICATION_ACTIONS.add path: 'properties', key: 'description', content: { type: 'string', maxLength: 200 } }); // Delete schema property languageService.deleteSchemaContent({ schema: 'http://example.com/my-schema', action: 0, // MODIFICATION_ACTIONS.delete path: 'properties', key: 'version' }); const document = TextDocument.create( 'file:///myconfig.yaml', 'yaml', 1, 'name: test\ndescription: A test configuration' ); const diagnostics = await languageService.doValidation(document, false); console.log('Validation with dynamic schema:', diagnostics); // Delete entire schema languageService.deleteSchema('http://example.com/my-schema'); // Or delete multiple schemas at once languageService.deleteSchemasWhole({ schemas: [ 'http://example.com/schema1', 'http://example.com/schema2' ], action: 2 // MODIFICATION_ACTIONS.deleteAll }); ``` -------------------------------- ### Associate Schemas via Modeline in TypeScript Source: https://context7.com/redhat-developer/yaml-language-server/llms.txt Associates YAML schemas using modeline comments for validation and hover support. Relies on yaml-language-server and vscode-languageserver-textdocument. Inputs include YAML documents with modeline comments specifying schema URIs, outputs are validation diagnostics. Supports both absolute URLs and relative paths, but requires the schema to be fetchable via schemaRequestService. ```typescript import { getLanguageService } from 'yaml-language-server'; import { TextDocument } from 'vscode-languageserver-textdocument'; const languageService = getLanguageService({ schemaRequestService: async (uri) => { if (uri === 'https://json.schemastore.org/github-workflow') { return JSON.stringify({ "type": "object", "properties": { "name": { "type": "string" }, "on": { "type": ["string", "array", "object"] } } }); } throw new Error('Schema not found'); }, workspaceContext: { resolveRelativePath: (rel, res) => rel } }); languageService.configure({ validate: true, hover: true, completion: true }); // Schema specified via modeline comment const document = TextDocument.create( 'file:///workflow.yaml', 'yaml', 1, `# yaml-language-server: $schema=https://json.schemastore.org/github-workflow name: CI Pipeline on: [push, pull_request] jobs: test: runs-on: ubuntu-latest` ); const diagnostics = await languageService.doValidation(document, false); console.log('Validation with modeline schema:', diagnostics); // Also works with relative paths const relativeSchemaDoc = TextDocument.create( 'file:///project/config.yaml', 'yaml', 1, `# yaml-language-server: $schema=../schemas/config-schema.json database: host: localhost port: 5432` ); ``` -------------------------------- ### Use Custom Schema Provider in TypeScript Source: https://context7.com/redhat-developer/yaml-language-server/llms.txt Dynamically resolves YAML schemas based on document URI using a custom provider. Uses yaml-language-server and vscode-languageserver-textdocument. Inputs are document URIs and YAML content; outputs are validation diagnostics against matched schemas. Supports multiple schemas per document but relies on the custom logic for URI matching. ```typescript import { getLanguageService, CustomSchemaProvider } from 'yaml-language-server'; import { TextDocument } from 'vscode-languageserver-textdocument'; const languageService = getLanguageService({ schemaRequestService: async (uri) => { // Fetch schema content const schemas = { 'http://example.com/dev-schema.json': { type: 'object', properties: { environment: { type: 'string', enum: ['development', 'staging'] } } }, 'http://example.com/prod-schema.json': { type: 'object', properties: { environment: { type: 'string', enum: ['production'] } } } }; return JSON.stringify(schemas[uri] || {}); }, workspaceContext: { resolveRelativePath: (rel, res) => rel } }); // Register custom schema provider const customProvider: CustomSchemaProvider = async (uri: string) => { // Return schema URI based on file path if (uri.includes('/environments/dev/')) { return 'http://example.com/dev-schema.json'; } else if (uri.includes('/environments/prod/')) { return 'http://example.com/prod-schema.json'; } // Can return array for multiple schemas return ['http://example.com/base-schema.json']; }; languageService.registerCustomSchemaProvider(customProvider); languageService.configure({ validate: true }); // Development file uses dev schema const devDoc = TextDocument.create( 'file:///project/environments/dev/config.yaml', 'yaml', 1, 'environment: development' ); const devDiagnostics = await languageService.doValidation(devDoc, false); console.log('Dev validation:', devDiagnostics); // Should pass // Production file uses prod schema const prodDoc = TextDocument.create( 'file:///project/environments/prod/config.yaml', 'yaml', 1, 'environment: production' ); const prodDiagnostics = await languageService.doValidation(prodDoc, false); console.log('Prod validation:', prodDiagnostics); // Should pass ``` -------------------------------- ### YAML Document Formatting with Prettier Source: https://context7.com/redhat-developer/yaml-language-server/llms.txt Formats YAML documents according to specified Prettier options. This feature requires the `yaml-language-server` and `vscode-languageserver-textdocument` libraries. It takes an unformatted document and returns text edits for formatting. ```typescript import { getLanguageService } from 'yaml-language-server'; import { TextDocument } from 'vscode-languageserver-textdocument'; const languageService = getLanguageService({ schemaRequestService: async (uri) => '', workspaceContext: { resolveRelativePath: (rel, res) => rel } }); languageService.configure({ format: true }); const unformattedDoc = TextDocument.create( 'file:///config.yaml', 'yaml', 1, `name: my-project version: 1.0.0 config: enabled: true items: [1,2,3] nested: deeply: { value: 123 }` ); // Format with custom options const edits = await languageService.doFormat(unformattedDoc, { singleQuote: false, bracketSpacing: true, proseWrap: 'preserve', printWidth: 80 }); // Apply edits to get formatted text let formatted = unformattedDoc.getText(); for (const edit of edits.reverse()) { const start = unformattedDoc.offsetAt(edit.range.start); const end = unformattedDoc.offsetAt(edit.range.end); formatted = formatted.substring(0, start) + edit.newText + formatted.substring(end); } console.log('Formatted YAML:\n', formatted); // Expected output: // name: my-project // version: 1.0.0 // config: // enabled: true // items: [1, 2, 3] // nested: // deeply: { value: 123 } ``` -------------------------------- ### Configure Custom YAML Tags Source: https://github.com/redhat-developer/yaml-language-server/blob/main/README.md Defines how to specify custom tags for YAML files within the editor's settings. This allows for custom scalar, sequence, and mapping types to be recognized and used in YAML documents. ```yaml "yaml.customTags": [ "!Scalar-example scalar", "!Seq-example sequence", "!Mapping-example mapping" ] ``` -------------------------------- ### Inlined Schema Definition using Modeline Source: https://github.com/redhat-developer/yaml-language-server/blob/main/README.md Shows how to specify a YAML schema directly within a YAML file using a modeline comment. Supports URLs, relative paths, and absolute paths for the schema. ```yaml # yaml-language-server: $schema= ``` ```yaml # yaml-language-server: $schema=../relative/path/to/schema ``` ```yaml # yaml-language-server: $schema=/absolute/path/to/schema ``` -------------------------------- ### Folding Ranges for YAML Language Server Source: https://context7.com/redhat-developer/yaml-language-server/llms.txt Shows how to use the YAML Language Server to generate folding range information for a YAML document. This allows editors to provide collapsible regions for code blocks, improving readability. ```typescript import { getLanguageService } from 'yaml-language-server'; import { TextDocument } from 'vscode-languageserver-textdocument'; const languageService = getLanguageService({ schemaRequestService: async (uri) => '', workspaceContext: { resolveRelativePath: (rel, res) => rel } }); const document = TextDocument.create( 'file:///config.yaml', 'yaml', 1, `# Application Configuration app: name: MyApp version: 1.0.0 features: - authentication - logging - metrics database: host: localhost port: 5432 credentials: username: admin password: secret cache: enabled: true ttl: 3600` ); const foldingRanges = languageService.getFoldingRanges(document, { rangeLimit: 5000 }); console.log('Folding ranges:', foldingRanges?.map(range => ({ startLine: range.startLine, endLine: range.endLine, kind: range.kind }))); // Expected output shows collapsible regions for: // - app (lines 1-7) // - features (lines 4-6) // - database (lines 8-12) // - credentials (lines 11-12) // - cache (lines 13-14) ``` -------------------------------- ### Custom YAML Tags Configuration - TypeScript Source: https://context7.com/redhat-developer/yaml-language-server/llms.txt Configures the YAML language service with custom tags for CloudFormation and Ansible support. Defines scalar, sequence, and mapping tag types while enabling validation and completion. Demonstrates CloudFormation template validation with custom tags like !Ref, !Sub, and !GetAtt. ```typescript import { getLanguageService } from 'yaml-language-server'; import { TextDocument } from 'vscode-languageserver-textdocument'; const languageService = getLanguageService({ schemaRequestService: async (uri) => { return JSON.stringify({ type: 'object', properties: { Resources: { type: 'object' } } }); }, workspaceContext: { resolveRelativePath: (rel, res) => rel } }); languageService.configure({ validate: true, completion: true, // Define custom tags with their types customTags: [ '!Ref scalar', // CloudFormation reference '!Sub scalar', // CloudFormation substitute '!GetAtt scalar', // CloudFormation get attribute '!Join sequence', // CloudFormation join '!ImportValue scalar', // CloudFormation import '!Select sequence', // CloudFormation select '!vault scalar', // Ansible vault '!include scalar', // Custom include tag '!merge mapping' // Custom merge tag ], schemas: [{ uri: 'http://example.com/cloudformation-schema.json', fileMatch: ['*.cf.yaml', '*.cloudformation.yaml'] }] }); const cloudFormationDoc = TextDocument.create( 'file:///template.cf.yaml', 'yaml', 1, `AWSTemplateFormatVersion: '2010-09-09' Resources: MyBucket: Type: AWS::S3::Bucket Properties: BucketName: !Sub 'my-bucket-\${AWS::Region}' MyQueue: Type: AWS::SQS::Queue Properties: QueueName: !Ref MyBucket Tags: - Key: Name Value: !Join ['-', [!Ref MyBucket, 'queue']]` ); const diagnostics = await languageService.doValidation(cloudFormationDoc, false); console.log('CloudFormation validation:', diagnostics); // Custom tags are recognized and won't cause parse errors ``` -------------------------------- ### Associate Schema with Multiple Glob Patterns Source: https://github.com/redhat-developer/yaml-language-server/blob/main/README.md Shows how to associate a single schema with multiple glob patterns using a JSON array. This allows for more flexible schema application across different file sets. ```yaml yaml.schemas: { "kubernetes": ["filePattern1.yaml", "filePattern2.yaml"] } ``` -------------------------------- ### TypeScript Interface for JSON Schema Description (Extended) Source: https://github.com/redhat-developer/yaml-language-server/blob/main/README.md Defines the extended interface for JSON schema descriptions, including URI, name, description, and flags indicating if the schema is used for the current file and if it originates from a schema store. This is used for LSP communication. ```typescript interface JSONSchemaDescriptionExt { /** * Schema URI */ uri: string; /** * Schema name, from schema store */ name?: string; /** * Schema description, from schema store */ description?: string; /** * Is schema used for current document */ usedForCurrentFile: boolean; /** * Is schema from schema store */ fromStore: boolean; } ``` -------------------------------- ### Associate Schema with Glob Pattern Source: https://github.com/redhat-developer/yaml-language-server/blob/main/README.md Associates a specified JSON schema (local or online) with YAML files matching a given glob pattern. Schema paths should be relative to the project root. ```yaml yaml.schemas: { "https://json.schemastore.org/composer": "/myYamlFile.yaml" } ``` -------------------------------- ### Reference Nested Schema Definition Source: https://github.com/redhat-developer/yaml-language-server/blob/main/README.md Explains how to reference a nested schema definition within a larger schema using a URL fragment. This is useful for component files that don't have standalone schemas. ```yaml yaml.schemas: { "https://json.schemastore.org/circleciconfig#/definitions/jobs/additionalProperties": "/src/jobs/*.yaml" } ``` -------------------------------- ### TypeScript Interface for JSON Schema Description Source: https://github.com/redhat-developer/yaml-language-server/blob/main/README.md Defines the interface for JSON schema descriptions, including URI, name, and description. This interface is used in responses from the language server when requesting schemas associated with a document. ```typescript interface JSONSchemaDescriptionExt { /** * Schema URI */ uri: string; /** * Schema name, from schema store */ name?: string; /** * Schema description, from schema store */ description?: string; } ``` -------------------------------- ### Kubernetes Validation Mode for YAML Language Server Source: https://context7.com/redhat-developer/yaml-language-server/llms.txt Demonstrates how to configure and use the YAML Language Server for specialized validation of Kubernetes resources. It shows setting up a custom schema request service to provide Kubernetes API definitions and performing validation and completion on a Kubernetes YAML document. ```typescript import { getLanguageService } from 'yaml-language-server'; import { TextDocument } from 'vscode-languageserver-textdocument'; const languageService = getLanguageService({ schemaRequestService: async (uri) => { if (uri === 'kubernetes') { // Return Kubernetes schema return JSON.stringify({ oneOf: [ { $ref: '#/definitions/io.k8s.api.apps.v1.Deployment' }, { $ref: '#/definitions/io.k8s.api.core.v1.Service' } ], definitions: { 'io.k8s.api.apps.v1.Deployment': { type: 'object', properties: { apiVersion: { type: 'string', enum: ['apps/v1'] }, kind: { type: 'string', enum: ['Deployment'] } } }, 'io.k8s.api.core.v1.Service': { type: 'object', properties: { apiVersion: { type: 'string', enum: ['v1'] }, kind: { type: 'string', enum: ['Service'] } } } } }); } return '{}'; }, workspaceContext: { resolveRelativePath: (rel, res) => rel } }); languageService.configure({ validate: true, completion: true, hover: true, isKubernetes: true, schemas: [{ uri: 'kubernetes', fileMatch: ['*.k8s.yaml', 'k8s/*.yaml'] }] }); const k8sDocument = TextDocument.create( 'file:///deployment.k8s.yaml', 'yaml', 1, `apiVersion: apps/v1 kind: Deployment metadata: name: nginx-deployment spec: replicas: 3 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:1.14.2 ports: - containerPort: 80` ); // Validate with Kubernetes mode enabled const diagnostics = await languageService.doValidation(k8sDocument, true); console.log('Kubernetes validation:', diagnostics); // Get Kubernetes-aware completions const position = { line: 1, character: 6 }; // After "kind: " const completions = await languageService.doComplete(k8sDocument, position, true); console.log('K8s completions:', completions.items.map(i => i.label)); ``` -------------------------------- ### Extract Document Symbols in TypeScript Source: https://context7.com/redhat-developer/yaml-language-server/llms.txt This code extracts flat and hierarchical document outlines from a YAML file for navigation purposes using the yaml-language-server. It depends on yaml-language-server and vscode-languageserver-textdocument libraries. Takes a YAML document as input and outputs arrays of symbols with names, kinds, and locations. Limited to YAML format and requires a TextDocument instance. ```typescript import { getLanguageService } from 'yaml-language-server'; import { TextDocument } from 'vscode-languageserver-textdocument'; const languageService = getLanguageService({ schemaRequestService: async (uri) => '', workspaceContext: { resolveRelativePath: (rel, res) => rel } }); const document = TextDocument.create( 'file:///docker-compose.yaml', 'yaml', 1, `version: '3.8' services: web: image: nginx:latest ports: - "80:80" database: image: postgres:13 environment: POSTGRES_PASSWORD: secret networks: frontend: backend:` ); // Get flat symbol list const symbols = languageService.findDocumentSymbols(document); console.log('Flat symbols:', symbols.map(s => ({ name: s.name, kind: s.kind, location: { line: s.location.range.start.line } }))); // Get hierarchical symbols const hierarchicalSymbols = languageService.findDocumentSymbols2(document); console.log('Hierarchical symbols:', JSON.stringify(hierarchicalSymbols, null, 2)); // Expected: Nested structure with version, services (web, database), networks ``` -------------------------------- ### Validate YAML Documents Against JSON Schemas (TypeScript) Source: https://context7.com/redhat-developer/yaml-language-server/llms.txt Shows how to perform validation on YAML documents using the `doValidation` method of the YAML Language Service. It requires a `schemaRequestService` that can provide the schema content and configures the service with specific schemas and file matching patterns. ```typescript import { getLanguageService } from 'yaml-language-server'; import { TextDocument } from 'vscode-languageserver-textdocument'; const languageService = getLanguageService({ schemaRequestService: async (uri) => { const schema = { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "name": { "type": "string" }, "version": { "type": "string", "pattern": "^\\d+\\.\\d+\\.\\d+$" }, "dependencies": { "type": "object", "additionalProperties": { "type": "string" } } }, "required": ["name", "version"] }; return JSON.stringify(schema); }, workspaceContext: { resolveRelativePath: (rel, res) => rel } }); languageService.configure({ validate: true, schemas: [{ uri: 'http://example.com/package-schema.json', fileMatch: ['package.yaml'] }] }); // Valid YAML const validDoc = TextDocument.create( 'file:///package.yaml', 'yaml', 1, 'name: my-package\nversion: 1.0.0\ndependencies:\n lodash: "^4.17.21"' ); const validDiagnostics = await languageService.doValidation(validDoc, false); // Expected: [] (no errors) // Invalid YAML - missing required field const invalidDoc = TextDocument.create( 'file:///package.yaml', 'yaml', 1, 'name: my-package' ); const invalidDiagnostics = await languageService.doValidation(invalidDoc, false); // Expected: [{ message: "Missing property 'version'", severity: Error, ... }] console.log('Validation results:', invalidDiagnostics.map(d => ({ message: d.message, line: d.range.start.line, severity: d.severity }))); ```