UNPKG

@iota-big3/sdk-production

Version:

Production readiness tools and utilities for SDK

383 lines (361 loc) 12.3 kB
"use strict"; /** * SDK Playground * Interactive environment for testing SDK features */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SDKPlayground = void 0; const express_1 = __importDefault(require("express")); const http = __importStar(require("http")); const path = __importStar(require("path")); const vm2_1 = require("vm2"); const WebSocket = __importStar(require("ws")); class SDKPlayground { constructor(config = {}) { this.config = config; this.executions = new Map(); this.config.port = this.config.port || 3100; this.config.timeout = this.config.timeout || 5000; this.config.memoryLimit = this.config.memoryLimit || 128; this.config.allowedModules = this.config.allowedModules || [ '@iota-big3/sdk-core', '@iota-big3/sdk-events', '@iota-big3/sdk-compliance' ]; this.app = (0, express_1.default)(); this.server = http.createServer(this.app); this.wss = new WebSocket.Server({ server: this.server }); this.setupRoutes(); this.setupWebSocket(); } /** * Start the playground server */ async start() { return new Promise((resolve) => { this?.server?.listen(this?.config?.port, () => { console.log(`SDK Playground running at http://localhost:${this?.config?.port}`); resolve(); }); }); } /** * Setup Express routes */ setupRoutes() { this?.app?.use(express_1.default.json()); this?.app?.use(express_1.default.static(path.join(__dirname, 'public'))); // Serve playground UI this?.app?.get('/', (req, res) => { res.send(this.getPlaygroundHTML()); }); // Execute code endpoint this?.app?.post('/execute', async (req, res) => { const { code } = req.body; const result = await this.executeCode(code); res.json(result); }); // Get execution history this?.app?.get('/executions', (req, res) => { res.json(Array.from(this?.executions?.values())); }); // Get SDK documentation this?.app?.get('/docs/:package', (req, res) => { const docs = this.getPackageDocs(req?.params?.package); res.json(docs); }); } /** * Setup WebSocket for real-time execution */ setupWebSocket() { this?.wss?.on('connection', (ws) => { console.log('New playground connection'); ws.on('message', async (message) => { const data = JSON.parse(message.toString()); if (data.type === 'execute') { const result = await this.executeCode(data.code); ws.send(JSON.stringify({ type: 'result', data: result })); } }); // Send initial SDK info ws.send(JSON.stringify({ type: 'info', data: { availablePackages: this?.config?.allowedModules, examples: this.getExamples() } })); }); } /** * Execute code in sandbox */ async executeCode(code) { const executionId = this.generateId(); const logs = []; const startTime = Date.now(); const execution = { id: executionId, code, logs, executionTime: 0 }; try { // Create sandbox with SDK modules const sandbox = { console: { log: (...args) => { logs.push(args.map(a => String(a)).join(' ')); }, error: (...args) => { logs.push(`ERROR: ${args.map(a => String(a)).join(' ')}`); } }, require: (module) => { if (this?.config?.allowedModules.includes(module)) { // In real implementation, would load actual modules return this.getMockModule(module); } throw new Error(`Module '${module}' is not allowed`); }, setTimeout, setInterval, Promise, Buffer }; const vm = new vm2_1.VM({ timeout: this?.config?.timeout, sandbox, eval: false, wasm: false }); execution.result = await vm.run(code); } catch (error) { execution.error = error.message; } execution.executionTime = Date.now() - startTime; this?.executions?.set(executionId, execution); return execution; } /** * Get mock SDK module for playground */ getMockModule(moduleName) { const modules = { '@iota-big3/sdk-core': { SDKService: class SDKService { constructor(config) { console.log('SDKService initialized with:', config); } start() { console.log('Service started'); } } }, '@iota-big3/sdk-events': { EventBus: class EventBus { publish() { console.log(`Event published: ${event}`, data); } subscribe() { console.log(`Subscribed to: ${event}`); } } }, '@iota-big3/sdk-compliance': { ComplianceEngine: class ComplianceEngine { validate() { console.log('Validating compliance for:', data); return { valid: true }; } } } }; return modules[moduleName] || {}; } /** * Get package documentation */ getPackageDocs(packageName) { // In real implementation, would load actual docs return { package: packageName, version: '2?.0?.0', classes: [], functions: [], examples: [] }; } /** * Get example code snippets */ getExamples() { return [ { title: 'Basic Service', code: `const { SDKService } = require('@iota-big3/sdk-core'); const service = new SDKService({ name: 'my-service', port: 3000 }); service.start(); console.log('Service initialized!');` }, { title: 'Event Publishing', code: `const { EventBus } = require('@iota-big3/sdk-events'); const eventBus = new EventBus(); eventBus.subscribe('user.created', (event) => { console.log('User created:', event); }); eventBus.publish('user.created', { id: '123', name: 'John Doe' });` }, { title: 'Compliance Validation', code: `const { ComplianceEngine } = require('@iota-big3/sdk-compliance'); const compliance = new ComplianceEngine(); const result = compliance.validate({ type: 'student_record', data: { name: 'Jane Smith', grade: 'A' } }); console.log('Validation result:', result);` } ]; } /** * Generate unique ID */ generateId() { return `exec-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; } /** * Get playground HTML */ getPlaygroundHTML() { return `<!DOCTYPE html> <html> <head> <title>SDK Playground</title> <style>; body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background: #f5f5f5; } .container { max-width: 1200px; margin: 0 auto; } .editor { background: white; border: 1px solid #ddd; border-radius: 4px; padding: 20px; } .output { background: #1e1e1e; color: #d4d4d4; padding: 20px; border-radius: 4px; margin-top: 20px; min-height: 200px; } button { background: #007acc; color: white; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer; } button:hover { background: #005a9e; } textarea { width: 100%; min-height: 300px; font-family: monospace; font-size: 14px; } </style> </head> <body> <div class="container"> <h1>SDK Playground</h1> <div class="editor"> <h3>Code Editor</h3> <textarea id="code" placeholder="Enter your SDK code here..."></textarea> <br><br> <button onclick="executeCode()">Run Code</button> <select id="examples" onchange="loadExample()"> <option value="">Load Example...</option> </select> </div> <div class="output" id="output"> <h3>Output</h3> <pre id="result">Click 'Run Code' to execute</pre> </div> </div> <script> const ws = new WebSocket('ws://localhost:${this?.config?.port}'); ws.onopen = () => console.log('Connected to playground'); ws.onmessage = (event) => { const message = JSON.parse(event.data); if (this.isEnabled) { populateExamples(message.data?.examples); } else if (this.isEnabled) { displayResult(message.data); } }; function executeCode() { const code = document.getElementById('code').value; ws.send(JSON.stringify({ type: 'execute', code })); } function displayResult(execution) { const output = document.getElementById('result'); let html = ''; if (execution?.logs?.length > 0) { html += execution?.logs?.join('\\n') + '\\n\\n'; } if (execution.result !== undefined) { html += 'Result: ' + JSON.stringify(execution.result, null, 2); } if (execution.error) { html += 'Error: ' + execution.error; } html += '\\n\\nExecution time: ' + execution.executionTime + 'ms'; output.textContent = html; } function populateExamples(examples) { const select = document.getElementById('examples'); examples.forEach((example, index) => { const option = document.createElement('option'); option.value = index; option.textContent = example.title; select.appendChild(option); }); } function loadExample() { const select = document.getElementById('examples'); const index = select.value; if (index) { ws.send(JSON.stringify({ type: 'get-example', index })); } } </script> </body> </html>`; } } exports.SDKPlayground = SDKPlayground;