UNPKG

@permaweb/beam

Version:

A hyperbeam cli tool

122 lines (102 loc) 3.17 kB
#!/usr/bin/env node import { program } from 'commander' import { connect, createSigner } from '@permaweb/aoconnect' import fs from 'fs' import path from 'path' import url from 'url' import os from 'os' // Initialize CLI program program .name('beam') .description('A hyperbeam cli') .version('1.0.0') .usage('[options] <url>') .option('-X, --request <method>', 'Request method to use', 'GET') .option('-H, --header <header>', 'Pass custom header(s) to server', [], (val, prev) => [...prev, val]) .option('-d, --data <data>', 'HTTP POST data') .option('-o, --output <file>', 'Write to file instead of stdout') .option('-v, --verbose', 'Make the operation more talkative') .option('-f, --file <file>', 'Read data from file') .option('--raw', 'Display raw response data'); // Parse command line arguments program.parse(); const options = program.opts(); // Get URL from arguments const urlArg = program.args[0]; if (!urlArg) { console.error('Error: URL is required'); program.help(); process.exit(1); } async function main() { try { const WALLET = JSON.parse(fs.readFileSync(os.homedir() + '/.aos.json', 'utf-8')) if (options.verbose) { console.log('> Request details:'); console.log(`> URL: ${urlArg}`); console.log(`> Method: ${options.request}`); } // Parse URL const parsedUrl = new URL(urlArg); const { request } = connect({ MODE: 'mainnet', device: 'process@1.0', signer: createSigner(WALLET), URL: parsedUrl.origin }) // Prepare headers const headers = {}; if (options.header && options.header.length > 0) { for (const header of options.header) { const [key, value] = header.split(':').map(part => part.trim()); headers[key] = value; if (options.verbose) { console.log(`> Header: ${key}: ${value}`); } } } // Prepare data let data = null; if (options.file) { if (options.verbose) { console.log(`> Reading data from file: ${options.file}`); } data = fs.readFileSync(path.resolve(options.file), 'utf8'); } else if (options.data) { data = options.data; if (options.verbose) { console.log(`> Data: ${data}`); } } const params = { path: parsedUrl.pathname, method: options.request, ...headers } if (options.verbose) { console.log(`> Params: ${params}`); } // Make the request const response = await request(params); // Process response if (options.output) { if (options.verbose) { console.log(`> Writing response to file: ${options.output}`); } fs.writeFileSync(path.resolve(options.output), options.raw ? response : JSON.stringify(response, null, 2)); } else { if (options.raw) { console.log(response); } else { console.log(JSON.stringify(response.body, null, 2)); } } if (options.verbose) { console.log('> Request completed successfully'); } } catch (error) { console.error('Error:', error.message); process.exit(1); } } main();