@qodalis/cli-curl
Version:
Provide utility functions for the library curl
255 lines (244 loc) • 11.5 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('@qodalis/cli-core'), require('@angular/core')) :
typeof define === 'function' && define.amd ? define(['@qodalis/cli-core', '@angular/core'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.cliCore, global.ngCore));
})(this, (function (cliCore, core) { 'use strict';
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
// Automatically generated during build
const LIBRARY_VERSION = '0.0.2';
let CliCurlCommandProcessor = class CliCurlCommandProcessor {
constructor() {
this.command = 'curl';
this.description = 'A command-line tool to execute HTTP requests on your server. Supports GET, POST, PUT, DELETE, headers, and body data.';
this.author = cliCore.DefaultLibraryAuthor;
this.version = LIBRARY_VERSION;
this.processors = [];
this.metadata = {
icon: '🌐',
};
this.registerSubProcessors();
}
async processCommand(command, context) {
context.executor.showHelp(command, context);
}
async initialize(context) { }
registerSubProcessors() {
this.processors = [
{
command: 'get',
description: 'Perform an HTTP GET request',
valueRequired: true,
parameters: [
{
name: 'header',
aliases: ['H'],
type: 'array',
description: 'Add custom headers. Accept multiple headers.',
required: false,
},
{
name: 'proxy',
type: 'boolean',
description: 'Use procy',
required: false,
},
],
processCommand: async (command, context) => {
await this.executeRequest('GET', command, context);
},
},
{
command: 'post',
description: 'Perform an HTTP POST request',
valueRequired: true,
parameters: [
{
name: 'header',
aliases: ['H'],
type: 'array',
description: 'Add custom headers',
required: false,
},
{
name: 'data',
aliases: ['d'],
type: 'string',
description: 'Request body',
required: false,
},
{
name: 'proxy',
type: 'boolean',
description: 'Use procy',
required: false,
},
],
processCommand: async (command, context) => {
await this.executeRequest('POST', command, context);
},
},
{
command: 'put',
description: 'Perform an HTTP PUT request',
valueRequired: true,
parameters: [
{
name: 'header',
aliases: ['H'],
type: 'array',
description: 'Add custom headers',
required: false,
},
{
name: 'data',
aliases: ['d'],
type: 'string',
description: 'Request body',
required: false,
},
{
name: 'proxy',
type: 'boolean',
description: 'Use procy',
required: false,
},
],
processCommand: async (command, context) => {
await this.executeRequest('PUT', command, context);
},
},
{
command: 'delete',
description: 'Perform an HTTP DELETE request',
valueRequired: true,
parameters: [
{
name: 'header',
aliases: ['H'],
type: 'array',
description: 'Add custom headers',
required: false,
},
{
name: 'proxy',
type: 'boolean',
description: 'Use procy',
required: false,
},
],
processCommand: async (command, context) => {
await this.executeRequest('DELETE', command, context);
},
},
];
}
async executeRequest(method, command, context) {
const url = command.value;
const headers = command.args['header'] || command.args['H'] || [];
const data = command.args['data'] || command.args['d'];
const verbose = !!command.args['verbose'];
const useProxy = !!command.args['proxy'];
if (!url) {
context.writer.writeError('URL is required.');
return;
}
// Prepare headers
const headersObject = headers.reduce((acc, header) => {
const [key, value] = header.split(':').map((str) => str.trim());
if (key && value)
acc[key] = value;
return acc;
}, {});
// Prepare request options
const options = {
method,
headers: headersObject,
body: data ? JSON.stringify(JSON.parse(data)) : undefined,
};
try {
const requestUrl = useProxy ? this.rewriteUrlToProxy(url) : url;
const response = await fetch(requestUrl, options);
const text = await response.text();
context.writer.writeSuccess('Request successful:');
if (verbose) {
context.writer.writeln(`Status: ${response.status}`);
context.writer.writeln(`Headers: ${JSON.stringify(response.headers, null, 2)}`);
}
context.writer.writeln(text);
context.process.output(text);
}
catch (error) {
context.writer.writeError(`Request failed: ${error}`);
context.process.exit(-1);
}
finally {
context.writer.writeln();
context.writer.writeInfo('Equivalent curl command:');
context.writer.writeln(this.generateCurlCommand(url, method, headers, data));
}
}
generateCurlCommand(url, method, headers, data) {
const headerString = headers.map((h) => `-H "${h}"`).join(' ');
const dataString = data ? `-d '${data}'` : '';
return `curl -X ${method} ${headerString} ${dataString} "${url}"`;
}
rewriteUrlToProxy(originalUrl) {
const regex = /^(https?):\/\/([^\/]+)(\/.*)?$/i;
const match = originalUrl.match(regex);
if (!match) {
throw new Error('Invalid URL provided');
}
const scheme = match[1]; // 'http' or 'https'
const domain = match[2]; // domain.com
const path = match[3] || '/'; // /path or '/'
return `https://proxy.qodalis.com/proxy/${scheme}/${domain}${path}`;
}
writeDescription(context) {
context.writer.writeln(this.description);
context.writer.writeln();
context.writer.writeln('Usage:');
context.writer.writeln(' curl <method> <url> [options]');
context.writer.writeln();
context.writer.writeln('Options:');
context.writer.writeln(' -H, --header Add custom headers (e.g., -H="Authorization: Bearer <token>")');
context.writer.writeln(' -d, --data Add request body');
context.writer.writeln(' --verbose Print detailed response');
context.writer.writeln();
context.writer.writeln('Examples:');
context.writer.writeln(' curl get https://api.example.com/users');
context.writer.writeln(' curl post https://api.example.com/users -d=\'{"name":"John"}\' -H="Content-Type: application/json"');
context.writer.writeln();
context.writer.writeWarning('Note: The server must allow CORS for this tool to work.');
}
};
CliCurlCommandProcessor = __decorate([
core.Injectable()
], CliCurlCommandProcessor);
const module = {
name: '@qodalis/cli-curl',
processors: [new CliCurlCommandProcessor()],
};
cliCore.bootUmdModule(module);
}));