0.3.3 • Published 11 months ago

@earnbasejs/plugin v0.3.3

Weekly downloads
-
License
MIT
Repository
-
Last release
11 months ago

EarnBase Plugin SDK

npm version License: MIT

Official SDK for developing plugins for the EarnBase platform.

Installation

# Using npm
npm install @earnbasejs/plugin

# Using yarn 
yarn add @earnbasejs/plugin

Features

  • šŸš€ Fast and simple plugin development
  • šŸ”’ Secure sandbox execution
  • šŸ“¦ Hot reload during development
  • šŸ”„ Message queue integration
  • šŸ“Š Resource monitoring
  • šŸ›  CLI development tools
  • šŸ“ Complete type definitions

Quick Start

  1. Create new plugin:
# Create plugin from template
earnbase create my-plugin

# Navigate to plugin directory
cd my-plugin

# Install dependencies
yarn install
  1. Code your plugin:
import { BasePlugin, PluginMetadata } from '@earnbasejs/plugin';

export class MyPlugin extends BasePlugin {
  // Define plugin metadata
  public static metadata: PluginMetadata = {
    name: 'my-plugin',
    version: '1.0.0',
    description: 'My awesome plugin',
    tasks: [
      {
        name: 'example',
        description: 'Example task',
        inputSchema: [
          {
            name: 'message',
            type: 'string',
            required: true,
            description: 'Message to process'
          }
        ],
        outputSchema: [
          {
            name: 'result',
            type: 'string',
            description: 'Processed result'
          }
        ]
      }
    ],
    resources: {
      cpu: '0.5',
      memory: '512Mi',
      timeout: 300
    }
  };

  // Register tasks
  protected registerTasks(): void {
    this.registerTask('example', {
      name: 'example',
      description: 'Example task',
      async validate(input) {
        return !!input.message;
      },
      async execute(input) {
        // Task implementation
        return { result: `Processed: ${input.message}` };
      }
    });
  }
}
  1. Development:
# Start development server with hot reload
yarn dev

# Build for production
yarn build

# Run tests
yarn test

Detailed Guide

Plugin Structure

my-plugin/
ā”œā”€ā”€ src/
│   └── index.ts           # Plugin implementation
ā”œā”€ā”€ tests/
│   └── index.test.ts      # Test files
ā”œā”€ā”€ package.json           
ā”œā”€ā”€ tsconfig.json          
└── README.md             

Plugin Lifecycle

  1. Initialization
async onInit(): Promise<void> {
  // Plugin initialization
}
  1. Task Execution
async executeTask(name: string, input: any): Promise<any> {
  // Execute specific task
}
  1. Cleanup
async onStop(): Promise<void> {
  // Cleanup resources
}

Message Queue Integration

// Report progress
await this.context.reportProgress({
  taskName: 'example',
  status: ExecutionStatus.RUNNING,
  progress: 50,
  message: 'Processing...'
});

// Send output
await this.context.sendOutput({
  result: 'success'
});

Resource Management

@Plugin({
  resources: {
    cpu: '0.5',      // CPU limit
    memory: '512Mi', // Memory limit
    timeout: 300     // Execution timeout
  }
})

Error Handling

try {
  await this.processData();
} catch (error) {
  this.logger.error('Processing failed', error);
  throw new PluginError('PROCESSING_FAILED', error.message);
}

CLI Commands

# Create new plugin
earnbase create my-plugin

# Create new plugin using AI
earnbase create:ai

# Development
earnbase dev

# Build
earnbase build

# Deploy
earnbase deploy

Testing

import { PluginTester } from '@earnbasejs/plugin/testing';

describe('MyPlugin', () => {
  let tester: PluginTester<MyPlugin>;

  beforeEach(async () => {
    tester = new PluginTester({
      plugin: MyPlugin,
      context: { /* test context */ }
    });
    await tester.setup();
  });

  it('should process correctly', async () => {
    const result = await tester.execute('example', {
      message: 'test'
    });
    expect(result.result).toBe('Processed: test');
  });
});

Best Practices

  1. Task Design
  • Each task performs a specific function
  • Careful input validation
  • Regular progress reporting
  • Graceful error handling
  1. Resource Usage
  • Monitor resource consumption
  • Clean up resources after use
  • Set appropriate timeouts
  • Handle rate limiting
  1. Security
  • Validate all inputs
  • Use secure defaults
  • Follow least privilege principle
  • Sanitize outputs
  1. Testing
  • Unit tests for each task
  • Integration tests
  • Performance tests
  • Security tests

Example Plugins

  1. Facebook Plugin:
export class FacebookPlugin extends BasePlugin {
  protected registerTasks(): void {
    this.registerTask('createPost', {
      async execute(input) {
        // Create Facebook post
      }
    });
  }
}
  1. Grass Airdrop Plugin:
export class GrassPlugin extends BasePlugin {
  protected registerTasks(): void {
    this.registerTask('dailyCheckIn', {
      async execute() {
        // Daily check in
      }
    });
  }
}

Task Types

1. Simple Task

Basic task implementation with single operation.

2. Retryable Task

Task with automatic retry on failure:

this.registerTask('retryableTask', {
  retryStrategy: {
    maxAttempts: 3,
    delay: 1000,  
    backoff: true
  }
});

3. Concurrent Task

Task that processes multiple items in parallel:

this.registerTask('concurrentTask', {
  maxConcurrent: 5,
  async execute(items) {
    return Promise.all(items.map(this.processItem));
  }
});

4. Long Running Task

Task for long operations with progress tracking:

this.registerTask('longTask', {
  async execute() {
    await this.setProgress(0);
    // Long operation
    await this.setProgress(100);
  }
});

AI-Powered Plugin Creation

Create a new plugin with AI assistance:

# Create plugin using AI
earnbase create:ai

# Follow the interactive prompts:
1. Configure OpenAI settings (first time only)
   - Enter OpenAI API key
   - Optionally set custom API endpoint
   - Select model (GPT-4, GPT-3.5-turbo, etc)

2. Enter plugin details
   - Name
   - Description  
   - Author

3. Describe your plugin's tasks
   - What should each task do?
   - Input/output requirements
   - Special features (retry, concurrent, etc)

4. Review and customize generated code
   - Preview generated code
   - Add validation
   - Add test cases
   - Add documentation

5. Create project files
   - Generated plugin code
   - Test files
   - README & documentation

The AI will help you create:

  • Properly structured plugin code
  • Input validation
  • Error handling
  • Progress tracking
  • Resource management
  • Test cases
  • Documentation

You can then modify and extend the generated code as needed.

Contributing

  1. Fork repository
  2. Create feature branch
  3. Commit changes
  4. Push to branch
  5. Create Pull Request

Support

License

MIT License

Copyright (c) 2024 EarnBase Team