### Deploy Application from Sandbox with Auto SSL/DNS (JavaScript) Source: https://www.ose.sh/docs/guides This guide shows how to deploy an application from an OSE sandbox, including automatic SSL and DNS configuration. It involves creating a sandbox, installing dependencies, building the application, and initiating the deployment. The OSE SDK is the primary dependency. ```javascript import { OSE } from '@ose-cloud/sdk'; const ose = new OSE({ apiKey: process.env.OSE_API_KEY }); // Create and prepare sandbox const sandbox = await ose.sandboxes.create({ template: 'nextjs' }); // Install dependencies and build await sandbox.terminal.execute('npm install'); await sandbox.terminal.execute('npm run build'); // Deploy to production const deployment = await ose.deployments.create({ sandboxId: sandbox.id, name: 'my-production-app', port: 3000, domain: 'app.yourdomain.com' // Optional custom domain }); console.log('Deployed to:', deployment.url); // Output: https://my-production-app.ose.sh ``` -------------------------------- ### Install OSE Cloud SDK with npm Source: https://www.ose.sh/docs/installation Installs the OSE Cloud SDK for Node.js/TypeScript using npm. This is the primary method for Node.js/TypeScript projects. ```bash npm install @ose-cloud/sdk ``` -------------------------------- ### Install OSE Cloud SDK with pip Source: https://www.ose.sh/docs/installation Installs the OSE Cloud SDK for Python using pip. This is the standard package installer for Python. ```bash pip install ose-cloud ``` -------------------------------- ### Install OSE Cloud SDK with yarn Source: https://www.ose.sh/docs/installation Installs the OSE Cloud SDK for Node.js/TypeScript using yarn. This is an alternative package manager for Node.js/TypeScript projects. ```bash yarn add @ose-cloud/sdk ``` -------------------------------- ### Manage Sandbox Lifecycle for Cost Efficiency (JavaScript) Source: https://www.ose.sh/docs/guides This example implements a SandboxManager class to efficiently manage sandbox lifecycles, ensuring cost efficiency. It includes creating sandboxes, scheduling automatic cleanup after inactivity, and handling manual cleanup on process termination. The OSE SDK is required. ```javascript import { OSE } from '@ose-cloud/sdk'; const ose = new OSE({ apiKey: process.env.OSE_API_KEY }); class SandboxManager { constructor() { this.activeSandboxes = new Map(); } async createSandbox(userId, config) { const sandbox = await ose.sandboxes.create(config); this.activeSandboxes.set(userId, sandbox); // Auto-cleanup after 1 hour of inactivity this.scheduleCleanup(userId, 60 * 60 * 1000); return sandbox; } scheduleCleanup(userId, timeout) { setTimeout(async () => { const sandbox = this.activeSandboxes.get(userId); if (sandbox) { await sandbox.delete(); this.activeSandboxes.delete(userId); console.log(`Cleaned up sandbox for user ${userId}`); } }, timeout); } async cleanup() { // Clean up all sandboxes on shutdown for (const [userId, sandbox] of this.activeSandboxes) { await sandbox.delete(); console.log(`Cleaned up sandbox for user ${userId}`); } this.activeSandboxes.clear(); } } // Handle process termination const manager = new SandboxManager(); process.on('SIGTERM', () => manager.cleanup()); process.on('SIGINT', () => manager.cleanup()); ``` -------------------------------- ### Create and Connect to OSE Cloud Sandbox (JavaScript/TypeScript) Source: https://www.ose.sh/docs/quickstart Demonstrates how to initialize the OSE SDK with an API key and base URL, then create a new sandbox environment using a specified template (e.g., 'nextjs'). It logs the ID of the newly created sandbox. ```javascript import { OSE } from '@ose-cloud/sdk'; const ose = new OSE({ apiKey: 'ose_sk_live_...', baseUrl: 'https://ose.sh/api' }); // Create a new sandbox const sandbox = await ose.sandboxes.create({ template: 'nextjs' }); console.log('Sandbox created:', sandbox.id); ``` -------------------------------- ### Clean Up OSE Cloud Resources (JavaScript/TypeScript) Source: https://www.ose.sh/docs/quickstart Provides the code to terminate and delete an OSE Cloud sandbox. It is crucial to explicitly delete sandboxes to stop billing and free up resources. ```javascript await sandbox.delete(); ``` -------------------------------- ### Configure OSE Cloud API Key in Node.js/TypeScript Source: https://www.ose.sh/docs/installation Demonstrates how to initialize the OSE Cloud SDK with an API key in a Node.js/TypeScript environment. It uses an environment variable for the API key, which is a common security practice. ```javascript import { OSECloud } from '@ose-cloud/sdk'; const ose = new OSECloud({ apiKey: process.env.OSE_API_KEY }); ``` -------------------------------- ### Execute Commands and Manage Files in OSE Cloud Sandbox (JavaScript/TypeScript) Source: https://www.ose.sh/docs/quickstart Shows how to execute commands within an OSE Cloud sandbox, including running simple shell commands like 'echo' and executing Node.js files. It also demonstrates writing content to a file within the sandbox. ```javascript // Execute a command const result = await sandbox.terminal.execute('echo "Hello from OSE Cloud!"'); console.log('Output:', result.output); // Write a file await sandbox.files.write('/app/hello.js', 'console.log("Hello World!");'); // Run the file const output = await sandbox.terminal.execute('node /app/hello.js'); console.log(output.output); // "Hello World!" ``` -------------------------------- ### Execute Parallel Builds Across Multiple Sandboxes (JavaScript) Source: https://www.ose.sh/docs/guides This pattern showcases how to handle complex operations requiring multiple sandboxes, specifically for parallel builds. It involves creating sandboxes for different projects concurrently, cloning repositories, installing dependencies, building, and then cleaning up all sandboxes. The OSE SDK is the sole dependency. ```javascript import { OSE } from '@ose-cloud/sdk'; const ose = new OSE({ apiKey: process.env.OSE_API_KEY }); async function parallelBuild(projects) { // Create sandboxes for each project in parallel const sandboxes = await Promise.all( projects.map(project => ose.sandboxes.create({ template: project.template, memory: project.memory || 2048 }) ) ); // Build each project const results = await Promise.all( sandboxes.map(async (sandbox, i) => { const project = projects[i]; // Clone and build await sandbox.terminal.execute(`git clone ${project.repo} /app`); await sandbox.terminal.execute('cd /app && npm install'); await sandbox.terminal.execute('cd /app && npm run build'); return { project: project.name, sandbox: sandbox.id, status: 'built' }; }) ); return { sandboxes, results }; } // Usage const { sandboxes, results } = await parallelBuild([ { name: 'frontend', repo: 'https://github.com/org/frontend', template: 'nextjs' }, { name: 'backend', repo: 'https://github.com/org/backend', template: 'nextjs' }, { name: 'worker', repo: 'https://github.com/org/worker', template: 'python' } ]); console.log('Build results:', results); // Clean up all sandboxes when done await Promise.all(sandboxes.map(s => s.delete())); ``` -------------------------------- ### GET /sandboxes Source: https://www.ose.sh/docs/api List all sandboxes for your account. ```APIDOC ## GET /sandboxes ### Description List all sandboxes for your account. ### Method GET ### Endpoint `/sandboxes` ``` -------------------------------- ### Integrate AI Agent with Sandbox for Code Execution (JavaScript) Source: https://www.ose.sh/docs/guides This snippet demonstrates how to connect an AI agent to an OSE sandbox for code execution. It involves creating a sandbox, writing code to it, executing the code, and retrieving the output. Dependencies include the '@ose-cloud/sdk' and '@anthropic-ai/sdk'. ```javascript import { OSE } from '@ose-cloud/sdk'; import Anthropic from '@anthropic-ai/sdk'; const ose = new OSE({ apiKey: process.env.OSE_API_KEY }); const anthropic = new Anthropic(); // Create a sandbox for the AI agent const sandbox = await ose.sandboxes.create({ template: 'nextjs', memory: 4096 }); // Let the AI execute code async function executeAICode(code) { // Write the code to sandbox await sandbox.files.write('/app/agent-code.js', code); // Execute and return results const result = await sandbox.terminal.execute('node /app/agent-code.js'); return result.output; } // Example: AI generates and runs code const message = await anthropic.messages.create({ model: 'claude-3-opus-20240229', messages: [{ role: 'user', content: 'Write a function to calculate fibonacci' }] }); const output = await executeAICode(message.content[0].text); console.log('AI Code Output:', output); // Clean up await sandbox.delete(); ``` -------------------------------- ### Configure Network Timeout and Proxy (JavaScript) Source: https://www.ose.sh/docs/troubleshooting This code example shows how to configure the OSE client to increase the connection `timeout` and set up a custom `httpAgent` for proxy support. This is essential for resolving 'Connection Timeout' issues and ensuring connectivity through corporate proxies. ```javascript const ose = new OSE({ apiKey: process.env.OSE_API_KEY, // Increase connection timeout timeout: 60000, // Custom agent for proxy support httpAgent: new HttpProxyAgent('http://proxy.company.com:8080') }); ``` -------------------------------- ### GET /sandboxes/:id/files Source: https://www.ose.sh/docs/api Read a file from the sandbox filesystem. ```APIDOC ## GET /sandboxes/:id/files ### Description Read a file from the sandbox filesystem. ### Method GET ### Endpoint `/sandboxes/:id/files` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the sandbox. #### Query Parameters - **path** (string) - Required - The path to the file within the sandbox. ``` -------------------------------- ### GET /sandboxes/:id Source: https://www.ose.sh/docs/api Get details of a specific sandbox. ```APIDOC ## GET /sandboxes/:id ### Description Get details of a specific sandbox. ### Method GET ### Endpoint `/sandboxes/:id` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the sandbox to retrieve. ``` -------------------------------- ### Authenticate API Requests using cURL Source: https://www.ose.sh/docs/api All API requests to the OSE Cloud platform require authentication using a Bearer token. This example shows how to include the Authorization header in a cURL request to list sandboxes. Never expose your API key in client-side code. ```curl curl -X GET https://ose.sh/api/sandboxes \ -H "Authorization: Bearer ose_sk_live_..." ``` -------------------------------- ### POST /sandboxes Source: https://www.ose.sh/docs/api Create a new sandbox instance. ```APIDOC ## POST /sandboxes ### Description Create a new sandbox instance. ### Method POST ### Endpoint `/sandboxes` ### Request Body - **template** (string) - Required - The template to use for the sandbox (e.g., "nextjs"). - **memory** (integer) - Optional - The amount of memory to allocate to the sandbox in MB. ### Request Example ```json { "template": "nextjs", "memory": 2048 } ``` ### Response #### Success Response (200) - **sandbox** (object) - Details of the created sandbox. - **id** (string) - The unique identifier for the sandbox. - **status** (string) - The current status of the sandbox (e.g., "running"). - **template** (string) - The template used for the sandbox. #### Response Example ```json { "sandbox": { "id": "sb_1a2b3c4d5e6f", "status": "running", "template": "nextjs" } } ``` ``` -------------------------------- ### POST /deployments Source: https://www.ose.sh/docs/api Deploy sandbox contents to OSE Cloud. ```APIDOC ## POST /deployments ### Description Deploy sandbox contents to OSE Cloud. ### Method POST ### Endpoint `/deployments` ### Request Body - **name** (string) - Required - The name for the deployment. - **sandboxId** (string) - Required - The ID of the sandbox to deploy. - **port** (integer) - Optional - The port to expose the deployment on. ### Request Example ```json { "name": "my-app", "sandboxId": "sb_1a2b3c4d5e6f", "port": 3000 } ``` ### Response #### Success Response (200) - **deployment** (object) - Details of the created deployment. - **id** (string) - The unique identifier for the deployment. - **url** (string) - The URL where the deployment is accessible. - **status** (string) - The current status of the deployment (e.g., "building"). #### Response Example ```json { "deployment": { "id": "dep_9x8y7z6w5v", "url": "https://my-app.ose.sh", "status": "building" } } ``` ``` -------------------------------- ### Create a Next.js Sandbox with OSE Cloud Source: https://www.ose.sh/docs/index Demonstrates how to programmatically create an isolated sandbox environment for a Next.js application using the OSE Cloud SDK. Specifies memory and CPU allocation for the sandbox. This is useful for setting up development or testing environments. ```javascript const sandbox = await ose.sandboxes.create({ template: 'nextjs', memory: 2048, cpu: 1 }); ``` -------------------------------- ### Verify API Key and Authentication (JavaScript) Source: https://www.ose.sh/docs/troubleshooting This code illustrates how to validate the API key format and ensure it's correctly set as an environment variable before initializing the OSE client. This helps resolve 'Authentication Failed (401)' errors by catching common mistakes like missing keys or incorrect formatting. ```javascript // Check API key format const apiKey = process.env.OSE_API_KEY; if (!apiKey) { throw new Error('OSE_API_KEY environment variable not set'); } if (!apiKey.startsWith('ose_sk_')) { throw new Error('Invalid API key format. Key should start with ose_sk_'); } const ose = new OSE({ apiKey }); ``` -------------------------------- ### Allocate More Memory and CPU for Sandbox (JavaScript) Source: https://www.ose.sh/docs/troubleshooting This snippet shows how to request more memory and CPU resources when creating a sandbox. By specifying the `memory` and `cpu` options in the `create` method, you can mitigate 'Out of Memory' errors. Note that memory limits are plan-dependent. ```javascript const sandbox = await ose.sandboxes.create({ template: 'nextjs', memory: 4096, // 4GB RAM cpu: 2 // 2 CPU cores }); ``` -------------------------------- ### POST /sandboxes/:id/files Source: https://www.ose.sh/docs/api Write a file to the sandbox filesystem. ```APIDOC ## POST /sandboxes/:id/files ### Description Write a file to the sandbox filesystem. ### Method POST ### Endpoint `/sandboxes/:id/files` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the sandbox. ### Request Body - **path** (string) - Required - The path to the file within the sandbox. - **content** (string) - Required - The content of the file. ### Request Example ```json { "path": "/app/index.js", "content": "console.log('Hello World!');" } ``` ``` -------------------------------- ### Create Svelte Sandbox Source: https://www.ose.sh/docs/web-frameworks Creates a Svelte sandbox with specified memory and CPU. This template uses SvelteKit for building fast, modern web applications. ```javascript const sandbox = await ose.sandboxes.create({ template: 'svelte', memory: 2048, cpu: 1 }); ``` -------------------------------- ### Create Deployment Response Body Source: https://www.ose.sh/docs/api After initiating a deployment, the API returns a JSON object containing the deployment's 'id', the 'url' where it will be accessible, and its current 'status'. The status will typically be 'building' initially. ```json { "deployment": { "id": "dep_9x8y7z6w5v", "url": "https://my-app.ose.sh", "status": "building" } } ``` -------------------------------- ### Create Sandbox Request Body Source: https://www.ose.sh/docs/api To create a new sandbox instance, send a POST request to the /sandboxes endpoint with a JSON body specifying the template and memory allocation. The 'template' parameter determines the initial environment, and 'memory' sets the RAM in MB. ```json { "template": "nextjs", "memory": 2048 } ``` -------------------------------- ### Create Full-Stack Sandbox - Node.js Source: https://www.ose.sh/docs/nodejs Sets up a full-stack sandbox environment with Node.js and Python using the OSE Cloud SDK. This template includes database tools and is ready for API development. It utilizes the 'fullstack' template identifier. ```javascript const sandbox = await ose.sandboxes.create({ template: 'fullstack', memory: 2048, cpu: 1 }); ``` -------------------------------- ### Create Python Sandbox Environment with OSE Cloud Source: https://www.ose.sh/docs/python This code snippet demonstrates how to create a secure, isolated Python sandbox environment using the OSE Cloud SDK. It specifies the 'python' template, memory allocation (2048 MB), and CPU cores (1). ```javascript const sandbox = await ose.sandboxes.create({ template: 'python', memory: 2048, cpu: 1 }); ``` -------------------------------- ### Create React Sandbox - Node.js Source: https://www.ose.sh/docs/nodejs Initializes a React sandbox with Vite for modern web development via the OSE Cloud SDK. This template supports React 19, TypeScript, a fast development server, and optimized builds. The 'react' template identifier is used. ```javascript const sandbox = await ose.sandboxes.create({ template: 'react', memory: 2048, cpu: 1 }); ``` -------------------------------- ### Initialize OSECloud SDK with API Key (Node.js) Source: https://www.ose.sh/docs/authentication This Node.js code snippet shows how to initialize the OSE Cloud SDK using an API key stored in an environment variable. It utilizes the `@ose-cloud/sdk` library and assumes the API key is accessible via `process.env.OSE_API_KEY`. ```javascript import { OSECloud } from '@ose-cloud/sdk'; const ose = new OSECloud({ apiKey: process.env.OSE_API_KEY }); ``` -------------------------------- ### Create Vue.js Sandbox Source: https://www.ose.sh/docs/web-frameworks Creates a Vue.js sandbox with specified memory and CPU. This template supports Vue.js 3 with Composition API and TypeScript. ```javascript const sandbox = await ose.sandboxes.create({ template: 'vue', memory: 2048, cpu: 1 }); ``` -------------------------------- ### Create Sandbox Response Body Source: https://www.ose.sh/docs/api Upon successful creation of a sandbox, the API returns a JSON response containing details of the newly created sandbox. This includes its unique 'id', current 'status', and the 'template' used. ```json { "sandbox": { "id": "sb_1a2b3c4d5e6f", "status": "running", "template": "nextjs" } } ``` -------------------------------- ### Create Deployment Request Body Source: https://www.ose.sh/docs/api To deploy sandbox contents to OSE Cloud, send a POST request to the /deployments endpoint. The request body requires the deployment 'name', the 'sandboxId' to deploy from, and the 'port' the application will listen on. ```json { "name": "my-app", "sandboxId": "sb_1a2b3c4d5e6f", "port": 3000 } ``` -------------------------------- ### Create Expo Mobile App Sandbox (JavaScript) Source: https://www.ose.sh/docs/other-languages This snippet demonstrates how to create a sandbox environment for mobile application development using the Expo template. It requires the 'ose' object and specifies memory and CPU resources for the sandbox. This is exclusively for iOS and Android development. ```javascript const sandbox = await ose.sandboxes.create({ template: 'expo', memory: 2048, cpu: 1 }); ``` -------------------------------- ### Implement Rate Limiting and Exponential Backoff (JavaScript) Source: https://www.ose.sh/docs/troubleshooting This snippet provides a robust solution for handling 'Rate Limit Exceeded (429)' errors. It utilizes `p-limit` to control concurrent requests and implements an exponential backoff strategy with retries for operations that encounter rate limiting. This ensures resilient API interaction. ```javascript import pLimit from 'p-limit'; // Limit concurrent requests const limit = pLimit(5); // Batch sandbox operations async function batchCreate(configs) { return Promise.all( configs.map(config => limit(() => ose.sandboxes.create(config)) ) ); } // Implement exponential backoff async function withRetry(fn, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error) { if (error.status === 429 && i < maxRetries - 1) { const delay = Math.pow(2, i) * 1000; console.log(`Rate limited. Retrying in ${delay}ms...`); await new Promise(r => setTimeout(r, delay)); continue; } throw error; } } } // Usage const sandbox = await withRetry(() => ose.sandboxes.create({ template: 'nextjs' }) ); ``` -------------------------------- ### Increase Sandbox Creation Timeout (JavaScript) Source: https://www.ose.sh/docs/troubleshooting This code snippet demonstrates how to increase the timeout duration for sandbox creation in OSE. It involves configuring the `OSE` client with a custom `timeout` value and setting `retries` and `retryDelay` for the sandbox creation process. This is useful for addressing Sandbox Creation Timeout errors. ```javascript const ose = new OSE({ apiKey: process.env.OSE_API_KEY, timeout: 120000 // 2 minutes }); const sandbox = await ose.sandboxes.create({ template: 'nextjs', // Retry configuration retries: 3, retryDelay: 5000 }); ``` -------------------------------- ### Write File Request Body Source: https://www.ose.sh/docs/api To write a file to a sandbox's filesystem, send a POST request to the /sandboxes/:id/files endpoint. The request body must include the 'path' where the file should be created within the sandbox and its 'content'. ```json { "path": "/app/index.js", "content": "console.log('Hello World!');" } ``` -------------------------------- ### Set API Key as Environment Variable (Bash) Source: https://www.ose.sh/docs/authentication This snippet demonstrates how to set your OSE Cloud API key as an environment variable. This is the recommended method for securely storing and accessing your API key in shell environments. ```bash export OSE_API_KEY="your-api-key-here" ``` -------------------------------- ### DELETE /sandboxes/:id Source: https://www.ose.sh/docs/api Terminate and delete a sandbox. ```APIDOC ## DELETE /sandboxes/:id ### Description Terminate and delete a sandbox. ### Method DELETE ### Endpoint `/sandboxes/:id` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the sandbox to delete. ``` -------------------------------- ### Implement Reconnection Logic for Terminal (JavaScript) Source: https://www.ose.sh/docs/troubleshooting This JavaScript class, `ResilientTerminal`, demonstrates how to handle unexpected WebSocket disconnections for terminal sessions. It implements a reconnection mechanism with a maximum number of retries and exponential backoff delays, ensuring a more stable terminal experience. ```javascript class ResilientTerminal { constructor(sandbox) { this.sandbox = sandbox; this.maxReconnects = 5; this.reconnectCount = 0; } async execute(command) { try { return await this.sandbox.terminal.execute(command); } catch (error) { if (this.isConnectionError(error) && this.reconnectCount < this.maxReconnects) { this.reconnectCount++; console.log(`Reconnecting... (attempt ${this.reconnectCount})`); await this.reconnect(); return this.execute(command); } throw error; } } isConnectionError(error) { return error.code === 'ECONNRESET' || error.code === 'ETIMEDOUT' || error.message.includes('WebSocket'); } async reconnect() { await new Promise(r => setTimeout(r, 1000 * this.reconnectCount)); await this.sandbox.terminal.connect(); } } ``` -------------------------------- ### Authentication Source: https://www.ose.sh/docs/api All API requests require authentication using a Bearer token. Never expose your API key in client-side code. ```APIDOC ## Authentication All API requests require authentication using a Bearer token. ```bash curl -X GET https://ose.sh/api/sandboxes \ -H "Authorization: Bearer ose_sk_live_..." ``` Never expose your API key in client-side code. ``` -------------------------------- ### Error Codes Source: https://www.ose.sh/docs/api Common error codes returned by the OSE Cloud API. ```APIDOC ## Error Codes | Code | Description | |---|---| | `400` | Bad Request - Invalid parameters | | `401` | Unauthorized - Invalid API key | | `404` | Not Found - Resource does not exist | | `429` | Too Many Requests - Rate limit exceeded | | `500` | Internal Server Error | ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.