npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@grasplabs/grasp

v0.4.16

Published

TypeScript SDK for browser automation and secure command execution in highly available and scalable cloud browser environments

Readme

🚀 Grasp SDK

npm version PyPI version Python License: MIT

Multi-language SDK for browser automation and secure command execution in highly available and scalable cloud browser environments

Grasp SDK provides a type-safe, event-driven API for browser automation and command execution in isolated cloud environments. Available for both TypeScript/JavaScript and Python.

✨ Features

  • 🌐 Cloud Browser Automation: Launch and control Chromium browsers in isolated cloud environments
  • 🔗 CDP Integration: Chrome DevTools Protocol support with optimized WebSocket frame parsing
  • Command Execution: Execute shell commands with real-time monitoring and enhanced logging
  • 🔒 Secure Execution: Run code in isolated E2B cloud environments
  • 🧪 TypeScript Support: Full type safety and IntelliSense with improved development environment
  • 🛠️ Developer Experience: Enhanced debugging capabilities and error handling

🚀 Quick Start

Installation

# Install the package
npm install @grasplabs/grasp
# or
yarn add @grasplabs/grasp
# or
pnpm add @grasplabs/grasp

Initialization

# Generate API key and initialize configuration
npx -y grasp-keygen <your-app-id>

This will create a .env.grasp file with your credentials.

Configuration

After running grasp-keygen, you'll have a .env.grasp file with your credentials:

GRASP_APP_ID=your-app-id
GRASP_APP_KEY=your-app-key

Basic Usage

// Import types if needed
import type { GraspOptions } from '@grasplabs/grasp';

import grasp from '@grasplabs/grasp';
import { chromium } from 'playwright';

async function main() {
  // Launch browser in cloud environment with enhanced options
  const connection = await grasp.launchBrowser({ 
    // API key is auto-loaded from .env.grasp
    type: 'chromium',        // Browser type: 'chromium' or 'chrome-stable'
    headless: true,          // Run in headless mode
    adblock: false,          // Disable adblock extension
    timeout: 150000,         // Connection timeout in milliseconds
    keepAliveMS: 5000,       // Keep browser alive for 5 sec
    logLevel: 'info',        // Set logging level
    debug: false,            // Disable debug mode for production
  });

  // Connect to the browser using Playwright
  const browser = await chromium.connectOverCDP(connection.wsUrl, {
    timeout: 150000,
  });

  // Create a new page and navigate
  const page = await browser.newPage();
  await page.goto('https://getgrasp.ai/', { waitUntil: 'domcontentloaded' });
  await page.screenshot({ path: 'grasp-ai.png' });
  await page.close();
   
  // Create another page with custom content
  const context = browser.contexts()[0] || await browser.newContext();
  const page2 = await context.newPage();
  await page2.setContent('<h1>Hello Grasp</h1>', { waitUntil: 'networkidle' });
  await page2.screenshot({ path: 'hello-world.png', fullPage: true });
  await page2.close();

  // Clean up
  await context.close();
  await browser.close();
}

main();

📚 API Reference

grasp.launchBrowser(options)

Launches a browser instance in the cloud environment.

Parameters:

  • options (object, optional):
    • key (string): Your Grasp API key (loaded from .env.grasp by default)
    • type (string, optional): Browser type to launch. Default: 'chromium'. Available: 'chromium', 'chrome-stable'
    • headless (boolean, optional): Whether to run browser in headless mode. Default: true
    • adblock (boolean, optional): Whether to enable adblock extension. Default: false
    • timeout (number, optional): Connection timeout in milliseconds. Default: 30000
    • keepAliveMS (number, optional): Keep-alive duration in milliseconds. Default: 0
    • logLevel (string, optional): Logging level. Available: 'debug', 'info', 'warn', 'error'. Default: 'info'
    • debug (boolean, optional): Enable debug mode for detailed logging. Default: false
    • launchTimeout (number, optional): Browser launch timeout in milliseconds. Default: 30000
    • envs (object, optional): Environment variables for the browser process
    • slowMo (number, optional): Slows down operations by specified milliseconds

