### Basic Local Setup Configuration Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/configuration.md Configure the host URL for a basic local Home Assistant setup. The access token should be set via the 'Manage Authentication' command. ```json { "vscode-home-assistant.hostUrl": "http://homeassistant.local:8123" // Token set via "Manage Authentication" command } ``` -------------------------------- ### Debug Output Example Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/auth-middleware.md Provides an example of the debug log output from the Home Assistant Auth channel. This output includes details about the middleware's installation, configuration requests, and the injection of tokens and URLs. ```log [2026-05-29 14:30:45] Installing auth middleware on connection [2026-05-29 14:30:45] Sending request type: ConfigurationRequest.type [2026-05-29 14:30:45] Sending initial configuration with token and URL [2026-05-29 14:30:45] Sending initial configuration with token (length: 255, first 5 chars: eyJha...) and URL (http://homeassistant.local:8123) [2026-05-29 14:30:45] Initial configuration with token and URL sent [2026-05-29 14:30:47] Sending follow-up configuration to ensure token and URL are set [2026-05-29 14:30:47] Follow-up configuration with token and URL sent ``` -------------------------------- ### Instantiate CommandMappings Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/extension.md Examples of instantiating the CommandMappings class for different Home Assistant service calls. ```typescript const scriptReloadCommand = new CommandMappings( "vscode-home-assistant.scriptReload", "script", "reload" ); const gitPullRestart = new CommandMappings( "vscode-home-assistant.hassioAddonRestartGitPull", "hassio", "addon_restart", { addon: "core_git_pull" } ); ``` -------------------------------- ### Include Directory Example Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/errors.md Demonstrates how to use `!include_dir_list` in `configuration.yaml`. Ensure the specified directory exists for the 'Go to Definition' feature to work correctly. ```yaml automation: - !include_dir_list automations/ # If automations/ directory doesn't exist, definition won't work ``` -------------------------------- ### Source Code Reference Example Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/README.md Illustrates how source code locations are referenced within the documentation for easy navigation to the implementation. ```plaintext Source: `src/extension.ts` Source: `src/auth/manager.ts:15` Source: `src/language-service/src/haLanguageService.ts:117` ``` -------------------------------- ### Install Auth Middleware Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/auth-middleware.md Installs the auth middleware on a language client connection. This is the primary method for setting up credential injection. ```typescript static async install( context: vscode.ExtensionContext, connection: MessageConnection ): Promise ``` ```typescript await AuthMiddleware.install(context, connection); console.log("Middleware installed - credentials will be injected"); ``` -------------------------------- ### AuthMiddleware.install Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/auth-middleware.md Installs the auth middleware on a language client connection. This method intercepts configuration requests and notifications to inject credentials. ```APIDOC ## AuthMiddleware.install ### Description Installs the auth middleware on a language client connection. This method intercepts configuration requests and notifications to inject credentials. ### Method `static async install(context: vscode.ExtensionContext, connection: MessageConnection): Promise` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Request Example ```typescript await AuthMiddleware.install(context, connection); console.log("Middleware installed - credentials will be injected"); ``` ### Response #### Success Response * None (void) #### Response Example * None ``` -------------------------------- ### Navigation Flow Example Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/INDEX.md Explains the steps involved when a user navigates to the definition of an `!include_dir_list` statement in a Home Assistant configuration file using VS Code. ```text 1. VS Code sends `textDocument/definition` LSP request 2. Server receives request in haLanguageService.getDefinition() 3. Loops through definitionProviders 4. IncludeDefinitionProvider.onDefinition() called 5. Parses line for !include directives and paths 6. Looks up path in IncludeReferences map 7. Returns Definition with file URI and range 8. Server sends definition back to VS Code 9. VS Code opens file at specified location 10. File appears at line specified in Definition ``` -------------------------------- ### Get Device Completions Example Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/ha-connection.md Retrieves completion items for all device IDs. The results contain device ID, kind, documentation (name, manufacturer, model), and sortText. ```typescript public async getDeviceCompletions(): Promise ``` ```typescript const deviceCompletions = await connection.getDeviceCompletions(); // Results: [ // { label: "a1b2c3d4e5f6", documentation: "Living Room Light (Philips Hue)", ... }, // ... // ] ``` -------------------------------- ### TypeScript Type Information Example Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/README.md Demonstrates how TypeScript type information is presented in the documentation, ensuring precise understanding of function signatures. ```typescript // From documentation: async getToken(context: vscode.ExtensionContext): Promise // You know the exact types expected ``` -------------------------------- ### Get Entity Completions Example Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/ha-connection.md Retrieves completion items for all entity IDs in Home Assistant. The results include entity ID, kind, documentation, and sortText. ```typescript public async getEntityCompletions(): Promise ``` ```typescript const completions = await connection.getEntityCompletions(); // Results: [ // { label: "light.living_room", kind: Variable, ... }, // { label: "switch.garage", kind: Variable, ... }, // ... // ] ``` -------------------------------- ### Quick Pick Format Example Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/commands.md Illustrates the format for displaying available reload commands in a quick pick interface. This is typically shown after a user initiates a reload action. ```plaintext > scriptReload (script.reload) automationReload (automation.reload) groupReload (group.reload) ... ``` -------------------------------- ### Extension Imports Server Code Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/PROJECT_STRUCTURE.md Example of how the main extension file imports the compiled server module. ```typescript // In extension.ts const serverModule = path.join( context.extensionPath, "out", "server", "server.js" // Points to compiled server/server.ts ); ``` -------------------------------- ### Example Command Execution Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/commands.md Illustrates a user command execution for script reloading and the corresponding request sent to the Home Assistant server. It shows the domain and service details. ```typescript // User runs command: vscode-home-assistant.scriptReload // Extension sends to server: // { // domain: "script", // service: "reload" // } // Server calls Home Assistant: POST /api/services/script/reload ``` -------------------------------- ### Validation Flow Example Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/INDEX.md Details the process when a user opens a Home Assistant configuration file with an invalid automation, triggering validation in VS Code. ```text 1. VS Code opens file, sends `textDocument/didOpen` notification 2. Server receives notification in onDocumentOpen() 3. Calls getDiagnostics(document) 4. Calls yamlLanguageService.doValidation(document) 5. YAML server validates against applied schemas 6. Returns array of Diagnostic objects 7. getDiagnostics() filters out errors on !secret and !input 8. Sends diagnostics via sendDiagnostics() 9. VS Code receives diagnostics 10. VS Code shows squiggly lines and error count 11. User hovers over error to see message 12. Server sends hover information 13. VS Code shows error description from schema ``` -------------------------------- ### Completion Flow Example Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/INDEX.md Illustrates the sequence of events when a user requests code completion for an entity ID in Home Assistant configurations within VS Code. ```text 1. VS Code detects completion request at cursor 2. Sends `textDocument/completion` LSP request to server 3. Server receives request in haLanguageService.getCompletions() 4. Checks if cursor is on entity_id property 5. Calls EntityIdCompletionContribution.collectValueCompletions() 6. Calls haConnection.getEntityCompletions() 7. haConnection retrieves entities from Home Assistant WebSocket 8. Returns array of CompletionItem objects 9. Server sends completion list back to VS Code 10. VS Code shows dropdown with entity IDs 11. User selects "light.living_room" 12. VS Code inserts selected text ``` -------------------------------- ### Send Initial Configuration Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/auth-middleware.md Sends the initial configuration with credentials immediately after middleware installation. It attempts to retrieve credentials from SecretStorage, environment variables, and legacy settings. ```typescript private async sendInitialConfiguration(connection: MessageConnection): Promise ``` -------------------------------- ### Token Obscuring Example Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/auth-middleware.md Demonstrates how the authentication middleware logs tokens by obscuring them. Full tokens are never logged; instead, they are truncated to 'first5...last5' if longer than 10 characters. ```log Injecting token (length: 255, first 5 chars: eyJha...) into configuration ``` -------------------------------- ### Get Code Completions Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/language-service.md Generates completion suggestions for a given position in a document. Use this to provide intelligent code hints to the user. ```typescript public getCompletions = async ( document: TextDocument, position: Position ): Promise ``` ```typescript const completions = await languageService.getCompletions(document, position); console.log(`Found ${completions.items.length} suggestions`) ``` -------------------------------- ### Get Definition Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/language-service.md Provides 'Go to Definition' functionality for includes, scripts, and secrets. Use this to navigate to the source of a symbol. ```typescript public getDefinition = async ( document: TextDocument, position: Position ): Promise ``` ```typescript const definitions = await languageService.getDefinition(document, position); if (definitions.length > 0) { console.log(`Go to: ${definitions[0].uri}:${definitions[0].range.start.line}`); } ``` -------------------------------- ### Get Floor Completions Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/ha-connection.md Retrieves completion items for all floors, including floor ID, kind, documentation (floor name), and sortText. ```typescript public async getFloorCompletions(): Promise ``` -------------------------------- ### Remote Setup with Self-Signed Certificate Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/configuration.md Configure the host URL and disable certificate validation for a remote Home Assistant instance with a self-signed certificate. The access token is managed separately. ```json { "vscode-home-assistant.hostUrl": "https://my-ha.duckdns.org", "vscode-home-assistant.ignoreCertificates": true // Token set via "Manage Authentication" command } ``` -------------------------------- ### Get Label Completions Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/ha-connection.md Retrieves completion items for all labels, including label ID, kind, documentation (label name and description), and sortText. ```typescript public async getLabelCompletions(): Promise ``` -------------------------------- ### Custom Service Data for Hassio Addon Restart Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/commands.md Provides an example of configuring custom service data for a specific command, `hassioAddonRestartGitPull`. This data is essential for correctly calling the Home Assistant service. ```typescript { domain: "hassio", service: "addon_restart", serviceData: { addon: "core_git_pull" } } ``` -------------------------------- ### Get Token with UI Prompt Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/auth-manager.md Retrieves the Home Assistant access token, falling back to UI prompts if necessary. It handles migration and validation of the URL. ```typescript const token = await AuthManager.getTokenWithUI(context); if (token) { // Use token for API calls } ``` -------------------------------- ### Get Authentication Token Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/README.md Retrieves an authentication token using the AuthManager. Ensure the context is properly initialized. ```typescript const token = await AuthManager.getToken(context); ``` -------------------------------- ### Instantiate HomeAssistantStatusBar Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/status-bar.md Create an instance of the HomeAssistantStatusBar and add it to the extension's subscriptions. This should be done during extension activation. ```typescript const statusBar = new HomeAssistantStatusBar(context); context.subscriptions.push(statusBar); ``` -------------------------------- ### onConnectionEstablished Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/ha-connection.md Callback fired when a connection to Home Assistant is successfully established. Provides instance name and version. ```APIDOC ## onConnectionEstablished ### Description Callback fired when connection to Home Assistant is successfully established. ### Parameters | Property | Type | Description | |----------|------|-------------| | name | `string \| undefined` | Home Assistant instance name | | version | `string \| undefined` | Home Assistant version | ### Example ```typescript haConnection.onConnectionEstablished = (info) => { console.log(`Connected to ${info.name} (v${info.version})`); }; ``` ``` -------------------------------- ### Extension Flow Diagram Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/auth-middleware.md Illustrates the integration of the authentication middleware within the extension's overall flow, from activation and credential migration to server initialization and handling of configuration changes. ```text Extension Activation ↓ AuthManager.migrateTokenFromSettings() AuthManager.migrateUrlFromSettings() ↓ LanguageClient created ↓ AuthMiddleware.install(context, connection) ↓ Sends initial configuration ↓ Server initializes with credentials ↓ User edits configuration ↓ VS Code sends DidChangeConfigurationNotification ↓ Middleware injects/migrates credentials ↓ Server processes with credentials ``` -------------------------------- ### Get Area Completions Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/ha-connection.md Retrieves completion items for all areas, including area ID, kind, documentation (area name), and sortText. ```typescript public async getAreaCompletions(): Promise ``` -------------------------------- ### HomeAssistantStatusBar Constructor Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/status-bar.md Initializes the HomeAssistantStatusBar with the provided VS Code extension context. This sets up the status bar item and its initial state. ```APIDOC ## Constructor HomeAssistantStatusBar ### Description Initializes the status bar item for displaying Home Assistant connection status. ### Parameters #### Parameters - **context** (`vscode.ExtensionContext`) - Required - VS Code extension context for resource management. ### Behavior - Creates status bar item aligned to the right with priority 100. - Sets command to `vscode-home-assistant.manageAuth`. - Initializes with "disconnected" status. - Registers itself for disposal when extension deactivates. ### Example ```typescript const statusBar = new HomeAssistantStatusBar(context); context.subscriptions.push(statusBar); ``` ``` -------------------------------- ### showReloadIntegrations() Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/commands.md Displays a quick pick menu allowing users to select and execute reload commands for specific Home Assistant integrations. ```APIDOC ## showReloadIntegrations() ### Description Shows a quick pick menu with reload commands for specific integrations. ### Parameters #### Path Parameters - commandMappings (`CommandMappings[]`) - Required - Array of all command mappings ### Behavior 1. Filters reload commands from mappings 2. Excludes the generic `reloadAll` command 3. Formats as quick pick items with: - **label**: Command name (e.g., "scriptReload") - **description**: Domain.service (e.g., "script.reload") - **commandId**: Full command ID for execution 4. Shows quick pick dialog 5. Executes selected command ``` -------------------------------- ### HomeAssistantConfiguration Interface Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/types.md Configuration object passed to language server initialization. This interface defines the settings for connecting to a Home Assistant instance. ```APIDOC ## HomeAssistantConfiguration Interface Configuration object passed to language server initialization. ```typescript export interface HomeAssistantConfiguration { longLivedAccessToken?: string; hostUrl?: string; ignoreCertificates: boolean; disableAutomaticFileAssociation: boolean; autoRenderTemplates: boolean; } ``` ### Fields - **longLivedAccessToken** (`string`): HA access token. Optional. - **hostUrl** (`string`): Instance URL. Optional. - **ignoreCertificates** (`boolean`): Skip SSL validation. Optional. Defaults to `false`. - **disableAutomaticFileAssociation** (`boolean`): Don't auto-associate files. Optional. Defaults to `false`. - **autoRenderTemplates** (`boolean`): Auto-render templates. Optional. Defaults to `true`. Sent via `initializationOptions` during language client startup. ``` -------------------------------- ### Get Valid YAML Tags Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/language-service.md Returns an array of valid YAML tags supported by Home Assistant syntax. This is an internal utility for YAML parsing. ```typescript private getValidYamlTags(): string[] ``` -------------------------------- ### Get Hover Information Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/language-service.md Provides hover information for schema documentation and deprecation warnings. Use this to display contextual help when hovering over code elements. ```typescript public getHover = async ( document: TextDocument, position: Position ): Promise ``` ```typescript const hover = await languageService.getHover(document, position); if (hover) { console.log(hover.contents); } ``` -------------------------------- ### Handle Configuration Send Failures Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/auth-middleware.md If sending the initial or follow-up configuration fails due to connection issues, the middleware continues to operate, injecting credentials into subsequent requests. ```text Error sending initial configuration: Connection lost Error sending follow-up configuration: Connection closed ``` -------------------------------- ### Get Debug Output Channel Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/auth-middleware.md Retrieves or creates the debug output channel for logging authentication operations. This channel is named 'Home Assistant Auth'. ```typescript private static getOutputChannel(): vscode.OutputChannel ``` -------------------------------- ### HomeAssistantConfiguration Interface Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/types.md Defines the configuration object passed to the language server during initialization. Use this to set up access token, host URL, and certificate handling. ```typescript export interface HomeAssistantConfiguration { longLivedAccessToken?: string; hostUrl?: string; ignoreCertificates: boolean; disableAutomaticFileAssociation: boolean; autoRenderTemplates: boolean; } ``` -------------------------------- ### Handle Connection Established Event Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/ha-connection.md Callback fired when a connection to Home Assistant is successfully established. It receives information about the connection, such as the instance name and version. ```typescript public onConnectionEstablished?: (info: { name?: string; version?: string }) => void ``` ```typescript haConnection.onConnectionEstablished = (info) => { console.log(`Connected to ${info.name} (v${info.version})`); }; ``` -------------------------------- ### findAndApplySchemas() Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/language-service.md Discovers Home Assistant configuration files and applies relevant JSON schemas for validation and completion. This method should be called to initialize the language service with the correct schemas. ```APIDOC ## findAndApplySchemas() ### Description Discovers Home Assistant configuration files and applies relevant JSON schemas for validation and completion. ### Method `async` ### Endpoint N/A (Class method) ### Parameters None ### Behavior 1. Retrieves all discovered Home Assistant files 2. Gets schema contributions from `SchemaServiceForIncludes` 3. Fixes circular `$ref` references in schemas (max depth 3) 4. Configures YAML language service with custom YAML tags, schema contributions, and enables validation, completion, and hover. 5. Triggers diagnostics for all files. ### Example ```typescript await languageService.findAndApplySchemas(); // All open YAML files now have schema validation ``` ``` -------------------------------- ### Get Service Completions Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/ha-connection.md Retrieves completion items for Home Assistant services and domains, including service calls, domain references, device actions, and triggers. ```typescript public async getServiceCompletions(): Promise ``` -------------------------------- ### activate() Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/extension.md Activates the Home Assistant extension by initializing the language server client, authentication system, status bar, and command handlers. This function is automatically called by VS Code upon extension activation. ```APIDOC ## activate() ### Description Activates the Home Assistant extension, initializing the language server client, auth system, status bar, and command handlers. ### Parameters #### Path Parameters - **context** (`vscode.ExtensionContext`) - Required - VS Code extension context providing subscriptions management, secret storage, and workspace access ### Behavior - Initializes `HomeAssistantStatusBar` for connection status display - Migrates tokens and URLs from settings to SecretStorage if needed - Initializes telemetry reporter - Creates and starts `LanguageClient` connecting to the language server - Installs `AuthMiddleware` to inject credentials - Registers all reload and management commands - Sets up notification handlers for server events: `no-config`, `ha_connected`, `ha_connection_error`, `configuration_check_completed`, `get_eror_log_completed`, `render_template_completed` - Automatically associates YAML files with Home Assistant language if workspace is detected - Initializes welcome message if no credentials are configured ### Registered Commands All commands are registered with prefixes `vscode-home-assistant.*`: **Reload Commands:** - `reloadAll` - Reload all integrations - `scriptReload` - Reload scripts - `groupReload` - Reload groups - `automationReload` - Reload automations - `sceneReload` - Reload scenes - `templateReload` - Reload template entities - `themeReload` - Reload themes - `homekitReload` - Reload HomeKit - And 20+ more integration-specific reload commands **Core Commands:** - `homeassistantCheckConfig` - Validate configuration remotely - `homeassistantReloadCoreConfig` - Reload core configuration - `homeassistantRestart` - Restart Home Assistant - `getErrorLog` - Retrieve error logs **Utility Commands:** - `renderTemplate` - Render Jinja2 templates - `openInBrowser` - Open Home Assistant in browser - `showReloadIntegrations` - Show integration reload menu **Authentication Commands:** - `manageAuth` - Manage token and instance URL - `debugAuth` - Debug authentication configuration - `repairAuth` - Repair authentication issues - `testConnection` - Test connection to Home Assistant ### Example ```typescript // This function is automatically called by VS Code when the extension activates // No manual invocation needed - declared in package.json activationEvents ``` ``` -------------------------------- ### openInBrowser Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/status-bar.md Opens the configured Home Assistant instance in the user's default web browser. Displays an error if the URL is not configured. ```APIDOC ## openInBrowser ### Description Opens Home Assistant in the default browser. ### Behavior 1. Gets URL from `AuthManager`. 2. If URL is available, opens it in system browser via `vscode.env.openExternal()`. 3. Shows error message if URL is not configured. ### Example ```typescript await statusBar.openInBrowser(); // Browser opens to Home Assistant instance ``` ``` -------------------------------- ### Get UUID Completions Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/ha-connection.md Retrieves completion items for UUIDs (automation/script IDs, etc.), including the UUID identifier, kind, documentation (associated entity name), and sortText. ```typescript public async getUuidCompletions(): Promise ``` -------------------------------- ### Open Home Assistant in Browser Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/status-bar.md Opens the configured Home Assistant instance URL in the default system browser. Displays an error message if the URL is not set. ```typescript await statusBar.openInBrowser(); // Browser opens to Home Assistant instance ``` -------------------------------- ### Get Document Diagnostics Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/language-service.md Generates validation diagnostics for a document, excluding errors on secret or input values which cannot be validated. It validates YAML syntax and filters out specific error types. ```typescript public getDiagnostics = async (document: TextDocument): Promise ``` ```typescript const diagnostics = await languageService.getDiagnostics(document); for (const diag of diagnostics) { console.log(`Line ${diag.range.start.line}: ${diag.message}`); } ``` -------------------------------- ### Check Credentials Before Connecting Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/errors.md Before attempting to connect, verify that the necessary credentials are configured and available. This prevents connection issues due to missing authentication tokens. ```typescript if (await AuthManager.hasCredentials(context)) { // Safe to connect } ``` -------------------------------- ### Find and Apply Schemas Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/language-service.md Discovers Home Assistant configuration files and applies relevant JSON schemas for validation and completion. This method configures the YAML language service with custom tags, schema contributions, and enables validation, completion, and hover features. ```typescript public findAndApplySchemas = async (): Promise ``` ```typescript await languageService.findAndApplySchemas(); // All open YAML files now have schema validation ``` -------------------------------- ### Get Home Assistant Token Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/auth-manager.md Retrieves the Home Assistant long-lived access token. It checks VS Code's SecretStorage first, then falls back to HASS_TOKEN and SUPERVISOR_TOKEN environment variables. ```typescript static async getToken(context: vscode.ExtensionContext): Promise ``` ```typescript const token = await AuthManager.getToken(context); if (token) { console.log(`Token found, length: ${token.length}`); } else { console.log("No token configured"); } ``` -------------------------------- ### Compile Project and Generate Schemas Source: https://github.com/keesschollaart81/vscode-home-assistant/wiki/HowTo:-Update-the-schema's This command compiles the project and generates JSON schemas. The schema generation happens automatically on the first run. ```bash npm run compile ``` -------------------------------- ### getDefinition() Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/language-service.md Provides "Go to Definition" functionality for includes, scripts, and secrets within Home Assistant configuration files. It helps navigate to the exact location where a symbol is defined. ```APIDOC ## getDefinition() API ### Description Provides "Go to Definition" functionality for includes, scripts, and secrets. This allows users to navigate directly to the definition of a symbol within the configuration files. ### Method Signature ```typescript public getDefinition(document: TextDocument, position: Position): Promise ``` ### Parameters #### Parameters - **document** (`TextDocument`) - Required - Document context - **position** (`Position`) - Required - Cursor position ### Returns `Definition[]` - An array of file locations where the symbol is defined. ### Supported Definition Types - `!include` directives - `!include_dir_list` - `!include_dir_named` - `!include_dir_merge_list` - `!include_dir_merge_named` - Scripts - `!secret` references ### Example ```typescript const definitions = await languageService.getDefinition(document, position); if (definitions.length > 0) { console.log(`Go to: ${definitions[0].uri}:${definitions[0].range.start.line}`); } ``` ``` -------------------------------- ### Telemetry Error Logging Example Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/errors.md Shows how errors during telemetry reporting are handled. Failures are caught and logged to the console using `console.log(error)` but are silently swallowed, meaning they do not impact the user experience or extension functionality. ```typescript // In src/extension.ts:54 catch (error) { console.log(error); // Logged but not shown to user } ``` -------------------------------- ### Default Configuration Settings Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/configuration.md These are the default values for the extension's configuration if not explicitly set by the user. ```json { "vscode-home-assistant.longLivedAccessToken": undefined, "vscode-home-assistant.hostUrl": undefined, "vscode-home-assistant.ignoreCertificates": false, "vscode-home-assistant.disableAutomaticFileAssociation": false, "vscode-home-assistant.autoRenderTemplates": true } ``` -------------------------------- ### Get Home Assistant Instance URL Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/auth-manager.md Retrieves the Home Assistant instance URL. It checks VS Code's SecretStorage first, then falls back to the HASS_SERVER environment variable, or a default URL if SUPERVISOR_TOKEN is set. ```typescript static async getUrl(context: vscode.ExtensionContext): Promise ``` ```typescript const url = await AuthManager.getUrl(context); if (url) { console.log(`Home Assistant at: ${url}`); } else { console.log("No instance URL configured"); } ``` -------------------------------- ### getTokenWithUI Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/auth-manager.md Retrieves the Home Assistant access token, attempting to get it from SecretStorage, environment variables, or settings. If the token or URL is not configured, it will prompt the user for input. It returns the token if found or entered, or undefined if the user cancels the process. ```APIDOC ## getTokenWithUI() ### Description Retrieves the Home Assistant access token, attempting to get it from SecretStorage, environment variables, or settings. If the token or URL is not configured, it will prompt the user for input. It returns the token if found or entered, or undefined if the user cancels the process. ### Method `static async getTokenWithUI(context: vscode.ExtensionContext): Promise` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Request Example ```typescript const token = await AuthManager.getTokenWithUI(context); if (token) { // Use token for API calls } ``` ### Response #### Success Response (200) `Promise` - The token if found/entered, undefined if user cancels #### Response Example ```json { "example": "your_home_assistant_token" or "undefined" } ``` ``` -------------------------------- ### Workspace Dependencies in package.json Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/PROJECT_STRUCTURE.md Lists key dependencies required by the extension, including VS Code API, language client, and Home Assistant specific libraries. ```json { "dependencies": { "vscode": "^1.99.0", "vscode-languageclient": "^9.0.1", "home-assistant-js-websocket": "^9.6.0", "yaml-language-server": "1.19.2", "axios": "^1.13.2" } } ``` -------------------------------- ### getHover() Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/language-service.md Provides hover information for schema documentation and deprecation warnings. When hovering over a specific part of the configuration, it displays relevant details, descriptions, and warnings. ```APIDOC ## getHover() API ### Description Provides hover information for schema documentation and deprecation warnings. This feature displays details about schema properties, enum values, deprecations, and default values when hovering over relevant parts of the configuration. ### Method Signature ```typescript public getHover(document: TextDocument, position: Position): Promise ``` ### Parameters #### Parameters - **document** (`TextDocument`) - Required - Document context - **position** (`Position`) - Required - Cursor position ### Returns `Hover | null` - Hover information or null if no information is available. ### Provides - Schema property descriptions - Enum value documentation - Deprecation warnings - Default values ### Example ```typescript const hover = await languageService.getHover(document, position); if (hover) { console.log(hover.contents); } ``` ``` -------------------------------- ### Initiating a Specific Integration Reload Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/commands.md Shows how to trigger the display of a quick pick menu for selecting a specific integration to reload. This is part of the user interaction flow for reloading integrations. ```typescript // User presses Ctrl+Shift+P and types "Reload specific" await showReloadIntegrations(commandMappings); // Quick pick appears, user selects integration to reload ``` -------------------------------- ### HomeAssistantLanguageService Constructor Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/language-service.md Initializes the HomeAssistantLanguageService with dependencies including the YAML language service, Home Assistant configuration, connection, definition providers, schema service, diagnostic callbacks, and configuration service. ```typescript constructor( private yamlLanguageService: LanguageService, private haConfig: HomeAssistantConfiguration, private haConnection: HaConnection, private definitionProviders: DefinitionProvider[], private schemaServiceForIncludes: SchemaServiceForIncludes, private sendDiagnostics: (fileUri: string, diagnostics: Diagnostic[]) => void, private diagnoseAllFiles: () => void, private configurationService: IConfigurationService ) ``` -------------------------------- ### ConfigurationService Class Definition Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/types.md Implements the IConfigurationService interface, managing Home Assistant connection configuration. Initializes from environment variables and updates from VS Code settings. ```typescript export class ConfigurationService implements IConfigurationService { public isConfigured = false; public token?: string; public url?: string; public ignoreCertificates = false; public disableAutomaticFileAssociation = false; public autoRenderTemplates = true; constructor() public updateConfiguration = (config: DidChangeConfigurationParams): void } ``` -------------------------------- ### Handle Missing Home Assistant URL Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/errors.md Check if the Home Assistant instance URL is configured. If not, the application cannot establish a connection, leading to empty completion lists and configuration errors. ```typescript const url = await AuthManager.getUrl(context); if (!url) { // Handle missing URL } ``` -------------------------------- ### Handle Configuration Request Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/auth-middleware.md Handles configuration requests from the language server, injecting credentials if the 'vscode-home-assistant' section is present. It also handles migrating credentials from settings.json to SecretStorage. ```typescript private async handleConfigurationRequest( originalSendRequest: Function, type: any, ...params: any[] ): Promise ``` -------------------------------- ### Initialization Options for Language Server Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/configuration.md Pass these options to the language server during initialization. They take precedence over environment variables for server-side operations. ```typescript { "vscode-home-assistant": { "longLivedAccessToken": "eyJhbGci...", "hostUrl": "http://homeassistant.local:8123", "ignoreCertificates": false } } ``` -------------------------------- ### DefinitionProvider Interface Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/types.md Interface for implementing 'Go to Definition' functionality. Implement this to provide definition locations for specific line content and URI. ```typescript export interface DefinitionProvider { onDefinition(line: string, uri: string): Promise; } ``` -------------------------------- ### Grant Write Access to User Source: https://github.com/keesschollaart81/vscode-home-assistant/wiki/VS-Code-Remote-SSH This command grants write access to the specified directory for your user. Replace 'yourusername' with your actual username and ensure the path points to your Home Assistant configuration folder. ```shell sudo chown -R yourusername /home/homeassistant/.homeassistant/ ``` -------------------------------- ### migrateUrlFromSettings Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/auth-manager.md Migrates a Home Assistant instance URL from VS Code settings to SecretStorage and removes it from settings.json. It returns true if the migration was successful, and false if no URL was found in the settings. ```APIDOC ## migrateUrlFromSettings() ### Description Migrates a Home Assistant instance URL from VS Code settings to SecretStorage and removes it from settings.json. It returns true if the migration was successful, and false if no URL was found in the settings. ### Method `static async migrateUrlFromSettings(context: vscode.ExtensionContext): Promise` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Request Example ```typescript const migrated = await AuthManager.migrateUrlFromSettings(context); if (migrated) { console.log("URL successfully migrated to secure storage"); } ``` ### Response #### Success Response (200) `Promise` - `true` if migration occurred, `false` if no URL in settings #### Response Example ```json { "example": "true or false" } ``` ``` -------------------------------- ### onConnectionFailed Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/ha-connection.md Callback fired when a connection to Home Assistant fails. Receives an error message or null. ```APIDOC ## onConnectionFailed ### Description Callback fired when connection to Home Assistant fails. ### Parameters | Parameter | Type | Description | |-----------|------|-------------| | error | `string \| null` | Error message or null | ### Example ```typescript haConnection.onConnectionFailed = (error) => { console.log(`Connection failed: ${error || "Unknown error"}`); }; ``` ``` -------------------------------- ### Handle Connection Errors Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/README.md Demonstrates how to catch and log errors during a connection attempt. Use this pattern for robust error handling. ```typescript try { await connection.connect(); } catch (error) { console.log("Connection failed:", error); } ``` -------------------------------- ### Migrate URL from Settings Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/auth-manager.md Migrates the Home Assistant instance URL from `settings.json` to `SecretStorage`. This should be called once to ensure URLs are stored securely. ```typescript const migrated = await AuthManager.migrateUrlFromSettings(context); if (migrated) { console.log("URL successfully migrated to secure storage"); } ``` -------------------------------- ### Set Home Assistant Host URL via Environment Variable Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/configuration.md Set the Home Assistant instance URL using the HASS_SERVER environment variable. This variable takes precedence over settings.json but has lower priority than SecretStorage. ```bash export HASS_SERVER="http://homeassistant.local:8123" ``` -------------------------------- ### Parallel Reload of Input Domains Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/commands.md Demonstrates using `Promise.all` to concurrently reload multiple input-related domains. This approach enhances performance by executing reloads in parallel rather than sequentially. ```typescript await Promise.all( ["input_button", "input_boolean", "input_datetime", "input_number", "input_select", "input_text"] .map(domain => client.sendRequest("callService", { domain, service: "reload" })) ); ``` -------------------------------- ### Show Reload Integrations Menu Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/commands.md Displays a quick pick menu allowing users to select specific integrations for reloading. It filters available commands and formats them for user selection. ```typescript export async function showReloadIntegrations( commandMappings: CommandMappings[] ): Promise ``` -------------------------------- ### HassLabel Interface Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/types.md Represents a Label/tag configuration in Home Assistant. ```APIDOC ## HassLabel Interface Label/tag configuration (exported from HaConnection). ```typescript export interface HassLabel { label_id: string; name: string; icon: string | null; color: string | null; description: string | null; } ``` ### Fields - **label_id** (`string`): Unique identifier. - **name** (`string`): Display name. - **icon** (`string | null`): Material Design icon. - **color** (`string | null`): Hex color. - **description** (`string | null`): Label description. ``` -------------------------------- ### Check for Credentials Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/auth-manager.md Checks if both a Home Assistant token and instance URL are available in the secure storage. ```typescript static async hasCredentials(context: vscode.ExtensionContext): Promise ``` -------------------------------- ### Extension Process Architecture Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/INDEX.md Illustrates the separation of concerns between the VS Code main process and the spawned language server process. It details the key components within each process. ```plaintext VS Code Process ├─ Extension Host (extension.ts) │ ├─ AuthManager - Credential management │ ├─ AuthMiddleware - Request/notification interception │ ├─ HomeAssistantStatusBar - UI status display │ └─ Commands - User action handlers │ └─ Language Server Process (server.ts) - Spawned as child ├─ ConfigurationService - Settings management ├─ HomeAssistantConfiguration - File discovery ├─ HaConnection - WebSocket to Home Assistant ├─ HomeAssistantLanguageService - LSP implementation ├─ SchemaServiceForIncludes - Schema loading └─ DefinitionProviders - Go to definition ├─ IncludeDefinitionProvider ├─ ScriptDefinitionProvider └─ SecretsDefinitionProvider ``` -------------------------------- ### HaFileInfo Interface Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/types.md Represents information about a single Home Assistant YAML file. It includes the filename and its full path or URI. ```typescript export interface HaFileInfo { filename: string; path: string; } ``` -------------------------------- ### Accessing and Updating Configuration at Runtime Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/configuration.md Demonstrates how to retrieve and modify extension configuration values programmatically within VSCode extension code. ```typescript // In extension code const config = vscode.workspace.getConfiguration("vscode-home-assistant"); const token = config.get("longLivedAccessToken"); const url = config.get("hostUrl"); const ignoreCerts = config.get("ignoreCertificates"); // Update a setting await config.update("key", value, ConfigurationTarget.Global); ``` -------------------------------- ### CommandMappings Class Constructor Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/api-reference/extension.md Defines a mapping between VS Code command IDs and Home Assistant service calls. Use this class to create mappings for custom commands. ```typescript export class CommandMappings { constructor( public commandId: string, public domain: string, public service: string, public serviceData?: { [key: string]: any } ) {} } ``` -------------------------------- ### IConfigurationService Interface Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/types.md Defines the public interface for accessing and updating the extension's configuration, including Home Assistant token, URL, and other settings. ```typescript export interface IConfigurationService { isConfigured: boolean; token?: string; url?: string; ignoreCertificates: boolean; disableAutomaticFileAssociation: boolean; autoRenderTemplates: boolean; updateConfiguration(config: DidChangeConfigurationParams): void; } ``` -------------------------------- ### HassLabel Interface Source: https://github.com/keesschollaart81/vscode-home-assistant/blob/dev/_autodocs/types.md Represents the structure of a label/tag configuration in Home Assistant. Includes ID, name, icon, color, and description. ```typescript export interface HassLabel { label_id: string; name: string; icon: string | null; color: string | null; description: string | null; } ```