### Rename Flow Example Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/agent/smart.md A workflow for renaming symbols across the workspace, starting with a check using lsp_prepare_rename, followed by lsp_rename, and verification with diagnostics and build checks. ```markdown 1. Run lsp_prepare_rename to verify rename is possible 2. If valid, run lsp_rename to perform workspace-wide rename 3. Run lsp_diagnostics to catch any issues 4. Run build/typecheck to verify ``` -------------------------------- ### Record Performance Trace with chrome-devtools-mcp Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/performance-guide.md This example demonstrates how to record a performance trace using 'chrome-devtools-mcp'. It specifies trace categories, navigates to a page, waits for network idle, optionally performs a click action, stops the trace, and analyzes the collected data for insights. ```javascript await useTool('performance_start_trace', { categories: ['loading', 'rendering', 'scripting', 'network'] }); await useTool('navigate_page', { url: 'https://example.com' }); await useTool('wait_for', { waitUntil: 'networkidle' }); await useTool('click', { uid: 'button-uid' }); const traceData = await useTool('performance_stop_trace'); const insights = await useTool('performance_analyze_insight'); ``` -------------------------------- ### Install Puppeteer Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/puppeteer-reference.md Installs Puppeteer for browser automation or Puppeteer-core if you intend to use your own Chrome instance. These commands are executed using npm. ```bash # Install Puppeteer npm install puppeteer # Install core only (bring your own Chrome) npm install puppeteer-core ``` -------------------------------- ### Understanding Code Flow Example Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/agent/smart.md A workflow for understanding existing code, utilizing tools like lsp_document_symbols, lsp_hover, lsp_goto_definition, lsp_find_references, and the Explore subagent. ```markdown 1. Use lsp_document_symbols to get file structure 2. Use lsp_hover for type information 3. Use lsp_goto_definition to trace dependencies 4. Use lsp_find_references to see usage patterns 5. Use Explore subagent for broader codebase understanding ``` -------------------------------- ### API/Library Adoption Flow Example Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/agent/smart.md A workflow for adopting new APIs or libraries, including checking for existing dependencies, finding documentation, implementing according to patterns, and verifying with diagnostics and tests. ```markdown 1. Check package.json/cargo.toml/etc. to see if library exists 2. If not present, inform user (do not add dependencies without permission) 3. Use Librarian or websearch to find documentation 4. Implement following library patterns from docs 5. Verify with diagnostics and tests ``` -------------------------------- ### Perform CPU Profiling with Puppeteer Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/performance-guide.md This code demonstrates how to perform CPU profiling using Puppeteer. It enables the Profiler domain via CDP, starts profiling, navigates the page and performs interactions, stops profiling, and retrieves the profile data. The resulting profile data can be imported into Chrome DevTools for visualization as a flame graph. ```javascript // Start CPU profiling const client = await page.createCDPSession(); await client.send('Profiler.enable'); await client.send('Profiler.start'); // Navigate and interact await page.goto('https://example.com'); await page.click('.button'); // Stop profiling const { profile } = await client.send('Profiler.stop'); // Analyze profile (flame graph data) // Import into Chrome DevTools for visualization ``` -------------------------------- ### Initialize Browser Automation with Shared Library Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/SKILL.md Demonstrates how to import and utilize the project's shared browser utility library. This setup simplifies browser lifecycle management including initialization and cleanup. ```javascript import { getBrowser, getPage, closeBrowser, outputJSON } from './lib/browser.js'; // Your automation logic ``` -------------------------------- ### New Feature Flow Example Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/agent/smart.md A workflow for implementing new features, involving creating todos, searching for similar patterns, incremental implementation, and verification. ```markdown 1. Create todos for each step 2. Search for similar patterns in codebase 3. Implement incrementally, marking todos as completed 4. Run diagnostics and tests after each significant change 5. Consult Oracle if design decisions are unclear ``` -------------------------------- ### Run Lighthouse Performance Audit Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/performance-guide.md Launches a headless Chrome instance to run a Lighthouse performance audit on a target URL and logs key metrics like FCP, LCP, and TBT. ```javascript import lighthouse from 'lighthouse'; import { launch } from 'chrome-launcher'; const chrome = await launch({ chromeFlags: ['--headless'] }); const { lhr } = await lighthouse('https://example.com', { port: chrome.port, onlyCategories: ['performance'] }); console.log({ performanceScore: lhr.categories.performance.score * 100, metrics: { FCP: lhr.audits['first-contentful-paint'].displayValue, LCP: lhr.audits['largest-contentful-paint'].displayValue, TBT: lhr.audits['total-blocking-time'].displayValue, CLS: lhr.audits['cumulative-layout-shift'].displayValue, SI: lhr.audits['speed-index'].displayValue } }); await chrome.kill(); ``` -------------------------------- ### Install Puppeteer Dependencies Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/SKILL.md If encountering 'Cannot find package 'puppeteer'' errors, run `npm install` within the scripts directory. For Linux/WSL systems, ensure system dependencies are installed using the provided script or manual commands. ```bash npm install ``` ```bash ./install-deps.sh ``` ```bash sudo apt-get install -y libnss3 libnspr4 libasound2t64 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libgbm1 ``` -------------------------------- ### GitHub Grep - Code Search Across Repositories Source: https://context7.com/huynguyen03dev/opencode-setup/llms.txt Search real-world code examples across millions of GitHub repositories using grep.app. ```APIDOC ## GitHub Grep - Code Search Across Repositories ### Description Search real-world code examples across millions of GitHub repositories using grep.app. ### Find React useState usage patterns ### Method `bun` ### Endpoint `bun /path/to/skills/gh-grep/scripts/grep.ts searchGitHub --query "useState(" --language "TypeScript,TSX"` ### Find authentication patterns ### Method `bun` ### Endpoint `bun /path/to/skills/gh-grep/scripts/grep.ts searchGitHub --query "getServerSession" --language "TypeScript,TSX"` ### Find useEffect cleanup with regex ### Method `bun` ### Endpoint `bun /path/to/skills/gh-grep/scripts/grep.ts searchGitHub --query "(?s)useEffect\(\) => {.*removeEventListener" --use-regexp true` ### Search within specific repository ### Method `bun` ### Endpoint `bun /path/to/skills/gh-grep/scripts/grep.ts searchGitHub --query "createContext" --repo "facebook/react"` ### Case-sensitive search for CORS handling ### Method `bun` ### Endpoint `bun /path/to/skills/gh-grep/scripts/grep.ts searchGitHub --query "CORS(" --match-case true --language "Python"` ``` -------------------------------- ### Monitor Rendering Performance Metrics Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/performance-guide.md A collection of snippets to track layout shifts, paint metrics, frame rates, and layout recalculations. These tools help identify performance bottlenecks in the browser rendering pipeline. ```javascript // Layout Thrashing await page.evaluate(() => { return new Promise((resolve) => { const measurements = []; const observer = new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { if (entry.entryType === 'measure' && entry.name.includes('layout')) { measurements.push({ name: entry.name, duration: entry.duration, startTime: entry.startTime }); } }); }); observer.observe({ entryTypes: ['measure'] }); setTimeout(() => { observer.disconnect(); resolve(measurements); }, 5000); }); }); // Paint Metrics const paintMetrics = await page.evaluate(() => { const paints = performance.getEntriesByType('paint'); return { firstPaint: paints.find(p => p.name === 'first-paint')?.startTime, firstContentfulPaint: paints.find(p => p.name === 'first-contentful-paint')?.startTime }; }); // FPS Monitoring await page.evaluate(() => { return new Promise((resolve) => { let frames = 0; let lastTime = performance.now(); function countFrames() { frames++; requestAnimationFrame(countFrames); } countFrames(); setTimeout(() => { resolve(frames / ((performance.now() - lastTime) / 1000)); }, 5000); }); }); // CLS Tracking await page.evaluate(() => { return new Promise((resolve) => { const shifts = []; let totalCLS = 0; const observer = new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { if (!entry.hadRecentInput) { totalCLS += entry.value; shifts.push({ value: entry.value, time: entry.startTime }); } }); }); observer.observe({ entryTypes: ['layout-shift'] }); setTimeout(() => { observer.disconnect(); resolve({ totalCLS, shifts }); }, 10000); }); }); ``` -------------------------------- ### Identify Render-Blocking Resources Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/performance-guide.md Uses the Performance API to find CSS and non-async script files that block the browser's critical rendering path. ```javascript await page.goto('https://example.com'); const renderBlockingResources = await page.evaluate(() => { const resources = performance.getEntriesByType('resource'); return resources.filter(resource => { return (resource.initiatorType === 'link' && resource.name.includes('.css')) || (resource.initiatorType === 'script' && !resource.name.includes('async')); }).map(r => ({ url: r.name, duration: r.duration, startTime: r.startTime })); }); console.log('Render-blocking resources:', renderBlockingResources); ``` -------------------------------- ### Measure Core Web Vitals with chrome-devtools-mcp Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/performance-guide.md This snippet demonstrates how to measure Core Web Vitals (LCP, FID, CLS) using the 'chrome-devtools-mcp' tool. It involves starting a performance trace, navigating to a page, waiting for it to load, stopping the trace, and then obtaining AI-powered insights. ```javascript await useTool('performance_start_trace', { categories: ['loading', 'rendering', 'scripting'] }); await useTool('navigate_page', { url: 'https://example.com' }); await useTool('wait_for', { waitUntil: 'networkidle' }); await useTool('performance_stop_trace'); const insights = await useTool('performance_analyze_insight'); ``` -------------------------------- ### Bugfix Flow Example Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/agent/smart.md A standard workflow for addressing bugs, involving reproduction, root cause analysis using tools like grep and LSP, implementing a fix, and verification. ```markdown 1. Reproduce the bug (run failing test or trigger condition) 2. Locate root cause (grep/LSP references → read relevant code) 3. Implement minimal fix 4. Run lsp_diagnostics on changed files 5. Run targeted test to confirm fix 6. Run broader test suite if available ``` -------------------------------- ### Record Performance Trace with Puppeteer Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/performance-guide.md This Puppeteer code snippet illustrates how to record a performance trace. It starts tracing with specified categories, navigates to a URL, and then stops the tracing, saving the output to 'trace.json'. The trace file can be analyzed using Chrome's tracing tool. ```javascript await page.tracing.start({ path: 'trace.json', categories: [ 'devtools.timeline', 'disabled-by-default-devtools.timeline', 'disabled-by-default-v8.cpu_profiler' ] }); await page.goto('https://example.com', { waitUntil: 'networkidle2' }); await page.tracing.stop(); ``` -------------------------------- ### Start Performance Tracing with Tracing.start(categories) Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/cdp-domains.md Starts performance tracing, capturing detailed performance information. Requires `categories` to specify what to trace. Used in conjunction with `Tracing.end()` for performance analysis. ```javascript Tracing.start(categories) ``` -------------------------------- ### Rebuild and Reinstall Puppeteer Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/SKILL.md If Puppeteer encounters issues, such as problems launching the browser, try running `npm rebuild` followed by `npm install`. This can resolve issues related to the Puppeteer installation or its dependencies. ```bash npm rebuild npm install ``` -------------------------------- ### Refactor Flow Example Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/agent/smart.md A workflow for refactoring code, emphasizing understanding symbol usage with LSP, structural analysis with AST-grep, incremental edits, and verification with diagnostics and tests. ```markdown 1. Use lsp_find_references to understand symbol usage across codebase 2. Use ast_grep_search for structural variants the LSP might miss 3. Make incremental edits (one logical change at a time) 4. Run lsp_diagnostics after each change 5. Run tests after each cluster of related changes 6. Repeat until complete ``` -------------------------------- ### Fetch Library Documentation with Context7 Source: https://context7.com/huynguyen03dev/opencode-setup/llms.txt CLI commands to interact with the Context7 MCP service. Enables developers to resolve library IDs and retrieve targeted documentation or code examples for specific frameworks. ```bash bun /path/to/skills/context7/scripts/context7.ts resolve-library-id --library-name "react" bun /path/to/skills/context7/scripts/context7.ts get-library-docs --context7-compatible-library-i-d "/vercel/next.js" --topic "routing" ``` -------------------------------- ### Analyze JavaScript Bundle Sizes Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/performance-guide.md Monitors network responses to identify JavaScript files and calculate their size. It logs the file name, size in KB, and whether the content is gzipped. ```javascript page.on('response', async (response) => { const url = response.url(); const type = response.request().resourceType(); if (type === 'script') { const buffer = await response.buffer(); const size = buffer.length; console.log({ url: url.split('/').pop(), size: (size / 1024).toFixed(2) + ' KB', gzipped: response.headers()['content-encoding'] === 'gzip' }); } }); ``` -------------------------------- ### Retrieve Library Documentation with Context7 Source: https://context7.com/huynguyen03dev/opencode-setup/llms.txt Fetches API references or conceptual guides for specific libraries using the Context7 CLI tool. It requires a library ID and a specified mode (info or code). ```bash bun /path/to/skills/context7/scripts/context7.ts get-library-docs \ --context7-compatible-library-i-d "/mongodb/docs" --mode "info" ``` -------------------------------- ### Manually Install Chrome for Puppeteer Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/SKILL.md If Puppeteer fails to download Chrome automatically during installation, you can manually trigger the download using `npx puppeteer browsers install chrome`. This ensures the necessary browser is available for Puppeteer to use. ```bash npx puppeteer browsers install chrome ``` -------------------------------- ### Start Observing Background Services with BackgroundService.startObserving(service) Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/cdp-domains.md Initiates observation for a specified background service. Requires the `service` name (e.g., 'pushMessaging', 'notifications') to begin tracking its activity. ```javascript BackgroundService.startObserving(service) ``` -------------------------------- ### Define and Validate Performance Budgets Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/performance-guide.md Defines a configuration object for performance metrics and resource limits, and provides an asynchronous function to compare actual page metrics against these budgets. It returns a status object indicating whether the page passed the checks and lists any specific violations. ```javascript const budgets = { // Core Web Vitals LCP: 2500, // ms FID: 100, // ms CLS: 0.1, // score // Other metrics FCP: 1800, // ms TTI: 3800, // ms TBT: 300, // ms // Resource budgets totalPageSize: 2 * 1024 * 1024, // 2 MB jsSize: 500 * 1024, // 500 KB cssSize: 100 * 1024, // 100 KB imageSize: 1 * 1024 * 1024, // 1 MB // Request counts totalRequests: 50, jsRequests: 10, cssRequests: 5 }; async function checkBudgets(page, budgets) { // Measure actual values const vitals = await measureCoreWebVitals(page); const resources = await analyzeResources(page); // Compare against budgets const violations = []; if (vitals.LCP > budgets.LCP) { violations.push(`LCP: ${vitals.LCP}ms exceeds budget of ${budgets.LCP}ms`); } if (resources.totalSize > budgets.totalPageSize) { violations.push(`Page size: ${resources.totalSize} exceeds budget of ${budgets.totalPageSize}`); } // ... check other budgets return { passed: violations.length === 0, violations }; } ``` -------------------------------- ### Capture Heap Snapshot via CDP Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/performance-guide.md Utilizes the Chrome DevTools Protocol (CDP) to enable the Heap Profiler and capture a heap snapshot for memory analysis. ```javascript const client = await page.createCDPSession(); // Take snapshot await client.send('HeapProfiler.enable'); const { result } = await client.send('HeapProfiler.takeHeapSnapshot'); ``` -------------------------------- ### Retrieve Browser Memory Usage Metrics Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/performance-guide.md Captures memory heap statistics and DOM node counts. Supports both direct Puppeteer metrics and custom evaluation scripts for detailed heap analysis. ```javascript // Using chrome-devtools-mcp await useTool('evaluate_script', { expression: `({ usedJSHeapSize: performance.memory?.usedJSHeapSize, totalJSHeapSize: performance.memory?.totalJSHeapSize })`, returnByValue: true }); // Using Puppeteer const metrics = await page.metrics(); console.log({ jsHeapUsed: (metrics.JSHeapUsedSize / 1024 / 1024).toFixed(2) + ' MB', jsHeapTotal: (metrics.JSHeapTotalSize / 1024 / 1024).toFixed(2) + ' MB', domNodes: metrics.Nodes }); ``` -------------------------------- ### Automate Performance Testing in CI/CD Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/performance-guide.md Uses Puppeteer to launch a headless browser, navigate to a target URL, and collect performance metrics. The script compares these metrics against predefined thresholds and exits with an error code if the performance fails to meet the requirements. ```javascript import puppeteer from 'puppeteer'; async function performanceTest(url) { const browser = await puppeteer.launch(); const page = await browser.newPage(); // Measure metrics await page.goto(url, { waitUntil: 'networkidle2' }); const metrics = await page.metrics(); const vitals = await measureCoreWebVitals(page); await browser.close(); // Check against thresholds const thresholds = { LCP: 2500, FID: 100, CLS: 0.1, jsHeapSize: 50 * 1024 * 1024 // 50 MB }; const failed = []; if (vitals.LCP > thresholds.LCP) failed.push('LCP'); if (vitals.FID > thresholds.FID) failed.push('FID'); if (vitals.CLS > thresholds.CLS) failed.push('CLS'); if (metrics.JSHeapUsedSize > thresholds.jsHeapSize) failed.push('Memory'); if (failed.length > 0) { console.error('Performance test failed:', failed); process.exit(1); } console.log('Performance test passed'); } performanceTest(process.env.TEST_URL); ``` -------------------------------- ### Get Refactoring Suggestions with lsp_code_actions Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/agent/smart.md Retrieves available refactoring suggestions and code actions for a given code location, helping to improve code quality. ```python lsp_code_actions() ``` -------------------------------- ### Get Errors/Warnings with lsp_diagnostics Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/agent/smart.md Fetches errors and warnings reported by the language server before any build process is initiated, aiding in early bug detection. ```python lsp_diagnostics() ``` -------------------------------- ### Monitor Network Requests with chrome-devtools-mcp and Puppeteer Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/performance-guide.md This snippet demonstrates how to monitor network requests on a webpage. It covers navigating to a URL, waiting for network activity to settle, listing all requests with specified resource types, and retrieving detailed information for each request. It also shows how to capture requests and responses using Puppeteer's event listeners. ```javascript await useTool('navigate_page', { url: 'https://example.com' }); await useTool('wait_for', { waitUntil: 'networkidle' }); const requests = await useTool('list_network_requests', { resourceTypes: ['Document', 'Script', 'Stylesheet', 'Image', 'XHR', 'Fetch'], pageSize: 100 }); for (const req of requests.requests) { const details = await useTool('get_network_request', { requestId: req.id }); console.log({ url: details.url, method: details.method, status: details.status, size: details.encodedDataLength, time: details.timing.receiveHeadersEnd - details.timing.requestTime, cached: details.fromCache }); } ``` ```javascript const requests = []; page.on('request', (request) => { requests.push({ url: request.url(), method: request.method(), resourceType: request.resourceType(), headers: request.headers() }); }); page.on('response', (response) => { const request = response.request(); console.log({ url: response.url(), status: response.status(), size: response.headers()['content-length'], cached: response.fromCache(), timing: response.timing() }); }); await page.goto('https://example.com'); ``` -------------------------------- ### Detect Oversized Images Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/performance-guide.md Evaluates page images to identify those where natural dimensions exceed displayed dimensions by more than 50%, indicating a need for optimization. ```javascript const images = await page.evaluate(() => { const images = Array.from(document.querySelectorAll('img')); return images.map(img => ({ src: img.src, naturalWidth: img.naturalWidth, naturalHeight: img.naturalHeight, displayWidth: img.width, displayHeight: img.height, oversized: img.naturalWidth > img.width * 1.5 || img.naturalHeight > img.height * 1.5 })); }); const oversizedImages = images.filter(img => img.oversized); console.log('Oversized images:', oversizedImages); ``` -------------------------------- ### Common GitHub CLI Operations Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/github/SKILL.md Examples of common tasks including fetching file contents, creating issues, listing pull requests, searching code, and submitting PR reviews. ```bash # Get file contents bun /home/hazeruno/.config/opencode/skills/github/scripts/github.ts get-file-contents \ --owner facebook --repo react --path README.md # Create an issue bun /home/hazeruno/.config/opencode/skills/github/scripts/github.ts create-issue \ --owner myorg --repo myrepo --title "Bug report" --body "Description here" # List open PRs bun /home/hazeruno/.config/opencode/skills/github/scripts/github.ts list-pull-requests \ --owner facebook --repo react --state open # Search code bun /home/hazeruno/.config/opencode/skills/github/scripts/github.ts search-code \ --q "useState filename:*.tsx" # Create a PR review bun /home/hazeruno/.config/opencode/skills/github/scripts/github.ts create-pull-request-review \ --owner myorg --repo myrepo --pull-number 123 \ --body "LGTM!" --event APPROVE ``` -------------------------------- ### Configure Screenshot Compression and Format Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/SKILL.md To manage large screenshot files, you can configure compression and format settings. Install ImageMagick for automatic compression, or manually specify options like `--max-size`, `--format`, and `--quality` to control file size and type. ```bash # Verify ImageMagick installation magick -version convert -version ``` ```bash node screenshot.js --url https://example.com --max-size 3 --format jpeg --quality 80 ``` ```bash node screenshot.js --url https://example.com --selector ".main-content" ``` -------------------------------- ### Simulate Slow Network Connection Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/performance-guide.md This code demonstrates how to simulate different network conditions, such as slow 3G or 4G connections. It shows how to use chrome-devtools-mcp's 'emulate_network' tool and Puppeteer's CDP session to configure download/upload throughput and latency. ```javascript // Using chrome-devtools-mcp await useTool('emulate_network', { throttlingOption: 'Slow 3G' // or 'Fast 3G', 'Slow 4G' }); // Using Puppeteer const client = await page.createCDPSession(); await client.send('Network.emulateNetworkConditions', { offline: false, downloadThroughput: 400 * 1024 / 8, // 400 Kbps uploadThroughput: 400 * 1024 / 8, latency: 2000 // 2000ms RTT }); ``` -------------------------------- ### Handle Hover, Focus, and Blur Events in JavaScript Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/puppeteer-reference.md Provides examples for simulating user interactions such as hovering over an element, focusing on an input field, and blurring an element using JavaScript. ```javascript // Hover over element await page.hover('.menu-item'); // Focus element await page.focus('#input'); // Blur await page.$eval('#input', el => el.blur()); ``` -------------------------------- ### Ask Question About Repository Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/deep-wiki/SKILL.md Pose a question about a specific GitHub repository and receive an AI-generated answer. This command is useful for getting targeted information about a codebase without manually searching through the source code. ```bash bun /home/hazeruno/.config/opencode/skills/deep-wiki/scripts/deepwiki.ts ask-question \ --repo-name "prisma/prisma" --question "How does the query engine work?" ``` -------------------------------- ### Get Repository Wiki Structure Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/deep-wiki/SKILL.md Retrieve a list of available documentation topics for a specified GitHub repository. This command helps in understanding the scope of documentation available for a project before diving deeper. ```bash bun /home/hazeruno/.config/opencode/skills/deep-wiki/scripts/deepwiki.ts read-wiki-structure --repo-name "facebook/react" ``` -------------------------------- ### Get Browser Command Line Arguments with Browser.getBrowserCommandLine() Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/cdp-domains.md Retrieves the command-line arguments used to launch the browser. This is useful for understanding the browser's startup configuration and any custom flags that might be active. ```javascript Browser.getBrowserCommandLine() ``` -------------------------------- ### Calculate Total Page Weight and Resource Counts Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/performance-guide.md This script calculates the total size of all resources loaded on a webpage and counts the number of resources by their type. It uses Puppeteer's 'response' event listener to capture the content of each response, sum their lengths, and categorize them by resource type. ```javascript let totalBytes = 0; let resourceCounts = {}; page.on('response', async (response) => { const type = response.request().resourceType(); const buffer = await response.buffer(); totalBytes += buffer.length; resourceCounts[type] = (resourceCounts[type] || 0) + 1; }); await page.goto('https://example.com'); console.log('Total size:', (totalBytes / 1024 / 1024).toFixed(2), 'MB'); console.log('Resources:', resourceCounts); ``` -------------------------------- ### Measure Core Web Vitals with Puppeteer Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/performance-guide.md This code uses Puppeteer to measure Core Web Vitals (LCP, FID, CLS) by leveraging the PerformanceObserver API. It navigates to a URL, sets up observers for each metric, and collects the data after a short delay. The measured vitals are then logged to the console. ```javascript import puppeteer from 'puppeteer'; const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://example.com', { waitUntil: 'networkidle2' }); const vitals = await page.evaluate(() => { return new Promise((resolve) => { const vitals = { LCP: null, FID: null, CLS: 0 }; new PerformanceObserver((list) => { const entries = list.getEntries(); vitals.LCP = entries[entries.length - 1].renderTime || entries[entries.length - 1].loadTime; }).observe({ entryTypes: ['largest-contentful-paint'] }); new PerformanceObserver((list) => { vitals.FID = list.getEntries()[0].processingStart - list.getEntries()[0].startTime; }).observe({ entryTypes: ['first-input'] }); new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { if (!entry.hadRecentInput) { vitals.CLS += entry.value; } }); }).observe({ entryTypes: ['layout-shift'] }); setTimeout(() => resolve(vitals), 5000); }); }); console.log('Core Web Vitals:', vitals); ``` -------------------------------- ### Get Document Root with DOM.getDocument() Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/cdp-domains.md Retrieves the root document node. This command is essential for starting any DOM inspection or manipulation, providing the entry point to the document's structure. ```javascript DOM.getDocument() ``` -------------------------------- ### Identify Unused Code Coverage with Puppeteer Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/performance-guide.md Measures the amount of unused JavaScript and CSS code on a page. It starts coverage tracking, navigates to a URL, stops tracking, and calculates the percentage of unused bytes. ```javascript // Start coverage await Promise.all([ page.coverage.startJSCoverage(), page.coverage.startCSSCoverage() ]); // Navigate await page.goto('https://example.com'); // Stop coverage const [jsCoverage, cssCoverage] = await Promise.all([ page.coverage.stopJSCoverage(), page.coverage.stopCSSCoverage() ]); // Calculate unused bytes function calculateUnusedBytes(coverage) { let usedBytes = 0; let totalBytes = 0; for (const entry of coverage) { totalBytes += entry.text.length; for (const range of entry.ranges) { usedBytes += range.end - range.start - 1; } } return { usedBytes, totalBytes, unusedBytes: totalBytes - usedBytes, unusedPercentage: ((totalBytes - usedBytes) / totalBytes * 100).toFixed(2) }; } console.log('JS Coverage:', calculateUnusedBytes(jsCoverage)); console.log('CSS Coverage:', calculateUnusedBytes(cssCoverage)); ``` -------------------------------- ### Query and Modify DOM Elements using JavaScript Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/puppeteer-reference.md Provides examples for interacting with the Document Object Model (DOM) using JavaScript. This includes getting element properties, retrieving multiple elements, modifying element values, and adding CSS classes to elements. ```javascript // Get element property const value = await page.$eval('#input', el => el.value); // Get multiple elements const items = await page.$$eval('.item', elements => elements.map(el => el.textContent) ); // Modify element await page.$eval('#input', (el, value) => { el.value = value; }, 'new value'); // Add class await page.$eval('.element', el => el.classList.add('active')); ``` -------------------------------- ### Basic Puppeteer Usage Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/puppeteer-reference.md Demonstrates the fundamental steps for launching a browser, opening a new page, navigating to a URL, performing actions, and closing the browser using Puppeteer. ```javascript import puppeteer from 'puppeteer'; // Launch browser const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox'] }); // Open page const page = await browser.newPage(); // Navigate await page.goto('https://example.com'); // Do work... // Cleanup await browser.close(); ``` -------------------------------- ### Identify Slow Network Requests Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/performance-guide.md This code snippet identifies network requests that take longer than a specified threshold (1 second in this example). It uses Puppeteer's 'response' event listener to access response timing information and logs details of slow requests, including their URL, time taken, and size. ```javascript page.on('response', (response) => { const timing = response.timing(); const totalTime = timing.receiveHeadersEnd - timing.requestTime; if (totalTime > 1000) { // Slower than 1 second console.log('Slow request:', { url: response.url(), time: totalTime.toFixed(2) + 'ms', size: response.headers()['content-length'] }); } }); ``` -------------------------------- ### Parallel Execution Guidance Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/agent/smart.md Guidelines for launching multiple tool calls in parallel when there are no dependencies between them, such as reading multiple files or searching different patterns simultaneously. Emphasizes the critical rule against parallel edits to the same file. ```markdown Launch multiple tool calls in parallel when no dependencies: - Reading related files simultaneously - Searching different patterns at once - Checking multiple diagnostics CRITICAL SAFETY RULE: Do NOT make multiple edits to the same file in parallel. If operations have logical dependencies, wait for the first to complete before starting the next. ``` -------------------------------- ### Execute Sequential Thinking Processes Source: https://context7.com/huynguyen03dev/opencode-setup/llms.txt Demonstrates how to initialize, continue, revise, branch, and complete a sequential thinking process using the Bun runtime. These commands manage the state of a multi-step analytical workflow. ```bash bun ~/.config/opencode/skills/sequential-thinking/scripts/sequential-thinking.ts sequentialthinking \ --thought "Initial analysis of the problem..." \ --thought-number 1 \ --total-thoughts 5 \ --next-thought-needed true bun ~/.config/opencode/skills/sequential-thinking/scripts/sequential-thinking.ts sequentialthinking \ --thought "Building on insight from step 1..." \ --thought-number 2 \ --total-thoughts 5 \ --next-thought-needed true bun ~/.config/opencode/skills/sequential-thinking/scripts/sequential-thinking.ts sequentialthinking \ --thought "Reconsidering step 2, I realize..." \ --thought-number 4 \ --total-thoughts 6 \ --is-revision true \ --revises-thought 2 \ --next-thought-needed true bun ~/.config/opencode/skills/sequential-thinking/scripts/sequential-thinking.ts sequentialthinking \ --thought "Alternative approach from step 3..." \ --thought-number 5 \ --total-thoughts 7 \ --branch-from-thought 3 \ --branch-id "alternative-approach" \ --next-thought-needed true bun ~/.config/opencode/skills/sequential-thinking/scripts/sequential-thinking.ts sequentialthinking \ --thought "Final verified conclusion..." \ --thought-number 6 \ --total-thoughts 6 \ --next-thought-needed false ``` -------------------------------- ### Get File Structure with lsp_document_symbols Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/agent/smart.md Retrieves an outline of the symbols (functions, classes, variables) defined within a specific file. ```python lsp_document_symbols() ``` -------------------------------- ### Get Type/Documentation with lsp_hover Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/agent/smart.md The lsp_hover tool retrieves type information and documentation for a symbol at a specific position within the code. ```python lsp_hover() ``` -------------------------------- ### Emulate Devices and Viewports Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/puppeteer-reference.md Demonstrates how to simulate mobile devices using predefined profiles, custom viewport configurations, and user-agent strings. Includes methods for setting geolocation, timezone, and locale settings. ```javascript import { devices } from 'puppeteer'; const iPhone = devices['iPhone 13 Pro']; await page.emulate(iPhone); await page.emulate({ viewport: { width: 375, height: 812, deviceScaleFactor: 3, isMobile: true, hasTouch: true, isLandscape: false }, userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X)...' }); await page.setViewport({ width: 1920, height: 1080, deviceScaleFactor: 1 }); await page.setGeolocation({ latitude: 37.7749, longitude: -122.4194, accuracy: 100 }); await page.emulateTimezone('America/New_York'); ``` -------------------------------- ### Get References Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/gkg/references/api_reference.md Finds all references (usages) to a specific code definition within a project. Supports pagination. ```APIDOC ## get-references ### Description Find all references to a code definition. ### Method GET ### Endpoint /get-references ### Parameters #### Query Parameters - **absolute-file-path** (string) - Required - Path to file containing the definition - **definition-name** (string) - Required - Exact symbol name (case-sensitive) - **page** (integer) - Optional - Page number (default: 1) ### Response #### Success Response (200) - **references** (array) - List of references, including file paths, line numbers, and context. #### Response Example ```json { "references": [ { "file": "/path/to/usage.ts", "line": 25, "context": "const result = myFunction();" } ] } ``` ``` -------------------------------- ### External Documentation Lookup with Librarian Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/agent/smart.md The 'librarian' subagent is used for external documentation lookup, finding implementation examples in other repositories, multi-repository analysis, and understanding library internals. ```python call_omo_agent(subagent_type="librarian") ``` -------------------------------- ### Load Specialized Knowledge with Skills Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/agent/smart.md Load specialized knowledge from the ~/.opencode/skills directory to enhance agent capabilities. ```shell skill: Load specialized knowledge from ~/.opencode/skills ``` -------------------------------- ### Monitor Font Loading Status Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/performance-guide.md Checks the status of all loaded fonts on the page to identify if any are failing to load or are currently in a non-loaded state. ```javascript const fonts = await page.evaluate(() => { return Array.from(document.fonts).map(font => ({ family: font.family, weight: font.weight, style: font.style, status: font.status, loaded: font.status === 'loaded' })); }); console.log('Fonts:', fonts); ``` -------------------------------- ### Get Definition Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/gkg/references/api_reference.md Resolves the definition location for callable symbols found on a specific line in a file. Returns either a `Definition` object or an `ImportedSymbol` object. ```APIDOC ## get-definition ### Description Go to definition for callable symbols on a line. ### Method GET ### Endpoint /get-definition ### Parameters #### Query Parameters - **absolute-file-path** (string) - Required - Path to file with the usage - **line** (integer) - Required - Exact line of code (whitespace preserved) - **symbol-name** (string) - Required - Symbol to resolve ### Response #### Success Response (200) - **definition** (object) - Details of the symbol's definition or import statement. - **type** (string) - "Definition" or "ImportedSymbol" - **location** (object) - Location details if type is "Definition" - **import_statement** (string) - The import statement if type is "ImportedSymbol" #### Response Example (Definition) ```json { "definition": { "type": "Definition", "location": { "file": "/path/to/definition.ts", "line": 50 } } } ``` #### Response Example (ImportedSymbol) ```json { "definition": { "type": "ImportedSymbol", "import_statement": "import { React } from 'react';" } } ``` ``` -------------------------------- ### Execute GitHub MCP CLI Commands Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/github/SKILL.md Demonstrates how to invoke the GitHub MCP CLI script using the Bun runtime. Requires the GITHUB_TOKEN environment variable for authentication. ```bash bun /home/hazeruno/.config/opencode/skills/github/scripts/github.ts [options] ``` -------------------------------- ### Measure Third-Party Script Impact Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/performance-guide.md Intercepts network responses to track the size and resource type of requests originating from specific third-party domains. ```javascript const thirdPartyDomains = ['googletagmanager.com', 'facebook.net', 'doubleclick.net']; page.on('response', async (response) => { const url = response.url(); const isThirdParty = thirdPartyDomains.some(domain => url.includes(domain)); if (isThirdParty) { const buffer = await response.buffer(); console.log({ url: url, size: (buffer.length / 1024).toFixed(2) + ' KB', type: response.request().resourceType() }); } }); ``` -------------------------------- ### Execute Sequential Thinking CLI Commands Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/sequential-thinking/SKILL.md Demonstrates the core workflow for the sequential-thinking script, including initialization, sequence continuation, revision of previous thoughts, branching exploration, and completion. These commands require the Bun runtime and target the sequential-thinking.ts script. ```bash # Initialize bun ~/.config/opencode/skills/sequential-thinking/scripts/sequential-thinking.ts sequentialthinking \ --thought "Initial analysis of the problem..." \ --thought-number 1 \ --total-thoughts 5 \ --next-thought-needed true # Continue bun ~/.config/opencode/skills/sequential-thinking/scripts/sequential-thinking.ts sequentialthinking \ --thought "Building on insight from step 1..." \ --thought-number 2 \ --total-thoughts 5 \ --next-thought-needed true # Revise bun ~/.config/opencode/skills/sequential-thinking/scripts/sequential-thinking.ts sequentialthinking \ --thought "Reconsidering step 2, I realize..." \ --thought-number 4 \ --total-thoughts 6 \ --is-revision true \ --revises-thought 2 \ --next-thought-needed true # Branch bun ~/.config/opencode/skills/sequential-thinking/scripts/sequential-thinking.ts sequentialthinking \ --thought "Alternative approach from step 3..." \ --thought-number 5 \ --total-thoughts 7 \ --branch-from-thought 3 \ --branch-id "alternative-approach" \ --next-thought-needed true # Complete bun ~/.config/opencode/skills/sequential-thinking/scripts/sequential-thinking.ts sequentialthinking \ --thought "Final verified conclusion..." \ --thought-number 6 \ --total-thoughts 6 \ --next-thought-needed false ``` -------------------------------- ### Web Access Tools Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/agent/smart.md Tools for fetching content from the web and performing web searches. ```shell webfetch ``` ```shell websearch ``` -------------------------------- ### Get Cookies with Network.getCookies(urls) Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/cdp-domains.md Retrieves cookies associated with the specified URLs. Requires an array of `urls`. Useful for inspecting or managing cookie data. ```javascript Network.getCookies(urls) ``` -------------------------------- ### Launch Puppeteer Browser with Options Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/puppeteer-reference.md Configures and launches a Puppeteer browser instance with various options for headless mode, Chrome executable path, user data directory, viewport size, arguments, debugging, and network proxy. ```javascript const browser = await puppeteer.launch({ // Visibility headless: false, // Show browser UI headless: 'new', // New headless mode (Chrome 112+) // Chrome location executablePath: '/path/to/chrome', channel: 'chrome', // or 'chrome-canary', 'chrome-beta' // Browser context userDataDir: './user-data', // Persistent profile // Window size defaultViewport: { width: 1920, height: 1080, deviceScaleFactor: 1, isMobile: false }, // Advanced options args: [ '--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-web-security', '--disable-features=IsolateOrigins', '--disable-site-isolation-trials', '--start-maximized' ], // Debugging devtools: true, // Open DevTools automatically slowMo: 250, // Slow down by 250ms per action // Network proxy: { server: 'http://proxy.com:8080' } }); ``` -------------------------------- ### View Repository Wiki Contents Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/deep-wiki/SKILL.md Display the complete AI-generated documentation for a given GitHub repository. This command provides a comprehensive overview of the project's documentation. ```bash bun /home/hazeruno/.config/opencode/skills/deep-wiki/scripts/deepwiki.ts read-wiki-contents --repo-name "vercel/next.js" ``` -------------------------------- ### Manage GitHub Repositories and Pull Requests Source: https://context7.com/huynguyen03dev/opencode-setup/llms.txt Facilitates interaction with GitHub, including fetching file contents, managing issues, listing pull requests, and performing PR reviews. Requires repository owner and name parameters. ```bash bun /path/to/skills/github/scripts/github.ts get-file-contents --owner facebook --repo react --path README.md bun /path/to/skills/github/scripts/github.ts create-issue --owner myorg --repo myrepo --title "Bug report" --body "Description here" bun /path/to/skills/github/scripts/github.ts list-pull-requests --owner facebook --repo react --state open bun /path/to/skills/github/scripts/github.ts search-code --q "useState filename:*.tsx" bun /path/to/skills/github/scripts/github.ts create-pull-request-review --owner myorg --repo myrepo --pull-number 123 --body "LGTM!" --event APPROVE bun /path/to/skills/github/scripts/github.ts merge-pull-request --owner myorg --repo myrepo --pull-number 123 ``` -------------------------------- ### Get Performance Metrics with Performance.getMetrics() Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/cdp-domains.md Retrieves performance metrics for the current page. This command provides insights into various performance aspects, such as navigation timing and rendering. ```javascript Performance.getMetrics() ``` -------------------------------- ### Verify Screenshot File Creation Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/SKILL.md After capturing a screenshot, verify its creation and inspect its properties using the `ls -lh` command. This step ensures the file exists and provides basic information about its size. ```bash node screenshot.js --url https://example.com --output ./docs/screenshots/page.png ls -lh ./docs/screenshots/page.png # Verify file exists ``` -------------------------------- ### Get Browser Version with Browser.getVersion() Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/references/cdp-domains.md Fetches information about the browser, including its version. This command requires no arguments and provides essential details for compatibility checks or logging. ```javascript Browser.getVersion() ``` -------------------------------- ### Manage Custom Skill Lifecycle Source: https://context7.com/huynguyen03dev/opencode-setup/llms.txt Provides commands to initialize and package custom skills for the OpenCode environment. It outlines the required directory structure including metadata and bundled resources. ```bash # Initialize a new skill python scripts/init_skill.py --path # Package a skill for distribution python scripts/package_skill.py # Package with custom output directory python scripts/package_skill.py ./dist ``` -------------------------------- ### Conduct Performance Testing and Analyze LCP Source: https://github.com/huynguyen03dev/opencode-setup/blob/main/skills/chrome-devtools/SKILL.md Use the `performance.js` script to gather performance metrics for a given URL. The output, typically JSON, can be parsed using `jq` to extract specific metrics like Largest Contentful Paint (LCP) for analysis. ```bash PERF=$(node performance.js --url https://example.com) LCP=$(echo $PERF | jq '.vitals.LCP') if (( $(echo "$LCP < 2500" | bc -l) )); then echo "✓ LCP passed: ${LCP}ms" else echo "✗ LCP failed: ${LCP}ms" fi ```