Returns:

  • Promise<Connection>: Connection object with:
    • id (string): Unique browser instance ID
    • wsUrl (string): WebSocket URL for CDP connection (recommended)
    • httpUrl (string): HTTP URL for CDP connection (legacy)

Example:

const connection = await grasp.launchBrowser({
  // key: process.env.GRASP_APP_KEY, // Loaded from .env.grasp
  type: 'chromium',           // Browser type: 'chromium' or 'chrome-stable'
  headless: true,             // Run in headless mode
  adblock: false,             // Enable adblock extension
  timeout: 150000,            // Connection timeout
  keepAliveMS: 3600000,       // Keep browser alive for 1 hour
  logLevel: 'info',           // Logging level: 'debug', 'info', 'warn', 'error'
  debug: false,               // Enable debug mode
  launchTimeout: 30000,       // Browser launch timeout
  envs: {                     // Environment variables
    'CUSTOM_VAR': 'value'
  }
});

Using with Playwright

After launching a browser, connect to it using Playwright's connectOverCDP method:

import { chromium } from 'playwright';

const connection = await grasp.launchBrowser();
const browser = await chromium.connectOverCDP(connection.wsUrl, {
  timeout: 150000
});

// Use browser as normal Playwright browser instance
const page = await browser.newPage();
// ... your automation code

await browser.close();

🐍 Python SDK

Grasp also provides a Python SDK with the same powerful features for browser automation and command execution.

Installation

# Install from PyPI (latest: v0.1.6)
pip install grasp_sdk

# Install from source
pip install -e ./py-src

# Install with development dependencies
pip install -e "./py-src[dev]"

Environment Setup

Create a .env.grasp file or set environment variables:

# Required
GRASP_KEY=your_grasp_api_key_here

# Optional
GRASP_LOG_LEVEL=info
GRASP_TIMEOUT=3600000

Basic Usage

import asyncio
import os
from playwright.async_api import async_playwright
from dotenv import load_dotenv
from grasp_sdk import GraspServer

# 加载环境变量
load_dotenv(".env.grasp")

async def main():
    """演示 Grasp SDK 的基本用法"""
    
    # 检查 API key
    api_key = os.getenv('GRASP_KEY')
    if not api_key:
        print("⚠️ 请设置 GRASP_KEY 环境变量")
        return

    print("🚀 正在启动浏览器...")

    # 使用 GraspServer 上下文管理器
    async with GraspServer({
        'timeout': 3600000,  # 容器最长运行1小时
    }) as connection:
        
        print(f"WebSocket URL: {connection['ws_url']}")
        
        # 使用 Playwright 连接到 CDP
        async with async_playwright() as p:
            browser = await p.chromium.connect_over_cdp(
                connection['ws_url'],
                timeout=150000
            )
            
            # 创建页面并访问网站
            page = await browser.new_page()
            await page.goto('https://getgrasp.ai/', wait_until='domcontentloaded')
            await page.screenshot(path='grasp-ai.png')
            
            # 创建自定义内容页面
            page2 = await browser.new_page()
            await page2.set_content('<h1>Hello Grasp</h1>', wait_until='networkidle')
            await page2.screenshot(path='hello-world.png', full_page=True)
            
            # 清理资源
            await page.close()
            await page2.close()
            await browser.close()
            
        print('✅ 任务完成,资源自动清理')

if __name__ == "__main__":
    asyncio.run(main())

Python API Reference

GraspServer(sandbox_config=None)

Main class for browser automation and command execution.

Parameters:

  • sandbox_config (dict, optional): Sandbox configuration overrides
    • template (str): E2B template to use (default: 'python')
    • timeout (int): Connection timeout in milliseconds (default: 30000)
    • api_key (str): E2B API key (loaded from environment by default)

