### k6 Studio Development Setup Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/README.md Clone the repository, set up the correct Node.js version using nvm, install dependencies with pnpm, and start the development server. ```bash git clone https://github.com/grafana/k6-studio.git cd k6-studio nvm use # Node 24.11.0 pnpm install pnpm start ``` -------------------------------- ### Example Development Setup Configuration Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/configuration.md An example configuration file for a development setup, demonstrating overrides for proxy, recorder, and telemetry settings. This configuration takes precedence over settings.json. ```json { "proxy": { "host": "127.0.0.1", "port": 9090, "ignoreHosts": ["localhost", "127.0.0.1"] }, "recorder": { "captureScreenshots": true, "bodySize": 5000000 }, "telemetry": { "usageReport": false, "errorReport": false } } ``` -------------------------------- ### Start Grafana k6 Studio Locally Source: https://github.com/grafana/k6-studio/blob/main/README.md Start the Grafana k6 Studio application locally after installing dependencies. This command runs the development server. ```bash pnpm start ``` -------------------------------- ### Example settings.json Configuration Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/configuration.md Provides a complete example of a settings.json file, illustrating the structure and possible values for proxy, recorder, telemetry, and window state settings. ```json { "proxy": { "enabled": true, "host": "127.0.0.1", "port": 8080, "ignoreHosts": [] }, "recorder": { "captureScreenshots": false, "captureBody": true, "bodySize": 1000000 }, "telemetry": { "usageReport": true, "errorReport": true, "userId": "550e8400-e29b-41d4-a716-446655440000" }, "windowState": { "width": 1200, "height": 800, "x": 0, "y": 0 }, "browserExecutablePath": "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "upstreamCertificatePath": null } ``` -------------------------------- ### launchProxy() Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/proxy-api.md Starts the proxy server and begins capturing network traffic. It resolves when the proxy has started successfully or rejects if initialization fails. ```APIDOC ## launchProxy() ### Description Starts the proxy server and begins capturing network traffic. ### Method `function` ### Parameters None ### Returns `Promise` - Resolves when proxy has started successfully. ### Throws Rejects if proxy initialization fails (port already in use, missing binary, etc.). ### Example ```typescript import { launchProxy } from 'window.studio.proxy' try { await studio.proxy.launchProxy() console.log('Proxy started') } catch (error) { console.error('Failed to start proxy:', error) } ``` ``` -------------------------------- ### Example Proxy Configuration Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/configuration.md An example of how to configure the proxy settings in a JSON file. This includes enabling the proxy, setting host and port, and specifying hosts to ignore. ```json { "proxy": { "enabled": true, "host": "127.0.0.1", "port": 8080, "ignoreHosts": ["localhost", "127.0.0.1", "*.internal"], "upstreamProxy": "http://corporate-proxy.example.com:3128" } } ``` -------------------------------- ### Create Installable Artifacts for Grafana k6 Studio Source: https://github.com/grafana/k6-studio/blob/main/README.md Generate installable artifacts such as .deb and .rpm packages for Grafana k6 Studio. This command is used when installable artifacts are desired instead of just a packaged app directory. ```bash pnpm make ``` -------------------------------- ### Migrate Settings Function Example Source: https://github.com/grafana/k6-studio/blob/main/src/schemas/settings/README.md Implement a migration function to convert settings from a previous version to the latest schema. This example shows how to handle version '2.0' by calling a specific migration function. ```typescript function migrate(settings: z.infer) { case '2.0': return migrate(v2.migrate(settings)) } ``` -------------------------------- ### Install Project Dependencies with pnpm Source: https://github.com/grafana/k6-studio/blob/main/README.md Install all necessary project dependencies using pnpm. This command should be run after cloning the repository and switching to the correct Node.js version. ```bash pnpm install ``` -------------------------------- ### Start HTTP Proxy Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/INDEX.md Launches the HTTP proxy server. This is a prerequisite for recording browser traffic. ```javascript studio.proxy.launchProxy() ``` -------------------------------- ### Think Time Configuration Examples Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/configuration.md Illustrates TypeScript interfaces and examples for configuring think time between requests, including 'none', 'uniform', and 'exponential' types with optional values. ```typescript interface ThinkTime { type: 'uniform' | 'exponential' | 'none' value?: number // milliseconds } // No think time { type: 'none' } // Fixed 1 second delay { type: 'uniform', value: 1000 } // Exponential distribution, mean 500ms { type: 'exponential', value: 500 } ``` -------------------------------- ### Run Development Server and Linters Source: https://github.com/grafana/k6-studio/blob/main/CLAUDE.md Commands for starting the development server, running linters, and performing type checks. ```bash pnpm start # start dev server (electron-forge) pnpm lint # eslint pnpm typecheck # tsc --noEmit ``` -------------------------------- ### ParameterizationRule Example Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/types.md An example of a parameterization rule that sets a session ID. ```typescript { id: 'rule-2', type: 'parameterization', enabled: true, value: { code: 'sessionId = "123"', inlineCode: 'sessionId' }, selector: { type: 'query', name: 'sid' } } ``` -------------------------------- ### Conventional Commits Examples Source: https://github.com/grafana/k6-studio/blob/main/CLAUDE.md Examples of commit messages following the Conventional Commits format. ```bash feat: Add type column to WebLogView fix: Application crashes when opening HAR file ``` -------------------------------- ### Get All Files and Subscribe to Add/Remove Events Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/utility-apis.md Demonstrates how to fetch all script files and subscribe to real-time additions and removals of files within the Studio environment. ```typescript // Get all files const files = await studio.ui.getFiles() // Subscribe to file changes studio.ui.onAddFile((file) => { console.log('New file:', file.fileName) }) studio.ui.onRemoveFile((file) => { console.log('Deleted:', file.fileName) }) ``` -------------------------------- ### Switch Node.js Version with nvm Source: https://github.com/grafana/k6-studio/blob/main/README.md If using nvm, switch to a compatible Node.js version before proceeding with the setup. ```bash nvm use ``` -------------------------------- ### Browser Event Example Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/browser-api.md An example of a 'click' BrowserEvent. This demonstrates the typical fields included for a click interaction. ```typescript { type: 'click', timestamp: 1623456789000, selector: 'button[type="submit"]' } ``` -------------------------------- ### Example Simple Load Test Options Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/configuration.md Shows a JSON configuration for a simple load test, specifying the number of virtual users and the test duration. This is equivalent to k6's 'options' export. ```json { "vus": 50, "duration": "5m" } ``` -------------------------------- ### Listen for Script Execution Start Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/script-api.md Registers a callback function to be invoked when a k6 script execution begins. This is useful for triggering actions or updating UI elements upon test start. ```typescript studio.script.onScriptStarted(() => { console.log('Test started') }) ``` -------------------------------- ### Launch Browser with Proxy Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/INDEX.md Starts a browser instance configured to use the specified proxy URL. Essential for capturing network requests. ```javascript studio.browser.launchBrowser({ proxyUrl: '...' }) ``` -------------------------------- ### Development Commands for k6 Studio Source: https://github.com/grafana/k6-studio/blob/main/AGENTS.md Common pnpm commands for starting the dev server, linting, type checking, testing, and formatting the k6 Studio project. ```bash pnpm start # start dev server (electron-forge) ``` ```bash pnpm lint # eslint ``` ```bash pnpm typecheck # tsc --noEmit ``` ```bash pnpm test # vitest run ``` ```bash pnpm test:watch # vitest watch ``` ```bash pnpm format # prettier ``` -------------------------------- ### Example k6 Script Output Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/generator-api.md An example of the JavaScript/k6 code generated by the `generateScript` function. This script includes basic HTTP requests and checks. ```javascript import http from 'k6/http' import { check, group } from 'k6' export const options = { vus: 10, duration: '30s' } const VARS = { "BASE_URL": "https://example.com" } export default function() { let response = http.get(__ENV.BASE_URL + '/api/users') check(response, { 'status is 200': (r) => r.status === 200 }) } ``` -------------------------------- ### CorrelationRule Example Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/types.md An example demonstrating how to configure a correlation rule to extract an access token from a JSON response and use it in the Authorization header. ```typescript { id: 'rule-1', type: 'correlation', enabled: true, extractors: [ { selector: { type: 'json', path: '$.access_token' }, from: 'response' } ], replacers: [ { selector: { type: 'header', name: 'Authorization' } } ], variable: { name: 'TOKEN', type: 'value' } } ``` -------------------------------- ### Example of GroupedProxyData Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/types.md Illustrates how ProxyData objects can be organized into groups. ```typescript const grouped = { 'auth': [request1, request2], 'checkout': [request3, request4] } ``` -------------------------------- ### VerificationRule Example Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/types.md An example of a verification rule that checks if the response status is 200 or 201. ```typescript { id: 'rule-3', type: 'verification', enabled: true, checks: [ { description: 'Status is 200', expression: 'r => r.status === 200' } ], selector: { statusCodes: [200, 201] } } ``` -------------------------------- ### Launch Proxy Server Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/proxy-api.md Starts the proxy server to capture network traffic. Ensure no other process is using the default port. ```typescript import { launchProxy } from 'window.studio.proxy' try { await studio.proxy.launchProxy() console.log('Proxy started') } catch (error) { console.error('Failed to start proxy:', error) } ``` -------------------------------- ### Get Application Settings Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/INDEX.md Loads the current application configuration. Use this to access or inspect existing settings. ```javascript studio.settings.getSettings() ``` -------------------------------- ### Launch and Monitor Proxy Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/INDEX.md Starts the proxy server, retrieves its status, and logs captured network requests. Ensure the proxy module is imported. ```typescript await studio.proxy.launchProxy() const status = await studio.proxy.getProxyStatus() studio.proxy.onProxyData((data) => { console.log(`Captured: ${data.request.method} ${data.request.url}`) }) ``` -------------------------------- ### Get Settings Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/settings-api.md Retrieves the current application settings. This includes proxy, recorder, telemetry, and window state configurations. ```APIDOC ## Get Settings ### Description Retrieves the current application settings. ### Method GET (or equivalent SDK call) ### Endpoint `/settings` (conceptual, actual call via SDK) ### Parameters None ### Request Example ```typescript const settings = await studio.settings.getSettings() ``` ### Response #### Success Response (200) - **proxy** (ProxySettings) - HTTP proxy configuration. - **recorder** (RecorderSettings) - Browser recording configuration. - **telemetry** (TelemetrySettings) - Usage tracking and error reporting settings. - **windowState** (WindowState) - Application window size and position. #### Response Example ```json { "proxy": { "enabled": true, "host": "127.0.0.1", "port": 8080, "ignoreHosts": [], "upstreamProxy": null }, "recorder": { "captureScreenshots": false, "captureBody": true }, "telemetry": { "usageReport": true, "errorReport": true }, "windowState": { "width": 1200, "height": 800, "x": 0, "y": 0 } } ``` ``` -------------------------------- ### Example Staged Load Profile Options Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/configuration.md A JSON configuration for a staged load profile, defining multiple stages with specific durations and target virtual user counts. This allows for complex load testing scenarios. ```json { "stages": [ { "duration": "2m", "target": 100 }, { "duration": "5m", "target": 100 }, { "duration": "2m", "target": 0 } ] } ``` -------------------------------- ### Setting Environment Variables on macOS/Linux Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/configuration.md Demonstrates how to set k6 environment variables and the HTTP proxy variable using the 'export' command before starting K6 Studio. ```bash export K6_VUS=100 export K6_DURATION=10m export HTTP_PROXY=http://proxy:3128 pnpm start ``` -------------------------------- ### Example Test Options Configuration Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/generator-api.md Defines configuration for k6 test execution, including virtual users, duration, and think time. This structure is used within the generator configuration. ```typescript const options = { vus: 50, duration: '5m', thinkTime: { type: 'uniform', value: 1000 } } ``` -------------------------------- ### Configure Proxy Settings Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/settings-api.md Set detailed proxy configurations including host, port, ignored hosts, and an upstream proxy for corporate environments. This example demonstrates how to retrieve, modify, and save the proxy settings. ```typescript const settings = await studio.settings.getSettings() settings.proxy = { enabled: true, host: '127.0.0.1', port: 9090, ignoreHosts: ['localhost', '127.0.0.1'], upstreamProxy: 'http://corporate-proxy:3128' } await studio.settings.saveSettings(settings) ``` -------------------------------- ### Get Application Settings Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/settings-api.md Retrieves the current application settings. Use this to read configuration values. ```typescript import { getSettings } from 'window.studio.settings' const settings = await studio.settings.getSettings() console.log('Proxy enabled:', settings.proxy.enabled) console.log('Window size:', settings.windowState.width, 'x', settings.windowState.height) ``` -------------------------------- ### signIn() Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/auth-api.md Initiates the OAuth sign-in flow with Grafana Cloud. This function starts the process for authenticating the user. ```APIDOC ## signIn() ### Description Initiates OAuth sign-in flow with Grafana Cloud. ### Method `signIn` ### Parameters None ### Returns `Promise` - Result of sign-in attempt. The `SignInResult` object contains a `success` boolean, an optional array of `StackInfo` objects if successful, and an optional `error` string if the sign-in failed. ### Throws Rejects on network errors or cancellation. ### Example ```typescript import { signIn } from 'window.studio.auth' try { const result = await studio.auth.signIn() if (result.success && result.stacks) { console.log('Sign in successful') console.log('Available stacks:', result.stacks.map(s => s.name)) } else { console.error('Sign in failed:', result.error) } } catch (error) { console.error('Sign in error:', error) } ``` ``` -------------------------------- ### Local Development Configuration Override Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/configuration.md Shows an example of a settings.local.json file used to override specific default settings for local development. This file is not tracked by git. ```json { "proxy": { "port": 9090 }, "telemetry": { "usageReport": false, "errorReport": false } } ``` -------------------------------- ### Handle Browser Launch Errors Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/README.md Listen for browser launch errors. If the browser is not found, consider installing Chrome/Chromium or specifying the `browserExecutablePath`. ```typescript studio.browser.onBrowserLaunchError((error) => { if (error.reason === 'BROWSER_NOT_FOUND') { // Install Chrome/Chromium or set browserExecutablePath } }) ``` -------------------------------- ### Package Grafana k6 Studio Application Source: https://github.com/grafana/k6-studio/blob/main/README.md Compile a local packaged build of the Grafana k6 Studio application. This command should be run after setting the required environment variables and installing dependencies. ```bash pnpm package ``` -------------------------------- ### Corporate proxy with certificate configuration Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/configuration.md Example configuration for using a corporate proxy with a specified CA certificate. This is often required in enterprise environments. ```json { "proxy": { "upstreamProxy": "http://proxy.corp:3128" }, "upstreamCertificatePath": "/path/to/corporate-ca.crt" } ``` -------------------------------- ### Initiate OAuth Sign-in Flow Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/auth-api.md Starts the OAuth sign-in process with Grafana Cloud. Use this to begin the authentication flow and retrieve available stacks upon success. ```typescript import { signIn } from 'window.studio.auth' try { const result = await studio.auth.signIn() if (result.success && result.stacks) { console.log('Sign in successful') console.log('Available stacks:', result.stacks.map(s => s.name)) } else { console.error('Sign in failed:', result.error) } } catch (error) { console.error('Sign in error:', error) } ``` -------------------------------- ### Run a k6 Script Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/script-api.md Executes a k6 test script. Use this to start a test, providing the script path and optionally a scenario name. Handles potential errors like proxy issues, file not found, or k6 binary failures. ```typescript import { runScript } from 'window.studio.script' try { await studio.script.runScript('/path/to/test.js') console.log('Script started') } catch (error) { if (error.name === 'ArchiveError') { console.error('k6 stderr:', error.stderr) } } ``` -------------------------------- ### Example HAR File Structure Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/har-api.md This JSON object demonstrates the typical structure of a HAR file, including creator information, log version, and an array of network entries. ```json { "log": { "version": "1.2", "creator": { "name": "k6 Studio", "version": "1.13.0" }, "entries": [ { "startedDateTime": "2024-01-15T10:30:00.000Z", "time": 245, "request": { "method": "GET", "url": "https://example.com/api/users", "httpVersion": "HTTP/2.0", "headers": [ { "name": "Accept", "value": "application/json" } ], "queryString": [], "cookies": [] }, "response": { "status": 200, "statusText": "OK", "httpVersion": "HTTP/2.0", "headers": [ { "name": "Content-Type", "value": "application/json" } ], "cookies": [], "content": { "size": 1024, "mimeType": "application/json", "text": "{...}" }, "redirectURL": "", "timings": { "blocked": 0, "dns": 100, "connect": 50, "send": 10, "wait": 50, "receive": 35, "ssl": 45 } } } ] } } ``` -------------------------------- ### Get Proxy Status Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/proxy-api.md Retrieves the current status of the proxy server. Possible statuses include 'online', 'offline', and 'starting'. ```typescript const status = await studio.proxy.getProxyStatus() if (status === 'online') { console.log('Proxy is running') } ``` -------------------------------- ### Main Application File Structure Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/INDEX.md Outlines the key files and directories within the root src/ directory of the k6 Studio application. ```bash src/ ├── main.ts # Electron main process entry ├── preload.ts # ContextBridge exposure (window.studio) ├── App.tsx # React root component ├── codegen/ # Script generation engine ├── store/ # Zustand state management ├── utils/ # Helper functions ├── services/ # Singletons (proxy, auth, tracking) └── handlers/ # IPC handler modules ``` -------------------------------- ### Show Save As File Dialog Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/INDEX.md Opens a file save dialog, allowing the user to choose a location and name for a file. Requires a starting location and can accept file filters. ```javascript studio.fs.showSaveAsDialog(location, filters) ``` -------------------------------- ### Conventional Commits Examples Source: https://github.com/grafana/k6-studio/blob/main/AGENTS.md Examples of commit messages following the Conventional Commits format for feature additions and bug fixes. ```git feat: Add type column to WebLogView ``` ```git fix: Application crashes when opening HAR file ``` -------------------------------- ### launchBrowser(options) Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/browser-api.md Launches a controlled browser instance for recording. It takes browser launch configuration options and returns a promise that resolves when the browser successfully launches. It can reject if the browser binary is not found, port allocation fails, or if the launch fails with a `LaunchBrowserError`. ```APIDOC ## launchBrowser(options) ### Description Launches a controlled browser instance for recording. ### Method `launchBrowser` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (`LaunchBrowserOptions`) - Required - Browser launch configuration ### Request Example ```typescript import { launchBrowser } from 'window.studio.browser' const options = { proxyUrl: 'http://127.0.0.1:8080', recordMode: true } try { await studio.browser.launchBrowser(options) console.log('Browser launched') } catch (error) { console.error('Failed to launch browser:', error) } ``` ### Response #### Success Response `Promise` - Resolves when browser successfully launches #### Response Example None explicitly provided, resolves on success. ### Error Handling - Rejects if browser binary not found - Rejects if port allocation fails - Rejects with `LaunchBrowserError` if launch fails ``` -------------------------------- ### Open k6 Script Workflow Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/filesystem-api.md Demonstrates how to open a k6 script file using the `showOpenDialog` and `openFile` methods. Includes filtering for specific file types. ```typescript const filters = [ { name: 'k6 Scripts', extensions: ['js'] }, { name: 'All Files', extensions: ['*'] } ] const filePath = await studio.fs.showOpenDialog(filters) if (filePath) { const content = await studio.fs.openFile(filePath) console.log('Script content:', content.data) } ``` -------------------------------- ### Typical Authentication Flow Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/auth-api.md Demonstrates the standard workflow for authenticating a user in k6 Studio, including checking existing authentication, initiating sign-in, and selecting a stack. ```typescript // 1. Check if already authenticated const profiles = await studio.auth.getProfiles() if (profiles.selectedStack) { console.log('Already authenticated to', profiles.selectedStack.name) } else { // 2. Start sign-in const unsubscribe = studio.auth.onStateChange((state) => { console.log('State:', state) }) try { const result = await studio.auth.signIn() if (result.success && result.stacks) { // 3. User selects stack const selected = result.stacks[0] studio.auth.selectStack({ stackId: selected.id }) console.log('Authenticated to', selected.name) } } finally { unsubscribe() } } ``` -------------------------------- ### Launch Browser Instance Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/browser-api.md Launches a controlled browser instance for recording user interactions. Specify proxy URL and recording mode. Handles potential launch errors. ```typescript import { launchBrowser } from 'window.studio.browser' const options = { proxyUrl: 'http://127.0.0.1:8080', recordMode: true } try { await studio.browser.launchBrowser(options) console.log('Browser launched') } catch (error) { console.error('Failed to launch browser:', error) } ``` -------------------------------- ### getTempScriptPath() Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/filesystem-api.md Gets the absolute path for a temporary script file. ```APIDOC ## getTempScriptPath() ### Description Gets the absolute path for a temporary script file. ### Method N/A (Function call) ### Endpoint N/A ### Parameters None ### Returns `Promise` - Absolute path to temporary script file ### Example ```typescript import { getTempScriptPath } from 'window.studio.fs' const tmpPath = await studio.fs.getTempScriptPath() console.log('Temp script path:', tmpPath) // Output: /tmp/k6-studio-temp-12345.js ``` ``` -------------------------------- ### Proxy Integration for Browser API Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/browser-api.md Demonstrates the steps to integrate with the proxy server for browser traffic capture. Ensure the proxy is running before launching the browser. ```javascript // 1. Start proxy await studio.proxy.launchProxy() // 2. Get proxy status const status = await studio.proxy.getProxyStatus() if (status !== 'online') { throw new Error('Proxy not running') } // 3. Launch browser with proxy const proxyStatus = await studio.proxy.getProxyStatus() await studio.browser.launchBrowser({ proxyUrl: `http://127.0.0.1:${proxyPort}` }) // 4. Record events studio.browser.onBrowserEvent((events) => { console.log('Recorded', events.length, 'events') }) // 5. Stop browser when done studio.browser.stopBrowser() ``` -------------------------------- ### ProxyStatus Type Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/types.md Represents the possible states of a proxy server: online, offline, or starting. ```typescript type ProxyStatus = 'online' | 'offline' | 'starting' ``` -------------------------------- ### getProxyStatus() Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/proxy-api.md Retrieves the current status of the proxy server. The status can be 'online', 'offline', or 'starting'. ```APIDOC ## getProxyStatus() ### Description Retrieves current proxy status. ### Method `function` ### Parameters None ### Returns `Promise` where `ProxyStatus = 'online' | 'offline' | 'starting'` ### Example ```typescript const status = await studio.proxy.getProxyStatus() if (status === 'online') { console.log('Proxy is running') } ``` ``` -------------------------------- ### Proxy Integration Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/browser-api.md Demonstrates how to integrate with the proxy server to capture network traffic before launching the browser. ```APIDOC ## Proxy Integration The browser API requires a running proxy server to capture traffic: ```typescript // 1. Start proxy await studio.proxy.launchProxy() // 2. Get proxy status const status = await studio.proxy.getProxyStatus() if (status !== 'online') { throw new Error('Proxy not running') } // 3. Launch browser with proxy const proxyStatus = await studio.proxy.getProxyStatus() await studio.browser.launchBrowser({ proxyUrl: `http://127.0.0.1:${proxyPort}` }) // 4. Record events studio.browser.onBrowserEvent((events) => { console.log('Recorded', events.length, 'events') }) // 5. Stop browser when done studio.browser.stopBrowser() ``` ``` -------------------------------- ### Detect Browser Availability Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/INDEX.md Checks if a compatible Chrome browser is installed and available on the system. Returns a boolean. ```javascript studio.ui.detectBrowser() ``` -------------------------------- ### getSettings() Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/settings-api.md Retrieves the current application settings. This is useful for displaying current configurations or initializing application state. ```APIDOC ## getSettings() ### Description Retrieves current application settings. ### Method GET (conceptual) ### Endpoint /settings ### Parameters None ### Request Example ```javascript import { getSettings } from 'window.studio.settings' const settings = await studio.settings.getSettings() console.log('Proxy enabled:', settings.proxy.enabled) ``` ### Response #### Success Response (200) - **settings** (AppSettings) - Current application settings object ### Response Example ```json { "proxy": { "enabled": true, "port": 8080 }, "recorder": { "recordConsoleLog": true }, "telemetry": { "usageReport": true }, "windowState": { "width": 1280, "height": 720, "x": 100, "y": 100 }, "browserExecutablePath": "/path/to/chrome", "upstreamCertificatePath": "/path/to/ca.crt" } ``` ``` -------------------------------- ### Record a User Flow with k6 Studio Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/README.md Steps to record a user flow using k6 Studio, including launching the proxy and browser, collecting events, and saving the recording. ```typescript // 1. Start proxy await studio.proxy.launchProxy() // 2. Launch browser with proxy await studio.browser.launchBrowser({ proxyUrl: 'http://127.0.0.1:8080' }) // 3. Collect events const events = [] studio.browser.onBrowserEvent((browserEvents) => { events.push(...browserEvents) }) studio.proxy.onProxyData((data) => { console.log(`Captured: ${data.request.method} ${data.request.url}`) }) // 4. User performs actions in browser... // 5. Save recording const recording = { id: 'rec-1', name: 'User Flow', entries: recordedRequests, groups: [], createdAt: Date.now() } const path = await studio.har.saveFile(recording, 'flow') ``` -------------------------------- ### Get Full Log Content Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/utility-apis.md Retrieves the entire content of the application log file as a string. This is an asynchronous operation. ```typescript const logs = await studio.log.getLogContent() console.log(logs) ``` -------------------------------- ### Get Current Platform Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/utility-apis.md Checks the current operating system platform. Useful for conditional logic based on the OS. ```typescript const platform: 'linux' | 'darwin' | 'win32' ``` ```typescript import { platform } from 'window.studio.app' if (platform === 'darwin') { console.log('Running on macOS') } ``` -------------------------------- ### Setting Environment Variables on Windows (PowerShell) Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/configuration.md Illustrates setting k6 environment variables and the HTTP proxy variable using PowerShell's '$env:' syntax before launching K6 Studio. ```powershell $env:K6_VUS = "100" $env:K6_DURATION = "10m" $env:HTTP_PROXY = "http://proxy:3128" pnpm start ``` -------------------------------- ### Run Tests and Formatting Source: https://github.com/grafana/k6-studio/blob/main/CLAUDE.md Commands for executing tests in watch mode and formatting code. ```bash pnpm test # vitest run pnpm test:watch # vitest watch pnpm format # prettier ``` -------------------------------- ### Get Log File Content Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/INDEX.md Retrieves the content of the application's log file. Use this for debugging or reviewing logs. ```javascript studio.log.getLogContent() ``` -------------------------------- ### signIn() Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/auth-api.md Initiates the sign-in process, typically involving OAuth. It returns a promise that resolves with the result of the sign-in attempt, including success status and available stacks if authentication is successful. ```APIDOC ## `signIn()` ### Description Initiates the authentication process. This typically involves an OAuth flow. ### Method `signIn` ### Returns - `Promise<{ success: boolean; stacks?: StackInfo[]; errorMessage?: string }>` - A promise that resolves to an object indicating the success of the sign-in attempt. - **success** (`boolean`) - True if the sign-in was successful, false otherwise. - **stacks** (`StackInfo[]`, optional) - An array of available Grafana stacks if authentication was successful. - **errorMessage** (`string`, optional) - A message describing the error if `success` is false. ### Example ```typescript try { const result = await studio.auth.signIn() if (result.success && result.stacks) { console.log('Sign-in successful. Available stacks:', result.stacks.map(s => s.name)) } else { console.error('Sign-in failed:', result.errorMessage) } } catch (error) { console.error('An unexpected error occurred during sign-in:', error) } ``` ``` -------------------------------- ### Get Temporary Script Path Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/INDEX.md Retrieves the path to the temporary directory where scripts can be stored. Useful for intermediate file operations. ```javascript studio.fs.getTempScriptPath() ``` -------------------------------- ### Replace k6 Binary on Linux Source: https://github.com/grafana/k6-studio/blob/main/README.md Replace the bundled k6 binary with a custom build for testing purposes on Linux. Ensure the copied binary has execute permissions. ```bash cp ./k6 resources/linux/x86_64/k6 chmod +x resources/linux/x86_64/k6 ``` -------------------------------- ### List Project Files Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/INDEX.md Retrieves a list of files within the current project directory. Returns an array of file objects. ```javascript studio.ui.getFiles() ``` -------------------------------- ### Get Temporary Script Path Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/filesystem-api.md Retrieves the absolute path for a temporary script file. Useful for intermediate file storage. ```typescript import { getTempScriptPath } from 'window.studio.fs' const tmpPath = await studio.fs.getTempScriptPath() console.log('Temp script path:', tmpPath) // Output: /tmp/k6-studio-temp-12345.js ``` -------------------------------- ### File Not Found Error Handling Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/filesystem-api.md Example of handling a 'File Not Found' error when attempting to open a non-existent file using a try-catch block. ```typescript try { const content = await studio.fs.openFile('/nonexistent.js') } catch (error) { console.error('File not found:', error.message) } ``` -------------------------------- ### Select Browser Executable Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/INDEX.md Opens a file picker dialog for the user to select a Chrome browser executable. This is typically used during application setup or configuration. ```javascript studio.settings.selectBrowserExecutable() ``` -------------------------------- ### Navigate Application Routes Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/utility-apis.md Navigates the application to a different route. Use this to switch between different views or sections within k6 Studio. ```typescript // Navigate to generator studio.app.changeRoute('/generator/test.k6g') // Navigate to validator studio.app.changeRoute('/validator/test.js') // Go back to home studio.app.changeRoute('/') ``` -------------------------------- ### Ignore all internal domains in proxy settings Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/configuration.md A common pattern for configuring proxy settings to bypass internal domains. This helps in corporate network setups. ```typescript ignoreHosts: ['*.internal', '*.local', '10.*', '172.16.*', '192.168.*'] ``` -------------------------------- ### Save k6 Generator Configuration Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/generator-api.md Persists the current generator configuration to a specified file path. This is useful for saving your progress or sharing generator setups. ```typescript const generator = { recording: [], options: { vus: 10, duration: '30s' }, rules: [], testData: { variables: [], files: [] } } await studio.generator.saveGenerator(generator, '/path/to/test.k6g') console.log('Generator saved') ``` -------------------------------- ### openLogFolder() Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/utility-apis.md Opens the folder containing application logs. ```APIDOC ## `openLogFolder()` ### Description Opens folder containing application logs. ### Signature `function openLogFolder(): void` ### Parameters None ### Returns `void` ### Example ```typescript studio.log.openLogFolder() ``` ``` -------------------------------- ### Select Browser Executable Path Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/settings-api.md Opens a file dialog to select the Chrome/Chromium binary. Use this when the browser path needs to be manually configured by the user. ```typescript const result = await studio.settings.selectBrowserExecutable() if (!result.canceled && result.filePaths.length > 0) { console.log('Selected browser:', result.filePaths[0]) } ``` -------------------------------- ### onAddFile(callback) Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/utility-apis.md Subscribes to an event that is invoked whenever a new file is created in the project. ```APIDOC ## onAddFile(callback) ### Description Invoked when new file created. ### Method `() => void` ### Parameters #### Path Parameters - **callback** (`(file: StudioFile) => void`) - Required - Function to be called when a file is added. ### Returns `() => void` - A function to unsubscribe the callback. ### Example ```typescript const unsubscribe = studio.ui.onAddFile((file) => { console.log('File created:', file.fileName) }) ``` ``` -------------------------------- ### Event Listeners Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/script-api.md Provides functions to register callbacks for various script execution events, including when a script starts, stops, finishes, fails, or logs output. ```APIDOC ## Event Listeners ### onScriptStarted(callback) #### Description Invoked when script execution begins. #### Method Signature ```typescript function onScriptStarted(callback: (data?: any) => void): void ``` #### Example ```typescript studio.script.onScriptStarted(() => { console.log('Test started') }) ``` ### onScriptStopped(callback) #### Description Invoked when script execution is stopped by user. #### Method Signature ```typescript function onScriptStopped(callback: (data?: any) => void): void ``` ### onScriptFinished(callback) #### Description Invoked when script execution completes successfully. #### Method Signature ```typescript function onScriptFinished(callback: (data?: any) => void): void ``` ### onScriptFailed(callback) #### Description Invoked when script execution fails. #### Method Signature ```typescript function onScriptFailed(callback: (data?: any) => void): void ``` ### onScriptLog(callback) #### Description Receives log output from k6 test execution. #### Method Signature ```typescript function onScriptLog(callback: (logEntry: string) => void): void ``` #### Parameters - **logEntry** (string) - Required - Single line of k6 output #### Example ```typescript studio.script.onScriptLog((entry) => { console.log('k6:', entry) }) ``` ``` -------------------------------- ### runScript Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/script-api.md Executes a k6 test script. It can optionally target a specific scenario within the script. The function returns a promise that resolves when the test execution starts. ```APIDOC ## runScript(scriptPath, scenarioName?) ### Description Executes a k6 test script with optional specific scenario. ### Method Signature ```typescript function runScript(scriptPath: string, scenarioName?: string): Promise ``` ### Parameters #### Path Parameters - **scriptPath** (string) - Required - Path to k6 script file (absolute or relative to SCRIPTS_PATH) - **scenarioName** (string) - Optional - Run specific scenario if script has multiple ### Returns - `Promise` - Resolves when test execution starts ### Throws - Rejects if proxy not ready - Rejects if script file not found - Rejects if k6 binary fails to execute - Rejects with `ArchiveError` containing k6 stderr ### Example ```typescript import { runScript } from 'window.studio.script' try { await studio.script.runScript('/path/to/test.js') console.log('Script started') } catch (error) { if (error.name === 'ArchiveError') { console.error('k6 stderr:', error.stderr) } } ``` ``` -------------------------------- ### selectScript Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/script-api.md Opens a file dialog allowing the user to select a k6 script file. It returns a promise that resolves with the selected file path, or undefined if the dialog is cancelled. ```APIDOC ## selectScript() ### Description Opens file dialog for user to select a k6 script. ### Method Signature ```typescript function selectScript(): Promise ``` ### Parameters None ### Returns - `Promise` - Selected file path or undefined if cancelled ### Example ```typescript const selected = await studio.script.selectScript() if (selected) { console.log('Selected script:', selected) } ``` ``` -------------------------------- ### selectBrowserExecutable() Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/settings-api.md Opens a file dialog allowing the user to select the Chrome or Chromium browser executable. Returns the file path of the selected binary. ```APIDOC ## selectBrowserExecutable() ### Description Opens file dialog to select Chrome/Chromium binary. ### Method GET (conceptual) ### Endpoint /settings/browser-executable ### Parameters None ### Request Example ```javascript const result = await studio.settings.selectBrowserExecutable() if (!result.canceled && result.filePaths.length > 0) { console.log('Selected browser:', result.filePaths[0]) } ``` ### Response #### Success Response (200) - **result** (OpenDialogReturnValue) - Object containing `canceled` (boolean) and `filePaths` (string array). ### Response Example ```json { "canceled": false, "filePaths": ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"] } ``` ``` -------------------------------- ### Record and Generate Test Script Workflow Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/INDEX.md This snippet outlines the steps for recording browser interactions, saving the HAR data, generating a k6 script, and executing it. ```javascript studio.settings.getSettings() studio.proxy.launchProxy() studio.browser.launchBrowser({ proxyUrl: '...' }) // User performs actions in browser studio.proxy.onProxyData() studio.har.saveFile(recording, 'name') studio.generator.createGenerator(harPath) // Apply rules (correlation, parameterization, verification) studio.generator.saveGenerator(generator, path) studio.script.runScript(path) studio.script.onScriptLog() // Debug and fix issues studio.auth.signIn() studio.cloud.run(script) // View results on Grafana Cloud ``` -------------------------------- ### Proxy API Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/README.md APIs for managing the network recording proxy. These functions allow you to start, stop, and monitor the proxy status, as well as subscribe to status changes and captured network requests. ```APIDOC ## Proxy API ### Description APIs for managing the network recording proxy. These functions allow you to start, stop, and monitor the proxy status, as well as subscribe to status changes and captured network requests. ### Methods - `launchProxy()` - Start recording - `stopProxy()` - Stop recording - `getProxyStatus()` - Check status - `onProxyStatusChange()` - Subscribe to status changes - `onProxyData()` - Subscribe to captured requests - `checkProxyHealth()` - Health check ``` -------------------------------- ### Equivalent k6 Configuration for Simple Load Test Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/configuration.md The JavaScript code equivalent to the simple load test JSON configuration, demonstrating how to define 'vus' and 'duration' in k6's 'options'. ```javascript export const options = { vus: 50, duration: '5m' } ``` -------------------------------- ### Initiate Streaming Chat Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/ai-api.md Use `streamChat` to start a conversational session with the AI assistant. Provide a request object containing messages and an ID. The function returns a controller to manage the stream. ```typescript import { streamChat } from 'window.studio.ai' const request = { id: 'chat-1', messages: [ { role: 'user', content: 'How do I add a delay between requests in k6?' } ] } const controller = studio.ai.streamChat(request) controller.onChunk((chunk) => { if (chunk.type === 'text') { console.log('AI:', chunk.text) } }) controller.onEnd(() => { console.log('Response complete') }) ``` -------------------------------- ### Save Generator Configuration Workflow Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/filesystem-api.md Demonstrates saving generator configuration objects to a file, specifying the format as JSON and filtering for '.k6g' files. ```typescript const generator = { recording: [], options: {}, rules: [] } const location = await studio.fs.showSaveAsDialog('project', [ { name: 'k6 Generator', extensions: ['k6g'] } ]) if (location) { await studio.fs.saveFile(location, { format: 'json', data: generator }) } ``` -------------------------------- ### Select Browser Executable Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/settings-api.md Opens a file dialog to allow the user to select the path to a browser executable (e.g., Chrome, Chromium). ```APIDOC ## Select Browser Executable ### Description Opens a file dialog for the user to select a browser executable path. ### Method POST (or equivalent SDK call) ### Endpoint `/settings/select-browser-executable` (conceptual, actual call via SDK) ### Parameters None ### Request Example ```typescript const result = await studio.settings.selectBrowserExecutable() if (!result.canceled) { const settings = await studio.settings.getSettings() settings.browserExecutablePath = result.filePaths[0] await studio.settings.saveSettings(settings) } ``` ### Response #### Success Response (200) - **canceled** (boolean) - True if the dialog was canceled, false otherwise. - **filePaths** (string[]) - An array containing the path(s) to the selected file(s), if any. #### Response Example ```json { "canceled": false, "filePaths": ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"] } ``` ``` -------------------------------- ### Retrieve Project Files Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/utility-apis.md Fetches all project files, categorized by type (recordings, generators, scripts, etc.). The response includes arrays for each file type. ```typescript function getFiles(): Promise ``` ```typescript interface GetFilesResponse { recordings: StudioFile[] generators: StudioFile[] scripts: StudioFile[] browserTests: StudioFile[] dataFiles: StudioFile[] } ``` ```typescript const files = await studio.ui.getFiles() console.log('Scripts:', files.scripts.map(f => f.fileName)) console.log('Data files:', files.dataFiles.map(f => f.path)) ``` -------------------------------- ### Select a k6 Script via File Dialog Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/script-api.md Opens a file dialog allowing the user to select a k6 script file. Returns the selected file path or undefined if the user cancels the dialog. ```typescript const selected = await studio.script.selectScript() if (selected) { console.log('Selected script:', selected) } ``` -------------------------------- ### getFiles() Source: https://github.com/grafana/k6-studio/blob/main/_autodocs/api-reference/utility-apis.md Retrieves all project files, organized by their type (recordings, generators, scripts, browser tests, data files). ```APIDOC ## getFiles() ### Description Retrieves all project files organized by type. ### Method `Promise` ### Parameters None ### Returns `Promise` - All project files ### Response Type ```typescript interface GetFilesResponse { recordings: StudioFile[] generators: StudioFile[] scripts: StudioFile[] browserTests: StudioFile[] dataFiles: StudioFile[] } ``` ### Example ```typescript const files = await studio.ui.getFiles() console.log('Scripts:', files.scripts.map(f => f.fileName)) console.log('Data files:', files.dataFiles.map(f => f.path)) ``` ```