### Install Dependencies and Run Development Server Source: https://context7.com/scalar/sandbox/llms.txt Commands for setting up the local development environment. Includes installing project dependencies using `pnpm`, running database migrations for a local D1 database, starting the development server with hot reload for both frontend and backend, building for production, and formatting code. ```bash # Install dependencies pnpm install # Run database migrations (local D1) pnpm db:migrate # Start development (frontend + backend concurrently) pnpm dev # Frontend: http://localhost:5173 # Backend: http://localhost:8788 # Build for production pnpm build # Format code pnpm format ``` -------------------------------- ### Export OpenAPI Specification as YAML (Bash) Source: https://context7.com/scalar/sandbox/llms.txt Downloads a normalized OpenAPI specification in YAML format using a GET request, demonstrated with curl. The downloaded YAML file can be validated and converted to JSON using command-line tools like swagger-cli and yq. ```bash # Download OpenAPI YAML via curl curl https://sandbox.scalar.com/files/abc12/openapi.yaml > api-spec.yaml # Use with swagger-cli swagger-cli validate api-spec.yaml # Convert to JSON cat api-spec.yaml | yq eval -o=json > api-spec.json ``` -------------------------------- ### Export OpenAPI Specification as JSON (JavaScript) Source: https://context7.com/scalar/sandbox/llms.txt Retrieves a normalized OpenAPI specification in JSON format via a GET request to /files/{sandboxId}/openapi.json. The returned JSON can be directly used with OpenAPI tools for validation and processing. ```javascript const sandboxId = 'abc12'; const response = await fetch(`/files/${sandboxId}/openapi.json`); const spec = await response.json(); console.log(spec); // Returns normalized OpenAPI spec: // { // openapi: '3.1.0', // info: { title: 'My API', version: '1.0.0' }, // paths: { ... } // } // Use with OpenAPI tools import { validate } from '@scalar/openapi-parser'; const result = await validate(spec); console.log(`Valid: ${result.valid}`); ``` -------------------------------- ### Retrieve OpenAPI Sandbox by ID (JavaScript) Source: https://context7.com/scalar/sandbox/llms.txt Fetches a saved OpenAPI sandbox by its unique identifier using a GET request to /api/share/{sandboxId}. The response is a JSON object containing the sandbox details, including its content which can be parsed to access the OpenAPI specification. ```javascript const sandboxId = 'abc12'; const response = await fetch(`/api/share/${sandboxId}`, { credentials: 'same-origin', }); const data = await response.json(); console.log(data); // Returns: { id: 'abc12', parentId: null, content: '{"openapi":"3.1.0",...}', token: 'a1b2c3...', createdAt: '2024-01-01T00:00:00Z' } // Parse and use the content const spec = JSON.parse(data.content); console.log(`API Title: ${spec.info.title}`); ``` -------------------------------- ### Generate Unique IDs and Secret Tokens with Nanoid Source: https://context7.com/scalar/sandbox/llms.txt Utility functions for generating unique identifiers and authorization tokens using the `nanoid` library. `generateUniqueId` creates a short, 5-character ID suitable for URLs, while `generateSecretToken` produces a longer, 32-character hexadecimal token for secure updates. Includes example usage and output. ```typescript import { customAlphabet, nanoid } from 'nanoid'; // Generate 5-character unique ID for sandbox URLs export function generateUniqueId(): string { return nanoid(5); } // Generate 32-character hex token for update authorization export function generateSecretToken(): string { return customAlphabet('1234567890abcdef', 32)(); } // Usage const newSandbox = { id: generateUniqueId(), // e.g., 'xK9p2' token: generateSecretToken(), // e.g., 'a1b2c3d4e5f6789012345678901234ab' }; console.log(`Share URL: /e/${newSandbox.id}`); console.log(`Update with: ?token=${newSandbox.token}`); ``` -------------------------------- ### Create Dark Mode Hook with localStorage Persistence Source: https://context7.com/scalar/sandbox/llms.txt Provides a composable function `useDarkMode` for managing dark mode preference. It uses `ref` to store the dark mode state, initializes it from `localStorage` or system preference, and persists changes back to `localStorage`. It also toggles a 'dark-mode' class on the document element. Includes usage example within a Vue component. ```typescript import { ref, watch } from 'vue'; export function useDarkMode() { const isDark = ref( localStorage.getItem('darkMode') === 'true' || window.matchMedia('(prefers-color-scheme: dark)').matches ); watch(isDark, (value) => { localStorage.setItem('darkMode', value.toString()); document.documentElement.classList.toggle('dark-mode', value); }, { immediate: true }); return isDark; } // Usage in component const isDark = useDarkMode(); // Pass to API Reference component ``` -------------------------------- ### Initialize Vue App with Router and Theming Source: https://context7.com/scalar/sandbox/llms.txt Initializes the Vue application, sets up routing, and applies global styles including theming. It mounts the main App component to the DOM. Routes are defined for new sandbox creation, editing, and preview modes. ```typescript import '@scalar/themes/style.css'; import { createApp } from 'vue'; import App from './App.vue'; import { router } from './router'; import './style.css'; const app = createApp(App); app.use(router); app.mount('#app'); // Routes: // / - New sandbox // /e/:id - Edit mode with saved spec // /p/:id - Preview mode (API docs only) ``` -------------------------------- ### Manage Database Migrations with Drizzle Kit Source: https://context7.com/scalar/sandbox/llms.txt Commands for managing database schema changes using Drizzle Kit. This includes generating new migration files after schema modifications, applying migrations locally to a Cloudflare D1 database, and applying migrations to the production environment. Migration files are stored in the `./migrations/` directory. ```bash # Generate new migration after schema changes pnpm db:generate # Apply migrations locally (Cloudflare D1 local) pnpm db:migrate # Apply migrations to production pnpm db:migrate:production # Migration files created in ./migrations/ # Example: 0000_initial_schema.sql ``` -------------------------------- ### Implement Share Functionality with Clipboard and URL Management Source: https://context7.com/scalar/sandbox/llms.txt Handles the sharing of sandbox content. If no changes are detected, it copies the current URL to the clipboard. Otherwise, it sends the content to a backend API to create a new version, obtains a shareable URL, copies it to the clipboard, and updates the router and stored content. It includes loading state management and error handling. ```typescript const share = async () => { // If no changes, just copy current URL if (!contentChanged.value) { await navigator.clipboard.writeText(window.location.href); toast.success('Copied URL to clipboard.', { description: window.location.href, }); return; } // Create new sandbox version loading.value = true; try { const response = await fetch('/api/share', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ parentId: storedContent.id ?? null, content: content.value, }), credentials: 'same-origin', }); const data = await response.json(); const url = `${window.location.origin}/e/${data.id}`; setTimeout(() => { navigator.clipboard.writeText(url); toast.success('Copied URL to clipboard.', { description: url }); }, 100); contentChanged.value = false; Object.assign(storedContent, data); router.replace({ name: 'edit', params: { id: data.id } }); } finally { loading.value = false; } }; ``` -------------------------------- ### Export as OpenAPI YAML Source: https://context7.com/scalar/sandbox/llms.txt Provides a way to download the normalized OpenAPI specification in YAML format for a given sandbox ID. ```APIDOC ## GET /files/{id}/openapi.yaml ### Description Retrieves the normalized OpenAPI specification for a given sandbox ID in YAML format. ### Method GET ### Endpoint /files/{id}/openapi.yaml ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the sandbox. ### Response #### Success Response (200) - (string) - The normalized OpenAPI specification in YAML format. ### Request Example (using curl) ```bash curl https://sandbox.scalar.com/files/abc12/openapi.yaml > api-spec.yaml ``` ``` -------------------------------- ### Retrieve Sandbox Source: https://context7.com/scalar/sandbox/llms.txt Fetches a saved OpenAPI sandbox by its unique identifier. The response includes the sandbox's ID, content, token, and creation timestamp. ```APIDOC ## GET /api/share/{id} ### Description Retrieves a saved OpenAPI sandbox by its unique identifier. ### Method GET ### Endpoint /api/share/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the sandbox to retrieve. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the sandbox. - **parentId** (string) - The ID of the parent sandbox, if any. - **content** (string) - The OpenAPI specification content as a JSON string. - **token** (string) - The secret token for updating the sandbox. - **createdAt** (string) - The timestamp when the sandbox was created. #### Response Example ```json { "id": "abc12", "parentId": null, "content": "{\"openapi\":\"3.1.0\",\"info\":{\"title\":\"My API\",\"version\":\"1.0.0\"},\"paths\":{\"/":{\"get\":{\"summary\":\"Root endpoint\"}}}}", "token": "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6", "createdAt": "2024-01-01T00:00:00Z" } ``` ``` -------------------------------- ### Export as OpenAPI JSON Source: https://context7.com/scalar/sandbox/llms.txt Allows downloading the normalized OpenAPI specification in JSON format for a given sandbox ID. ```APIDOC ## GET /files/{id}/openapi.json ### Description Retrieves the normalized OpenAPI specification for a given sandbox ID in JSON format. ### Method GET ### Endpoint /files/{id}/openapi.json ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the sandbox. ### Response #### Success Response (200) - (object) - The normalized OpenAPI specification in JSON format. ### Response Example ```json { "openapi": "3.1.0", "info": { "title": "My API", "version": "1.0.0" }, "paths": { "/users": { "get": { "summary": "List users", "responses": { "200": { "description": "Success" } } } } } } ``` ``` -------------------------------- ### Create or Update Sandbox Source: https://context7.com/scalar/sandbox/llms.txt This endpoint allows for the creation of a new OpenAPI sandbox or the update of an existing one using a token. It accepts a JSON payload containing the OpenAPI content. ```APIDOC ## POST /api/share ### Description Creates a new OpenAPI sandbox or updates an existing one with a provided token. The request body should contain the OpenAPI content. ### Method POST ### Endpoint /api/share ### Parameters #### Request Body - **parentId** (string) - Optional - The ID of a parent sandbox to link to. - **content** (string) - Required - A JSON string representing the OpenAPI specification. ### Request Example ```json { "parentId": null, "content": "{\n \"openapi\": \"3.1.0\",\n \"info\": {\n \"title\": \"My API\",\n \"version\": \"1.0.0\"\n },\n \"paths\": {\n \"/users\": {\n \"get\": {\n \"summary\": \"List users\",\n \"responses\": {\n \"200\": {\n \"description\": \"Success\"\n }\n }\n }\n }\n }\n}" } ``` ### Response #### Success Response (200 or 202) - **id** (string) - The unique identifier for the sandbox. - **content** (string) - The OpenAPI specification content. - **token** (string) - A secret token for updating the sandbox. - **createdAt** (string) - The timestamp when the sandbox was created. #### Response Example ```json { "id": "abc12", "content": "{\n \"openapi\": \"3.1.0\",\n \"info\": {\n \"title\": \"My API\",\n \"version\": \"1.0.0\"\n },\n \"paths\": {\n \"/users\": {\n \"get\": {\n \"summary\": \"List users\",\n \"responses\": {\n \"200\": {\n \"description\": \"Success\"\n }\n }\n }\n }\n }\n}", "token": "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6", "createdAt": "2024-01-01T00:00:00Z" } ``` ``` -------------------------------- ### Create New OpenAPI Sandbox (JavaScript) Source: https://context7.com/scalar/sandbox/llms.txt Creates a new OpenAPI sandbox or updates an existing one using a POST request to the /api/share endpoint. It requires a JSON payload with sandbox content and optionally accepts a parentId. The response includes the sandbox ID, content, token, and creation timestamp. ```javascript const response = await fetch('/api/share', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ parentId: null, content: JSON.stringify({ openapi: '3.1.0', info: { title: 'My API', version: '1.0.0', }, paths: { '/users': { get: { summary: 'List users', responses: { '200': { description: 'Success', }, }, }, }, }, }), }), credentials: 'same-origin', }); const data = await response.json(); // Returns: { id: 'abc12', content: '...', token: 'a1b2c3...', createdAt: '2024-01-01T00:00:00Z' } console.log(`Sandbox created: ${window.location.origin}/e/${data.id}`); ``` -------------------------------- ### Manage Reactive Content State with Change Tracking Source: https://context7.com/scalar/sandbox/llms.txt Manages the application's content state reactively using Vue's `ref` and `reactive`. It includes a watcher to track changes in the content and a `watchEffect` to prevent data loss by prompting the user before navigating away if unsaved changes exist. The state includes fields for ID, content, and creation timestamp. ```typescript import { reactive, ref, watch } from 'vue'; const content = ref( JSON.stringify({ openapi: '3.1.0', info: { title: 'Hello World', version: '1.0.0' }, paths: {}, }, null, 2) ); const contentChanged = ref(false); const storedContent = reactive({ id: null, content: '', createdAt: '', }); // Track changes watch(content, (value) => { if (value !== storedContent.content) { contentChanged.value = true; } else { contentChanged.value = false; } }); // Prevent data loss window.onbeforeunload = function () { if (contentChanged.value) { return false; // Browser shows confirmation dialog } }; ``` -------------------------------- ### Configure Vite API Proxy Source: https://context7.com/scalar/sandbox/llms.txt Sets up a Vite development server proxy to route API requests to a specific backend server during local development. This configuration allows the frontend, typically running on port 5173, to make requests to the backend on port 8788, simplifying API calls like fetch('/api/share') to be resolved as http://localhost:8788/api/share. ```typescript import { defineConfig } from 'vite'; export default defineConfig({ server: { proxy: { '/api': { target: 'http://localhost:8788', changeOrigin: true, }, '/files': { target: 'http://localhost:8788', changeOrigin: true, }, }, }, }); ``` -------------------------------- ### Update Existing OpenAPI Sandbox (JavaScript) Source: https://context7.com/scalar/sandbox/llms.txt Updates an existing OpenAPI sandbox's content using a POST request to /api/share, authenticated with a secret token. It accepts a JSON payload containing the updated content. A 202 status code indicates success, while other codes may indicate errors like 'Sandbox Not Found'. ```javascript const token = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'; const response = await fetch(`/api/share?token=${token}`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ content: JSON.stringify({ openapi: '3.1.0', info: { title: 'Updated API', version: '2.0.0', }, paths: {}, }), }), credentials: 'same-origin', }); if (response.status === 202) { const data = await response.json(); console.log('Sandbox updated successfully', data); } else { const error = await response.json(); console.error(error.message); // 'Sandbox Not Found' } ``` -------------------------------- ### Drizzle ORM SQLite Table Definition for Specs (TypeScript) Source: https://context7.com/scalar/sandbox/llms.txt Defines the 'Specs' table schema for SQLite using Drizzle ORM in TypeScript. This table stores OpenAPI specifications with fields for ID, parentId, content, token, and creation timestamp, including default values for createdAt. ```typescript import { sql } from 'drizzle-orm'; import { drizzle } from 'drizzle-orm/d1'; import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core'; export const Specs = sqliteTable('Specs', { id: text('id').primaryKey(), parentId: text('parent_id'), content: text('content').notNull(), token: text('token'), createdAt: text('created_at') .notNull() .default(sql`CURRENT_TIMESTAMP`), }); // Query example const db = drizzle(env.DB); const specs = await db.select().from(Specs).where(sql`${Specs.id} = ${'abc12'}`); console.log(specs[0].content); // Insert example await db.insert(Specs).values({ id: 'xyz99', parentId: 'abc12', content: JSON.stringify({ openapi: '3.1.0', info: { title: 'Test' } }), token: generateSecretToken(), }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.