Methods:

  • async start(): Start the sandbox environment
  • async execute_command(command, options=None): Execute shell command
  • async run_script(script_path, options=None): Run script file
  • async create_browser_task(): Create browser automation task
  • async close(): Clean up and close connections

Example with Browser Automation:

import asyncio
from grasp_sdk import GraspServer

async def browser_example():
    server = GraspServer()
    
    try:
        await server.start()
        
        # Launch browser
        browser = await server.launch_browser({
            "headless": True,
            "timeout": 150000
        })
        
        # Navigate and interact
        await browser.navigate("https://getgrasp.ai/")
        await browser.screenshot("grasp-ai.png")
        
        # Execute JavaScript
        title = await browser.evaluate("document.title")
        print(f"Page title: {title}")
        
    finally:
        await server.close()

asyncio.run(browser_example())

Features

  • 🔒 Secure Execution: Run commands in isolated E2B cloud environments
  • 🌐 Browser Automation: Control Chromium browsers with async/await
  • Real-time Communication: WebSocket-based command execution
  • 🧪 Type Safety: Complete type hints with Pydantic models
  • 🔄 Async/Await: Full async support for modern Python development
  • 🛠️ Developer Experience: Enhanced debugging and error handling

🔗 Language Support

Grasp SDK is available in multiple languages:

  • TypeScript/JavaScript: @grasplabs/grasp (this package)
  • Python: grasp_sdk (see Python SDK section above)

Both SDKs provide the same core functionality with language-specific optimizations and idioms.

📋 Release History

Python SDK (grasp_sdk)

v0.1.8 (2025-01-27)

  • 🚀 Latest release with file path handling feature
  • 🔧 Added support for file paths starting with '/home/user/' in run_script
  • ⚡ Aligned Python SDK behavior with Node.js SDK runScript function
  • 📦 Enhanced backward compatibility and flexibility

v0.1.7 (2025-01-27)

  • 🚀 Configuration simplification release
  • 🔧 Removed templateId configuration for simplified setup
  • ⚡ Code structure optimization and cleanup
  • 📦 Enhanced package stability and maintainability

v0.1.6 (2025-01-27)

  • 🚀 Version synchronization release
  • 🔧 Continuous improvements and optimizations
  • ⚡ Enhanced stability and performance
  • 📦 Updated package metadata

v0.1.5 (2025-01-27)

  • 🚀 Latest release with continuous improvements
  • 📚 Enhanced documentation and examples
  • 🔧 Stability improvements and optimizations
  • 📦 Updated package metadata

v0.1.4 (2025-01-27)

  • ✅ Version synchronization with project metadata
  • 📦 Updated package metadata and documentation
  • 🔧 Enhanced build and publishing workflow
  • 📚 Improved README with version badges and installation instructions

v0.1.0 (2025-01-27)

  • 🎉 Initial release of Python SDK
  • 🌐 Core browser automation functionality
  • 🔒 Secure command execution in E2B environments
  • 🧪 Full async/await support with type hints
  • 📖 Complete API compatibility with TypeScript version

TypeScript/JavaScript SDK (@grasplabs/grasp)

v0.1.3 (2025-01-27)

  • 🚀 Latest release with enhanced stability
  • 📦 Updated package metadata and build process
  • 🔧 Improved configuration and error handling
  • 📚 Enhanced documentation and examples

Latest Updates (v0.1.1+)

  • 🚀 Enhanced browser automation capabilities with new configuration options
  • ⚡ Improved CDP integration and WebSocket frame parsing
  • 🛠️ Better developer experience with enhanced debugging and logging
  • 🔧 Added new parameters:
    • keepAliveMS: Configure browser keep-alive duration
    • logLevel: Granular logging control ('debug', 'info', 'warn', 'error')
    • adblock: Built-in adblock extension support
    • launchTimeout: Configurable browser launch timeout
    • envs: Environment variables for browser process
  • 🎯 Optimized performance and error handling
  • 📚 Updated documentation with comprehensive parameter examples
  • 🔄 Enhanced graceful shutdown and resource cleanup