comfy-sparkle-sdk
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

Comfy Sparkle SDK

A TypeScript SDK for interacting with ComfyUI servers. This package provides a simple interface for executing ComfyUI workflows, monitoring their progress, and retrieving results.

Features

  • Connect to ComfyUI servers via WebSocket
  • Load, modify and execute workflows
  • Track execution progress in real-time
  • React component for easy UI integration
  • Browser and Node.js support
  • TypeScript typings for all APIs

Installation

npm install comfy-sparkle-sdk

Usage

Node.js Example

import { ComfyClient, WorkflowManager } from 'comfy-sparkle-sdk';
import path from 'path';

async function main() {
  // Initialize the client
  const client = new ComfyClient({
    serverUrl: 'http://192.168.50.232:8188',
    debug: true
  });

  try {
    // Connect to the server
    await client.connect();
    console.log('Connected to ComfyUI server');
    
    // Load workflows
    const workflowManager = new WorkflowManager();
    workflowManager.loadFromDirectory(path.join(__dirname, 'workflows'));
    
    // Get a workflow by ID
    const workflow = workflowManager.getWorkflow('txt2img');
    
    if (!workflow) {
      console.error('Workflow not found');
      return;
    }
    
    // Execute with custom inputs
    const promptId = await client.executeWorkflow(workflow, {
      '2': { // Node ID for positive prompt
        text: 'A beautiful sunset over mountains, photorealistic, 8k'
      },
      '4': { // Node ID for empty latent image
        width: 768,
        height: 512
      }
    });
    
    console.log(`Execution started with prompt ID: ${promptId}`);
    
    // Register for execution progress updates
    client.onEvent('executing', (event) => {
      console.log(`Progress: ${event.data.value.toFixed(2)}%`);
    });
    
    // Wait for execution to complete
    const result = await client.waitForExecution(promptId);
    console.log('Execution completed!');
    
    // Display result info
    if (result.outputs?.images) {
      console.log('Generated images:');
      result.outputs.images.forEach((image, index) => {
        console.log(`Image ${index + 1}: ${image.filename || image}`);
      });
    }
  } catch (error) {
    console.error('Error:', error);
  } finally {
    // Disconnect
    client.disconnect();
  }
}

main();

React Example

import React from 'react';
import { ComfyWorkflowRunner } from 'comfy-sparkle-sdk';

const ComfyUIComponent: React.FC = () => {
  const serverUrl = 'http://192.168.50.232:8188';
  
  // Your workflow JSON
  const workflow = {
    "1": {
      "inputs": {
        "ckpt_name": "dreamshaper_8.safetensors"
      },
      "class_type": "CheckpointLoaderSimple",
      "_meta": {
        "title": "Load Model"
      }
    },
    "2": {
      "inputs": {
        "text": "A beautiful landscape with mountains and a lake, photorealistic, 8k"
      },
      "class_type": "CLIPTextEncode",
      "_meta": {
        "title": "Positive Prompt"
      }
    },
    // ... rest of workflow nodes
  };
  
  return (
    <div>
      <h1>Image Generator</h1>
      
      <ComfyWorkflowRunner
        serverUrl={serverUrl}
        workflow={workflow}
        defaultInputs={{
          '2': { text: 'Beautiful sunset over ocean' }
        }}
        onComplete={(result) => console.log('Generation completed:', result)}
      />
    </div>
  );
};

export default ComfyUIComponent;

Browser Usage

For browser environments, use the BrowserComfyClient which uses native browser APIs:

import { BrowserComfyClient } from 'comfy-sparkle-sdk';

const client = new BrowserComfyClient({
  serverUrl: 'http://192.168.50.232:8188'
});

// Rest of the code is the same as the Node.js example

API Reference

ComfyClient / BrowserComfyClient

The main client for interacting with ComfyUI servers.

Constructor

new ComfyClient(options: ClientOptions)

Options:

  • serverUrl: ComfyUI server URL
  • autoConnect: Whether to automatically connect (default: true)
  • debug: Whether to log debug information (default: false)

Methods

  • connect(): Connect to the server
  • disconnect(): Disconnect from the server
  • getServerInfo(): Get server information
  • loadWorkflow(path): Load a workflow from the server
  • uploadWorkflow(workflow, filename): Upload a workflow to the server
  • executeWorkflow(workflow, inputs): Execute a workflow with optional input modifications
  • getExecutionResult(promptId): Get the result of an execution
  • waitForExecution(promptId, timeout): Wait for an execution to complete
  • onEvent(eventType, callback): Register a callback for events

WorkflowManager

Utility for managing ComfyUI workflows.

Methods

  • loadFromDirectory(dir): Load workflows from a directory
  • loadFromFile(id, filePath): Load a workflow from a file
  • getWorkflow(id): Get a workflow by ID
  • getMetadata(): Get all workflow metadata
  • saveMetadata(filePath): Save metadata to a file

ComfyWorkflowRunner

React component for running ComfyUI workflows.

Props

  • serverUrl: ComfyUI server URL
  • workflow: Workflow to execute
  • defaultInputs: Default inputs for the workflow
  • autoExecute: Whether to automatically execute on mount
  • onStart: Callback when execution starts
  • onComplete: Callback when execution completes
  • onError: Callback when execution fails
  • onProgress: Callback for progress updates
  • renderWorkflow: Custom renderer for the workflow UI
  • debug: Whether to enable debug logs

License

MIT

Package Sidebar

Install

npm i comfy-sparkle-sdk

Weekly Downloads

2

Version

1.0.0

License

MIT

Unpacked Size

93.3 kB

Total Files

25

Last publish

Collaborators

  • sparkletree