### MCP Server Integration for AI Assistants Source: https://github.com/snapback-dev/vscode/blob/main/README.md Demonstrates how AI assistants can interact with the SnapBack MCP server to manage code changes. It shows functions for starting tasks, getting context, validating changes, and ending sessions with learned patterns. Requires the SnapBack MCP server to be configured and running. ```javascript snap({mode: "start", task: "refactor auth module"}) → SnapBack creates checkpoint, returns context snap({mode: "check", files: ["auth.ts"]}) → Validates changes against learned patterns snap_end({ok: 1, learnings: ["Always backup before auth changes"]}) → Records session outcome for future learning ``` -------------------------------- ### SnapBack CLI Installation Source: https://github.com/snapback-dev/vscode/blob/main/README.md Command to install the SnapBack Command Line Interface (CLI) globally using npm. This allows for terminal-based automation and workflows. ```bash npm install -g @snapback/cli ``` -------------------------------- ### Initialize Development Environment Source: https://github.com/snapback-dev/vscode/blob/main/docs/development/ci-cd-guide.md Installs all project dependencies required for development using the pnpm package manager. ```bash pnpm install ``` -------------------------------- ### Define Contextual Beginner Hints Source: https://github.com/snapback-dev/vscode/blob/main/docs/PROGRESSIVE_DISCLOSURE.md A configuration object containing key-value pairs for UI hints shown to beginner users. These tips are triggered based on specific user actions to guide them through core features. ```json { "firstSnapshot": "💡 Tip: SnapBack automatically creates snapshots when you save protected files", "firstProtection": "💡 Tip: Use 🟢 Watch for silent snapshots, 🟡 Warn for confirmations, 🔴 Block for required notes", "firstRestore": "💡 Tip: You can compare snapshots side-by-side before restoring", "treeView": "💡 Tip: Click the SnapBack icon in the activity bar to see all your snapshots" } ``` -------------------------------- ### Best Practice: .snapbackrc with Descriptive Comments Source: https://github.com/snapback-dev/vscode/blob/main/docs/user-guide/team-configuration.md An example of a .snapbackrc file that includes descriptive comments to explain the rationale behind specific file protection levels. This enhances team understanding and maintainability of the configuration. ```json5 { patterns: { // Production credentials - never change without snapshot ".env.production": "Protected", // Dependency changes affect all developers "package.json": "Warning", "package-lock.json": "Warning", }, } ``` -------------------------------- ### SnapBack Basic Configuration File Source: https://github.com/snapback-dev/vscode/blob/main/docs/user-guide/settings.md A basic example of a .snapbackrc file used to define file protection patterns and their corresponding protection levels. This allows for team-wide consistency in how SnapBack handles different file types. ```json { "patterns": { "**/*.env": "block", "**/package.json": "warn", "**/*.config.js": "warn" } } ``` -------------------------------- ### Define SnapBack Configuration Patterns Source: https://github.com/snapback-dev/vscode/blob/main/docs/user-guide/team-configuration.md Examples of defining file patterns for different project types. Patterns are categorized by protection levels: Protected (Critical), Warning (Important), and Watched (Development). ```json5 { patterns: { ".env.production": "Protected", "docker-compose.production.yml": "Protected", ".env.local": "Warning", "package.json": "Warning", "src/components/**/*": "Watched" } } ``` ```json5 { patterns: { ".env.production": "Protected", "database/schema.sql": "Protected", "src/routes/**/*": "Warning", "src/controllers/**/*": "Watched" } } ``` ```json5 { patterns: { "terraform/production/**/*": "Protected", "terraform/staging/**/*": "Warning", "terraform/dev/**/*": "Watched" } } ``` -------------------------------- ### SnapBack Command Filtering by Experience Level Source: https://github.com/snapback-dev/vscode/blob/main/docs/PROGRESSIVE_DISCLOSURE.md This JSON object shows an example of how commands in the SnapBack extension are filtered based on the user's experience level using 'when' clauses. This specific example defines a command that is only available when the experience level is set to 'advanced'. ```json { "command": "snapback.deleteOlderSnapshots", "when": "snapback.experienceLevel == 'advanced'" } ``` -------------------------------- ### Example Mocha Integration Test for Protection Commands Source: https://github.com/snapback-dev/vscode/blob/main/docs/development/testing-guide.md A TypeScript example of a Mocha integration test for SnapBack's protection commands. It verifies command registration and checks for the creation of the .snapback directory upon extension activation within a VS Code environment. ```typescript import * as vscode from "vscode"; import * as assert from "assert"; import { before, after, describe, it } from "mocha"; describe("Protection Commands Integration", () => { before(async () => { // Ensure extension is activated const extension = vscode.extensions.getExtension( "marcelle-labs.snapback" ); if (!extension?.isActive) { await extension?.activate(); } }); it("should register all protection commands", async () => { const commands = await vscode.commands.getCommands(true); const protectionCommands = [ "snapback.protectFile", "snapback.changeProtectionLevel", "snapback.setWatchLevel", "snapback.setWarnLevel", "snapback.setBlockLevel", ]; for (const command of protectionCommands) { assert.ok( commands.includes(command), `Command ${command} should be registered` ); } }); it("should create .snapback directory on activation", async () => { const workspaceFolders = vscode.workspace.workspaceFolders; if (!workspaceFolders) { assert.fail("No workspace folders found"); return; } const snapbackDir = vscode.Uri.joinPath( workspaceFolders[0].uri, ".snapback" ); try { await vscode.workspace.fs.stat(snapbackDir); assert.ok(true, ".snapback directory should exist"); } catch (error) { assert.fail(".snapback directory should be created on activation"); } }); }); ``` -------------------------------- ### Basic .snapbackrc Configuration Source: https://github.com/snapback-dev/vscode/blob/main/docs/user-guide/team-configuration.md A basic example of a .snapbackrc file defining protection patterns and their corresponding levels. This configuration ensures that common file types like environment variables and package manifests are protected or warned about. ```json5 { // Protection patterns patterns: { // Pattern: Protection Level "**/*.env": "Protected", "**/package.json": "Warning", "**/*.config.js": "Warning", }, } ``` -------------------------------- ### SnapBack Configuration File (.snapbackrc) Source: https://github.com/snapback-dev/vscode/blob/main/README.md Example of a .snapbackrc configuration file used to define protection patterns and snapshot settings. This file allows for workspace-specific configurations, such as defining which files to protect and how, and setting snapshot auto-creation and retention policies. ```json { "protection": { "patterns": { "*.env*": "block", "src/auth/**": "warn", "**/database/**": "watch" } }, "snapshots": { "autoCreate": true, "maxAge": "30d" } } ``` -------------------------------- ### SnapBack CLI Commands for Snapshots and Protection Source: https://github.com/snapback-dev/vscode/blob/main/README.md Examples of common SnapBack CLI commands for managing snapshots and checking code. These commands facilitate terminal workflows and automation, sharing the same database as the VS Code extension. ```bash # Create a snapshot before risky operations snapback snap "before refactor" # List recent snapshots snapback list # Restore a specific snapshot snapback restore # Check file against learned patterns snapback check src/auth.ts # View protection status snapback status ``` -------------------------------- ### User Action Tracking in SnapBack Source: https://github.com/snapback-dev/vscode/blob/main/docs/PROGRESSIVE_DISCLOSURE.md These TypeScript examples show how to track various user actions within the SnapBack extension using the `userExperienceService.trackAction` method. This is crucial for understanding user behavior and progression through different experience levels. ```typescript // When snapshot is created await userExperienceService.trackAction('snapshotCreated'); // When snapshot is restored await userExperienceService.trackAction('snapshotRestored'); // When protection level changed await userExperienceService.trackAction('protectionChanged'); // When session finalized await userExperienceService.trackAction('sessionFinalized'); ``` -------------------------------- ### SnapBack Advanced Configuration File Source: https://github.com/snapback-dev/vscode/blob/main/docs/user-guide/settings.md An advanced example of a .snapbackrc file demonstrating more comprehensive configuration options. This includes setting default protection levels, defining multiple file patterns with specific protection levels, and enabling snapshot deduplication. ```json { "protectionLevels": { "defaultLevel": "watch" }, "patterns": { "**/*.env": "Protected", "**/package.json": "Warning", "**/*.config.js": "Warning", "src/components/**/*": "Watched", "src/api/**/*": "Warning" }, "snapshot": { "deduplication": { "enabled": true } } } ``` -------------------------------- ### Displaying Contextual Hints in SnapBack Source: https://github.com/snapback-dev/vscode/blob/main/docs/PROGRESSIVE_DISCLOSURE.md This TypeScript code demonstrates how to display contextual hints to the user using the `progressiveDisclosureController.showHint` method. These hints guide users by providing information based on their current progress or actions within the extension. ```typescript // After first snapshot await progressiveDisclosureController.showHint('firstSnapshot'); // After first protection await progressiveDisclosureController.showHint('firstProtection'); // When opening tree view await progressiveDisclosureController.showHint('treeView'); ``` -------------------------------- ### Best Practice: Simple .snapbackrc for Critical Files Source: https://github.com/snapback-dev/vscode/blob/main/docs/user-guide/team-configuration.md A minimal .snapbackrc configuration focusing on protecting the most critical files, such as production environment variables and package.json. This approach starts with essential protection and can be expanded later. ```json5 { patterns: { ".env.production": "Protected", "package.json": "Warning", }, } ``` -------------------------------- ### Include Native Module in Dependencies Source: https://github.com/snapback-dev/vscode/blob/main/docs/ESBUILD_NATIVE_MODULES.md Specifies that 'better-sqlite3' should be listed under 'dependencies' in the package.json file. This ensures the module is installed and available when the extension is packaged and distributed. ```json { "dependencies": { "better-sqlite3": "9.6.0" } } ``` -------------------------------- ### Configure GitHub Actions CI Workflow Source: https://github.com/snapback-dev/vscode/blob/main/docs/development/testing-guide.md This YAML configuration defines a GitHub Actions workflow for the SnapBack project. It automates the testing process by checking out the code, setting up Node.js, installing dependencies, and executing both unit and integration test suites on every push or pull request. ```yaml name: Test on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: 20 - run: npm install - run: npm run test:unit - run: npm run test:integration ``` -------------------------------- ### Document Performance Trade-offs Source: https://github.com/snapback-dev/vscode/blob/main/CONTRIBUTING.md Example of how to document performance trade-offs within the source code using comments. ```typescript // Performance note: This is O(n) but necessary for consistency // See: https://github.com/issue-number for optimization plan ``` -------------------------------- ### Unit Testing with Vitest Source: https://github.com/snapback-dev/vscode/blob/main/CONTRIBUTING.md A template for writing unit tests using Vitest. It demonstrates setup and teardown logic for a class and basic assertion patterns. ```typescript import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import { SnapshotManager } from '../src/snapshot/SnapshotManager'; describe('SnapshotManager', () => { let manager: SnapshotManager; beforeEach(async () => { manager = new SnapshotManager(/* config */); }); afterEach(async () => { await manager.cleanup(); }); it('should create a snapshot with valid file path', async () => { const snapshot = await manager.create('/path/to/file.ts'); expect(snapshot).toBeDefined(); expect(snapshot.id).toMatch(/^snap_/); }); it('should reject invalid file paths', async () => { await expect(manager.create('../../../etc/passwd')).rejects.toThrow(); }); }); ``` -------------------------------- ### Add and Execute electron-rebuild Source: https://github.com/snapback-dev/vscode/blob/main/docs/ESBUILD_NATIVE_MODULES.md Installs the '@electron/rebuild' package as a development dependency and then executes it. This tool helps in rebuilding native Node.js modules for Electron environments, which is relevant for VSCode extensions. ```bash pnpm add -D @electron/rebuild pnpm exec electron-rebuild ``` -------------------------------- ### Example Vitest Unit Test for Checkpoint Naming Source: https://github.com/snapback-dev/vscode/blob/main/docs/development/testing-guide.md A TypeScript example demonstrating a Vitest unit test for the calculateCheckpointName utility function. It mocks the gitService to provide a controlled git context for testing name generation. ```typescript import { describe, it, expect, vi } from "vitest"; import { calculateCheckpointName } from "../../src/utils/checkpointUtils"; describe("calculateCheckpointName", () => { it("should generate a name based on git context", () => { // Mock git context vi.mock("../../src/git/gitService", () => ({ getGitContext: () => ({ branch: "main", commit: "abc123", status: "modified", }), })); const result = calculateCheckpointName("test.txt"); expect(result).toContain("main"); expect(result).toContain("abc123"); }); }); ``` -------------------------------- ### GET snapback/intelligence/detectFrameworks Source: https://context7.com/snapback-dev/vscode/llms.txt Identifies frameworks and technologies used within the workspace. ```APIDOC ## GET snapback/intelligence/detectFrameworks ### Description Analyzes workspace to identify frameworks and configure appropriate patterns. ### Method GET ### Endpoint snapback/intelligence/detectFrameworks ### Response #### Success Response (200) - **frameworks** (array) - List of detected frameworks with versions and confidence scores. #### Response Example { "success": true, "frameworks": [ { "name": "react", "version": "18.2.0", "confidence": 0.95 } ] } ``` -------------------------------- ### GET snapback/vitals Source: https://context7.com/snapback-dev/vscode/llms.txt Retrieves health metrics and snapshot recommendations for the current workspace. ```APIDOC ## GET snapback/vitals ### Description Returns workspace health snapshot with guidance based on current activity levels. ### Method GET ### Endpoint snapback/vitals ### Response #### Success Response (200) - **vitals** (object) - Workspace health metrics including pulse, temperature, pressure, and oxygen. - **guidance** (object) - Recommended operations and suggestions. - **snapshotDecision** (object) - Recommendation on whether a snapshot is required. #### Response Example { "success": true, "vitals": { "pulse": { "changesPerMinute": 5, "level": "moderate" }, "temperature": { "aiPercentage": 45, "level": "warm" } }, "guidance": { "suggestion": "Consider creating a snapshot before major changes" } } ``` -------------------------------- ### Release Process Commands Source: https://github.com/snapback-dev/vscode/blob/main/CONTRIBUTING.md Standard workflow for maintainers to update the version, build, test, and deploy the extension. ```bash npm version patch|minor|major pnpm run compile pnpm test pnpm run deploy ``` -------------------------------- ### Open Quick Restore Picker (TypeScript) Source: https://context7.com/snapback-dev/vscode/llms.txt Opens a quick pick menu for rapid snapshot selection and restoration of the current file. It provides a list of recent snapshots with timestamps and AI tool attribution, enabling one-click restore. ```typescript // Command: snapback.quickRestore // Keyboard shortcut: Ctrl+Shift+R (Windows) / Cmd+Shift+R (Mac) // Provides: // - List of recent snapshots for current file // - Timestamped entries with AI tool attribution // - One-click restore without confirmation dialogs ``` -------------------------------- ### Configure Advanced Settings (.snapbackrc JSON) Source: https://context7.com/snapback-dev/vscode/llms.txt Provides advanced configuration options for SnapBack, including protection settings, ignore patterns, snapshot management, policies, and hooks. This allows for fine-grained control over SnapBack's behavior. ```json { "protection": [ { "pattern": ".env.production", "level": "block", "reason": "Production credentials - never change without snapshot", "autoCheckpoint": true, "debounce": 1000 }, { "pattern": "src/api/**/*", "level": "warn", "excludeFrom": ["src/api/test/**"] }, { "pattern": "database/migrations/**/*", "level": "warn" } ], "ignore": [ "node_modules/**", "dist/**", "*.log" ], "settings": { "maxSnapshots": 100, "compressionEnabled": true, "autoCheckpointInterval": 300000, "notificationDuration": 3000, "showStatusBarItem": true, "confirmRestore": true, "defaultProtectionLevel": "watch", "protectionDebounce": 500, "snapshotLocation": ".snapback", "maxStorageSize": 104857600, "parallelOperations": 4, "enableCaching": true }, "policies": { "requireCheckpointMessage": false, "enforceProtectionLevels": true, "allowOverrides": true, "minimumProtectionLevel": "watch", "preventAccidentalCommit": true }, "hooks": { "beforeSnapshot": "npm run lint", "afterSnapshot": "echo 'Snapshot created'", "beforeRestore": "git stash", "afterRestore": "npm install" } } ``` -------------------------------- ### VS Code Settings for SnapBack Source: https://github.com/snapback-dev/vscode/blob/main/README.md Illustrates VS Code settings that can be configured for SnapBack, including enabling auto-protection, defining protection patterns, and managing telemetry. These settings allow for fine-tuning SnapBack's behavior within the VS Code environment. ```json { "snapback.autoProtect": true, "snapback.protectionPatterns": ["*.env*", "**/*.key"], "snapback.telemetry": false } ``` -------------------------------- ### Configure Basic Protection Patterns (.snapbackrc JSON) Source: https://context7.com/snapback-dev/vscode/llms.txt Defines file protection patterns using glob syntax within the .snapbackrc configuration file. It specifies patterns, protection levels (block, warn), and reasons for protection. ```json { "protection": [ { "pattern": "**/*.env", "level": "block", "reason": "Environment files contain sensitive credentials" }, { "pattern": "**/package.json", "level": "warn", "reason": "Dependency changes affect all developers" }, { "pattern": "src/components/**/*", "level": "watch", "reason": "Active development files" } ] } ``` -------------------------------- ### Manage Performance Budgets Source: https://github.com/snapback-dev/vscode/blob/main/CONTRIBUTING.md Commands to execute performance tests, check bundle size, and enforce performance budgets for the extension. ```bash pnpm test:perf pnpm run check:bundle-size pnpm run enforce-performance-budget ``` -------------------------------- ### Run SnapBack CI/CD Test Commands Source: https://github.com/snapback-dev/vscode/blob/main/docs/development/ci-cd-guide.md A set of npm scripts used to execute various test suites, including unit, integration, and performance tests. These commands are essential for local development and CI pipeline validation. ```bash npm run test npm run test:unit npm run test:integration npm run test:coverage npm run test:performance npm run test:watch ``` -------------------------------- ### Get Workspace Vitals - TypeScript Source: https://context7.com/snapback-dev/vscode/llms.txt Retrieves workspace health metrics and snapshot recommendations using the snapback/vitals LSP request. It returns an object containing success status, vitals data (pulse, temperature, pressure, oxygen), guidance on operations, and a snapshot decision. ```typescript const vitalsResult = await connection.sendRequest("snapback/vitals", {}); ``` -------------------------------- ### SnapBack Command 'when' Clauses for Experience Level Source: https://github.com/snapback-dev/vscode/blob/main/docs/PROGRESSIVE_DISCLOSURE.md This JSON snippet illustrates the 'when' clauses used to control the visibility and availability of SnapBack extension commands based on the user's experience level. These clauses ensure that commands are only shown when appropriate for the user's current mode (e.g., 'advanced', 'intermediate'). ```json { "command": "snapback.deleteOlderSnapshots", "when": "snapback.experienceLevel == 'advanced'" }, { "command": "snapback.changeProtectionLevel", "when": "snapback.experienceLevel == 'intermediate' || snapback.experienceLevel == 'advanced'" } ``` -------------------------------- ### POST /webview/extension/action Source: https://github.com/snapback-dev/vscode/blob/main/docs/DiffViewManager-Architecture.md Handles user-triggered actions from the webview back to the extension host. ```APIDOC ## POST /webview/extension/action ### Description Processes user interactions such as accepting, ignoring, or rolling back changes. ### Method POST ### Endpoint /webview/extension/action ### Request Body - **type** (string) - Required - Action type: 'rollback', 'ignore', or 'accept' ### Request Example { "type": "accept" } ### Response #### Success Response (200) - **status** (string) - Confirmation of action processing ``` -------------------------------- ### Run Unit Tests with Vitest Source: https://github.com/snapback-dev/vscode/blob/main/docs/development/testing-guide.md Commands to execute unit tests using Vitest, including options for coverage reports and running specific test files. Unit tests focus on isolated components with heavy mocking. ```bash npm run test:unit npm run test:coverage npm run test:unit -- test/unit/specific.test.ts ``` -------------------------------- ### Manage Snapshots with MCP Tools Source: https://context7.com/snapback-dev/vscode/llms.txt Utilize the snap and snap_end tools to manage development task lifecycles, create checkpoints, and record learnings. These tools help maintain workspace context and track task outcomes. ```typescript snap({ mode: "start", task: "refactor auth module" }); snap({ mode: "check", files: ["auth.ts"] }); snap({ mode: "context" }); snap_end({ ok: 1, learnings: ["Always backup before auth changes"] }); ``` -------------------------------- ### Collect Load Metrics Source: https://github.com/snapback-dev/vscode/blob/main/CONTRIBUTING.md Command to collect performance metrics to identify bottlenecks when performance budgets are exceeded. ```bash pnpm run collect-load-metrics ``` -------------------------------- ### Debugging Native Module Loading Issues Source: https://github.com/snapback-dev/vscode/blob/main/docs/ESBUILD_NATIVE_MODULES.md This section provides troubleshooting steps for common issues when loading native modules, such as 'Cannot find module 'better-sqlite3''. It includes checks for the module's presence in 'node_modules', its inclusion in 'package.json' dependencies, and guidance on rebuilding the package. ```bash # 1. Check node_modules exists: ls node_modules/better-sqlite3 # 2. Verify it's in dependencies (not devDependencies): grep better-sqlite3 package.json # 3. Rebuild .vsix: pnpm run package ``` -------------------------------- ### Status Bar Beginner Mode UI Source: https://github.com/snapback-dev/vscode/blob/main/docs/PROGRESSIVE_DISCLOSURE.md Represents the status bar component displayed to beginner users. It provides a quick entry point for tips and recommended actions. ```text $(lightbulb) SnapBack Tips ``` -------------------------------- ### Configure Core Extension Settings (VS Code JSON) Source: https://context7.com/snapback-dev/vscode/llms.txt Sets core behavior for the SnapBack VS Code extension. This includes enabling/disabling features like AI detection, guardian, proactive alerts, and configuring logging levels and UI elements. ```json { "snapback.enabled": true, "snapback.aiDetection.enabled": true, "snapback.showAutoSnapshotNotifications": true, "snapback.guardian.enabled": true, "snapback.proactiveAlerts.enabled": true, "snapback.offlineMode.enabled": false, "snapback.logLevel": "info", "snapback.logNamespaces": ["activation", "mcp", "snapshot"], "snapback.logBatchDebug": false, "snapback.ui.showTreeView": false, "snapback.ui.hideInternalFiles": true } ``` -------------------------------- ### Integrate Webview Build into Extension Source: https://github.com/snapback-dev/vscode/blob/main/docs/DiffViewManager-Architecture.md A build step for the extension that triggers the Vite build process for the webview during production builds. ```javascript const buildWebview = async () => { console.log('Building webview...'); const { build } = require('vite'); await build({ configFile: './webview-ui/vite.config.ts' }); console.log('Webview built'); }; if (production) { await buildWebview(); } ``` -------------------------------- ### Pull Request Preparation Source: https://github.com/snapback-dev/vscode/blob/main/CONTRIBUTING.md Commands to synchronize the local branch with the main repository and run all required verification checks before opening a PR. ```bash git fetch origin git rebase origin/main pnpm run security:all pnpm test pnpm run check-types pnpm run lint pnpm run format pnpm run check:bundle-size ``` -------------------------------- ### Configure MCP Settings Source: https://github.com/snapback-dev/vscode/blob/main/docs/user-guide/mcp-troubleshooting.md Defines the essential configuration parameters for the SnapBack MCP integration, including server URL, authentication, and connection timeouts. ```json { "snapback.mcp.enabled": true, "snapback.mcp.serverUrl": "https://your-mcp-server.example.com", "snapback.mcp.authToken": "", "snapback.mcp.timeout": 5000, "snapback.mcp.authType": "bearer", "snapback.mcp.apiKey": "" } ``` -------------------------------- ### MCP Server Configuration Source: https://github.com/snapback-dev/vscode/blob/main/README.md Shows the JSON configuration required to add the SnapBack MCP server to an AI assistant's settings. This enables the AI assistant to communicate with the SnapBack protection system. ```json { "mcpServers": { "snapback": { "command": "npx", "args": ["@snapback/mcp-server"] } } } ``` -------------------------------- ### Configure Webview Build with Vite Source: https://github.com/snapback-dev/vscode/blob/main/docs/DiffViewManager-Architecture.md Defines the package dependencies and Vite configuration for the webview-ui component. It specifies the entry point and output settings for the React-based diff viewer. ```json { "name": "snapback-webview-ui", "private": true, "scripts": { "build": "vite build", "dev": "vite build --watch" }, "dependencies": { "react": "^18.2.0", "react-dom": "^18.2.0" }, "devDependencies": { "@types/react": "^18.2.0", "@types/react-dom": "^18.2.0", "@vitejs/plugin-react": "^4.0.0", "typescript": "^5.0.0", "vite": "^5.0.0" } } ``` ```typescript import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], build: { outDir: 'dist', rollupOptions: { input: { diffViewer: 'src/DiffViewer.tsx' }, output: { entryFileNames: '[name].js', chunkFileNames: '[name].js', assetFileNames: '[name].[ext]' } }, minify: 'esbuild', sourcemap: true, target: 'es2020' } }); ``` -------------------------------- ### POST /extension/command Source: https://context7.com/snapback-dev/vscode/llms.txt Sends commands from the webview to the extension to trigger snapshot actions, restorations, or navigation. ```APIDOC ## POST /extension/command ### Description Allows the webview to request actions from the extension host. ### Method POST ### Endpoint Internal Message Protocol (postMessage) ### Request Body - **command** (string) - Required - The action to perform (e.g., "createSnapshot", "restoreSnapshot", "navigateTo") - **file** (string) - Optional - Target file for snapshot - **snapshotId** (string) - Optional - ID for restoration - **tab** (string) - Optional - Target tab for navigation ### Request Example { "command": "createSnapshot", "file": "src/auth.ts" } ``` -------------------------------- ### Troubleshoot Extension Issues Source: https://github.com/snapback-dev/vscode/blob/main/CONTRIBUTING.md Commands for common troubleshooting tasks including clearing cache, running tests in CI conditions, and fixing type or bundle size issues. ```bash rm -rf node_modules pnpm-lock.yaml pnpm install pnpm test --clearCache pnpm test:ci pnpm run check-types pnpm run compile pnpm run check:bundle-size pnpm ls pnpm run lint:fix pnpm run security:check-deps pnpm run security:audit:fix pnpm run security:licenses ``` -------------------------------- ### Opening Native VSCode Diff Viewer (TypeScript) Source: https://github.com/snapback-dev/vscode/blob/main/docs/DiffViewManager-Architecture.md Demonstrates how to use VSCode's built-in `vscode.diff` command to open a native diff editor, leveraging the Monaco Editor's diffing capabilities. This approach avoids custom diff rendering in the webview. ```typescript // In DiffViewManager, instead of sending raw content to webview: async openDiffViewer(changeId: string): Promise { const { filePath, snapshotId } = this._parseChangeId(changeId); // Create virtual URIs for snapshot and current file const snapshotUri = vscode.Uri.parse(`snapback-snapshot:${snapshotId}/${filePath}`); const currentUri = vscode.Uri.file(filePath); // Open native diff editor await vscode.commands.executeCommand( 'vscode.diff', snapshotUri, // Left side (snapshot) currentUri, // Right side (current) `$(history) SnapBack: ${path.basename(filePath)}`, // Title { preview: false, // Keep open when switching files viewColumn: vscode.ViewColumn.Beside // Split editor } ); // Show action buttons in webview panel below diff // (Webview panel shows only metadata + action buttons, not diff itself) const panel = this._createActionPanel(changeId, filePath, snapshotId); await this._sendMetadata(panel, { changeId, filePath, recommendation: '...' }); } ``` -------------------------------- ### SnapBack Extension Configuration Settings Source: https://github.com/snapback-dev/vscode/blob/main/docs/PROGRESSIVE_DISCLOSURE.md This JSON object defines the configuration settings for the SnapBack VS Code extension. It includes options for enabling progressive disclosure, manually setting the experience level, and controlling the visibility of contextual hints. ```json { "snapback.progressiveDisclosure.enabled": { "type": "boolean", "default": true, "description": "Enable progressive disclosure of features" }, "snapback.progressiveDisclosure.manualLevel": { "type": "string", "enum": ["auto", "beginner", "intermediate", "advanced"], "default": "auto", "description": "Manually set experience level (or 'auto' to calculate automatically)" }, "snapback.progressiveDisclosure.showHints": { "type": "boolean", "default": true, "description": "Show contextual hints and tips" } } ``` -------------------------------- ### VS Code Webview Initialization and Event Handling (TypeScript) Source: https://github.com/snapback-dev/vscode/blob/main/docs/DiffViewManager-Architecture.md Initializes the VS Code webview panel, sets its HTML content using a React bundle, and sets up listeners for messages from the webview and for panel disposal. It also manages disposables to prevent memory leaks. ```typescript // Set HTML content with React bundle panel.webview.html = this._getHtmlForWebview(panel.webview); // Handle messages from webview const messageListener = panel.webview.onDidReceiveMessage( message => this._handleWebviewMessage(changeId, message) ); // Handle panel disposal panel.onDidDispose(() => { this._disposePanel(changeId); messageListener.dispose(); }); this._disposables.push(messageListener); return panel; } ``` -------------------------------- ### Advanced .snapbackrc Configuration with Protection Levels and Snapshots Source: https://github.com/snapback-dev/vscode/blob/main/docs/user-guide/team-configuration.md An advanced .snapbackrc configuration demonstrating custom protection levels, including a default level, and specific patterns for critical, important, and development files. It also includes optional snapshot settings like deduplication. ```json5 { // Optional: Override default settings protectionLevels: { defaultLevel: "Watched", }, // Protection patterns patterns: { // Critical files - require snapshots ".env.production": "Protected", ".env.staging": "Protected", "docker-compose.production.yml": "Protected", // Important files - notify on changes "package.json": "Warning", "package-lock.json": "Warning", "yarn.lock": "Warning", "src/api/**/*": "Warning", "database/migrations/**/*": "Warning", // Development files - silent protection "src/components/**/*": "Watched", "src/hooks/**/*": "Watched", "tests/**/*": "Watched", }, // Optional: Snapshot settings snapshot: { deduplication: { enabled: true, }, }, } ``` -------------------------------- ### Configure MCP Integrations (.snapbackrc JSON) Source: https://context7.com/snapback-dev/vscode/llms.txt Configures external Model Context Protocol (MCP) integrations for enriched context within SnapBack. It enables integrations like GitHub and Sentry, specifying their configurations and caching settings. ```json { "integrations": { "enabled": true, "github": { "enabled": true, "token": "${GITHUB_TOKEN}", "owner": "my-org", "repo": "my-repo", "timeoutMs": 5000 }, "sentry": { "enabled": true, "authToken": "${SENTRY_AUTH_TOKEN}", "organization": "my-org", "project": "my-project", "timeoutMs": 5000 }, "cache": { "enabled": true, "githubTtlMs": 300000, "sentryTtlMs": 300000, "maxEntries": 100 }, "circuitBreaker": { "failureThreshold": 3, "recoveryTimeMs": 60000 } } } ```