@scalar/snippetz 0.2.7 → 0.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/_virtual/client.js +133 -0
  2. package/dist/_virtual/client10.js +121 -0
  3. package/dist/_virtual/client11.js +128 -0
  4. package/dist/_virtual/client12.js +64 -0
  5. package/dist/_virtual/client13.js +128 -0
  6. package/dist/_virtual/client14.js +71 -0
  7. package/dist/_virtual/client15.js +81 -0
  8. package/dist/_virtual/client16.js +76 -0
  9. package/dist/_virtual/client17.js +81 -0
  10. package/dist/_virtual/client18.js +87 -0
  11. package/dist/_virtual/client19.js +45 -0
  12. package/dist/_virtual/client2.js +52 -0
  13. package/dist/_virtual/client20.js +44 -0
  14. package/dist/_virtual/client21.js +71 -0
  15. package/dist/_virtual/client22.js +45 -0
  16. package/dist/_virtual/client23.js +71 -0
  17. package/dist/_virtual/client24.js +122 -0
  18. package/dist/_virtual/client25.js +37 -0
  19. package/dist/_virtual/client26.js +154 -0
  20. package/dist/_virtual/client27.js +181 -0
  21. package/dist/_virtual/client28.js +43 -0
  22. package/dist/_virtual/client3.js +113 -0
  23. package/dist/_virtual/client4.js +70 -0
  24. package/dist/_virtual/client5.js +123 -0
  25. package/dist/_virtual/client6.js +166 -0
  26. package/dist/_virtual/client7.js +91 -0
  27. package/dist/_virtual/client8.js +13 -0
  28. package/dist/_virtual/client9.js +13 -0
  29. package/dist/core/utils/convertWithHttpSnippetLite.d.ts +1 -1
  30. package/dist/core/utils/convertWithHttpSnippetLite.d.ts.map +1 -1
  31. package/dist/httpsnippet-lite/dist/esm/helpers/code-builder.js +60 -0
  32. package/dist/httpsnippet-lite/dist/esm/helpers/escape.js +72 -0
  33. package/dist/httpsnippet-lite/dist/esm/helpers/headers.js +20 -0
  34. package/dist/httpsnippet-lite/dist/esm/helpers/shell.js +16 -0
  35. package/dist/httpsnippet-lite/dist/esm/targets/objc/helpers.js +56 -0
  36. package/dist/httpsnippet-lite/dist/esm/targets/php/helpers.js +35 -0
  37. package/dist/httpsnippet-lite/dist/esm/targets/powershell/common.js +51 -0
  38. package/dist/httpsnippet-lite/dist/esm/targets/python/helpers.js +61 -0
  39. package/dist/httpsnippet-lite/dist/esm/targets/swift/helpers.js +74 -0
  40. package/dist/plugins/c/libcurl/libcurl.js +1 -1
  41. package/dist/plugins/clojure/clj_http/clj_http.js +1 -1
  42. package/dist/plugins/csharp/httpclient/httpclient.js +1 -1
  43. package/dist/plugins/csharp/restsharp/restsharp.js +1 -1
  44. package/dist/plugins/go/native/native.js +1 -1
  45. package/dist/plugins/http/http11/http11.js +1 -1
  46. package/dist/plugins/java/asynchttp/asynchttp.js +1 -1
  47. package/dist/plugins/java/nethttp/nethttp.js +1 -1
  48. package/dist/plugins/java/okhttp/okhttp.js +1 -1
  49. package/dist/plugins/java/unirest/unirest.js +1 -1
  50. package/dist/plugins/js/axios/axios.js +1 -1
  51. package/dist/plugins/js/jquery/jquery.js +1 -1
  52. package/dist/plugins/js/xhr/xhr.js +1 -1
  53. package/dist/plugins/kotlin/okhttp/okhttp.js +1 -1
  54. package/dist/plugins/node/axios/axios.js +1 -1
  55. package/dist/plugins/objc/nsurlsession/nsurlsession.js +1 -1
  56. package/dist/plugins/ocaml/cohttp/cohttp.js +1 -1
  57. package/dist/plugins/php/curl/curl.js +1 -1
  58. package/dist/plugins/php/guzzle/guzzle.js +1 -1
  59. package/dist/plugins/powershell/restmethod/restmethod.js +1 -1
  60. package/dist/plugins/powershell/webrequest/webrequest.js +1 -1
  61. package/dist/plugins/python/python3/python3.js +1 -1
  62. package/dist/plugins/python/requests/requests.js +1 -1
  63. package/dist/plugins/r/httr/httr.js +1 -1
  64. package/dist/plugins/ruby/native/native.js +1 -1
  65. package/dist/plugins/shell/httpie/httpie.js +1 -1
  66. package/dist/plugins/shell/wget/wget.js +1 -1
  67. package/dist/plugins/swift/nsurlsession/nsurlsession.js +1 -1
  68. package/package.json +1 -2
@@ -0,0 +1,122 @@
1
+ import { CodeBuilder } from '../httpsnippet-lite/dist/esm/helpers/code-builder.js';
2
+ import { escapeForDoubleQuotes } from '../httpsnippet-lite/dist/esm/helpers/escape.js';
3
+
4
+ /**
5
+ * @description
6
+ * HTTP code snippet generator for native Go.
7
+ *
8
+ * @author
9
+ * @montanaflynn
10
+ *
11
+ * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author.
12
+ */
13
+ const native = {
14
+ info: {
15
+ key: 'native',
16
+ title: 'NewRequest',
17
+ link: 'http://golang.org/pkg/net/http/#NewRequest',
18
+ description: 'Golang HTTP client request',
19
+ },
20
+ convert: ({ postData, method, allHeaders, fullUrl }, options = {}) => {
21
+ const { blank, push, join } = new CodeBuilder({ indent: '\t' });
22
+ const { showBoilerplate = true, checkErrors = false, printBody = true, timeout = -1, insecureSkipVerify = false, } = options;
23
+ const errorPlaceholder = checkErrors ? 'err' : '_';
24
+ const indent = showBoilerplate ? 1 : 0;
25
+ const errorCheck = () => {
26
+ if (checkErrors) {
27
+ push('if err != nil {', indent);
28
+ push('panic(err)', indent + 1);
29
+ push('}', indent);
30
+ }
31
+ };
32
+ // Create boilerplate
33
+ if (showBoilerplate) {
34
+ push('package main');
35
+ blank();
36
+ push('import (');
37
+ push('"fmt"', indent);
38
+ if (timeout > 0) {
39
+ push('"time"', indent);
40
+ }
41
+ if (insecureSkipVerify) {
42
+ push('"crypto/tls"', indent);
43
+ }
44
+ if (postData === null || postData === void 0 ? void 0 : postData.text) {
45
+ push('"strings"', indent);
46
+ }
47
+ push('"net/http"', indent);
48
+ if (printBody) {
49
+ push('"io"', indent);
50
+ }
51
+ push(')');
52
+ blank();
53
+ push('func main() {');
54
+ blank();
55
+ }
56
+ // Create an insecure transport for the client
57
+ if (insecureSkipVerify) {
58
+ push('insecureTransport := http.DefaultTransport.(*http.Transport).Clone()', indent);
59
+ push('insecureTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}', indent);
60
+ }
61
+ // Create client
62
+ const hasTimeout = timeout > 0;
63
+ const hasClient = hasTimeout || insecureSkipVerify;
64
+ const client = hasClient ? 'client' : 'http.DefaultClient';
65
+ if (hasClient) {
66
+ push('client := http.Client{', indent);
67
+ if (hasTimeout) {
68
+ push(`Timeout: time.Duration(${timeout} * time.Second),`, indent + 1);
69
+ }
70
+ if (insecureSkipVerify) {
71
+ push('Transport: insecureTransport,', indent + 1);
72
+ }
73
+ push('}', indent);
74
+ blank();
75
+ }
76
+ push(`url := "${fullUrl}"`, indent);
77
+ blank();
78
+ // If we have body content or not create the var and reader or nil
79
+ if (postData === null || postData === void 0 ? void 0 : postData.text) {
80
+ push(`payload := strings.NewReader(${JSON.stringify(postData.text)})`, indent);
81
+ blank();
82
+ push(`req, ${errorPlaceholder} := http.NewRequest("${method}", url, payload)`, indent);
83
+ blank();
84
+ }
85
+ else {
86
+ push(`req, ${errorPlaceholder} := http.NewRequest("${method}", url, nil)`, indent);
87
+ blank();
88
+ }
89
+ errorCheck();
90
+ // Add headers
91
+ if (Object.keys(allHeaders).length) {
92
+ Object.keys(allHeaders).forEach(key => {
93
+ push(`req.Header.Add("${key}", "${escapeForDoubleQuotes(allHeaders[key])}")`, indent);
94
+ });
95
+ blank();
96
+ }
97
+ // Make request
98
+ push(`res, ${errorPlaceholder} := ${client}.Do(req)`, indent);
99
+ errorCheck();
100
+ // Get Body
101
+ if (printBody) {
102
+ blank();
103
+ push('defer res.Body.Close()', indent);
104
+ push(`body, ${errorPlaceholder} := io.ReadAll(res.Body)`, indent);
105
+ errorCheck();
106
+ }
107
+ // Print it
108
+ blank();
109
+ push('fmt.Println(res)', indent);
110
+ if (printBody) {
111
+ push('fmt.Println(string(body))', indent);
112
+ }
113
+ // End main block
114
+ if (showBoilerplate) {
115
+ blank();
116
+ push('}');
117
+ }
118
+ return join();
119
+ },
120
+ };
121
+
122
+ export { native };
@@ -0,0 +1,37 @@
1
+ import { CodeBuilder } from '../httpsnippet-lite/dist/esm/helpers/code-builder.js';
2
+ import { escapeForDoubleQuotes } from '../httpsnippet-lite/dist/esm/helpers/escape.js';
3
+ import { getHeader } from '../httpsnippet-lite/dist/esm/helpers/headers.js';
4
+
5
+ const restsharp = {
6
+ info: {
7
+ key: 'restsharp',
8
+ title: 'RestSharp',
9
+ link: 'http://restsharp.org/',
10
+ description: 'Simple REST and HTTP API Client for .NET',
11
+ },
12
+ convert: ({ allHeaders, method, fullUrl, headersObj, cookies, postData }) => {
13
+ const { push, join } = new CodeBuilder();
14
+ const isSupportedMethod = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'].includes(method.toUpperCase());
15
+ if (!isSupportedMethod) {
16
+ return 'Method not supported';
17
+ }
18
+ push(`var client = new RestClient("${fullUrl}");`);
19
+ push(`var request = new RestRequest(Method.${method.toUpperCase()});`);
20
+ // Add headers, including the cookies
21
+ Object.keys(headersObj).forEach(key => {
22
+ push(`request.AddHeader("${key}", "${escapeForDoubleQuotes(headersObj[key])}");`);
23
+ });
24
+ cookies === null || cookies === void 0 ? void 0 : cookies.forEach(({ name, value }) => {
25
+ push(`request.AddCookie("${name}", "${value}");`);
26
+ });
27
+ if (postData === null || postData === void 0 ? void 0 : postData.text) {
28
+ const header = getHeader(allHeaders, 'content-type');
29
+ const text = JSON.stringify(postData.text);
30
+ push(`request.AddParameter("${header}", ${text}, ParameterType.RequestBody);`);
31
+ }
32
+ push('IRestResponse response = client.Execute(request);');
33
+ return join();
34
+ },
35
+ };
36
+
37
+ export { restsharp };
@@ -0,0 +1,154 @@
1
+ import { CodeBuilder } from '../httpsnippet-lite/dist/esm/helpers/code-builder.js';
2
+ import { escapeForDoubleQuotes } from '../httpsnippet-lite/dist/esm/helpers/escape.js';
3
+ import { getHeader } from '../httpsnippet-lite/dist/esm/helpers/headers.js';
4
+
5
+ const getDecompressionMethods = (allHeaders) => {
6
+ let acceptEncodings = getHeader(allHeaders, 'accept-encoding');
7
+ if (!acceptEncodings) {
8
+ return []; // no decompression
9
+ }
10
+ const supportedMethods = {
11
+ gzip: 'DecompressionMethods.GZip',
12
+ deflate: 'DecompressionMethods.Deflate',
13
+ };
14
+ const methods = [];
15
+ if (typeof acceptEncodings === 'string') {
16
+ acceptEncodings = [acceptEncodings];
17
+ }
18
+ acceptEncodings.forEach(acceptEncoding => {
19
+ acceptEncoding.split(',').forEach(encoding => {
20
+ const match = /\s*([^;\s]+)/.exec(encoding);
21
+ if (match) {
22
+ const method = supportedMethods[match[1]];
23
+ if (method) {
24
+ methods.push(method);
25
+ }
26
+ }
27
+ });
28
+ });
29
+ return methods;
30
+ };
31
+ const httpclient = {
32
+ info: {
33
+ key: 'httpclient',
34
+ title: 'HttpClient',
35
+ link: 'https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient',
36
+ description: '.NET Standard HTTP Client',
37
+ },
38
+ convert: ({ allHeaders, postData, method, fullUrl }, options) => {
39
+ var _a, _b;
40
+ const opts = {
41
+ indent: ' ',
42
+ ...options,
43
+ };
44
+ const { push, join } = new CodeBuilder({ indent: opts.indent });
45
+ push('using System.Net.Http.Headers;');
46
+ let clienthandler = '';
47
+ const cookies = Boolean(allHeaders.cookie);
48
+ const decompressionMethods = getDecompressionMethods(allHeaders);
49
+ if (cookies || decompressionMethods.length) {
50
+ clienthandler = 'clientHandler';
51
+ push('var clientHandler = new HttpClientHandler');
52
+ push('{');
53
+ if (cookies) {
54
+ // enable setting the cookie header
55
+ push('UseCookies = false,', 1);
56
+ }
57
+ if (decompressionMethods.length) {
58
+ // enable decompression for supported methods
59
+ push(`AutomaticDecompression = ${decompressionMethods.join(' | ')},`, 1);
60
+ }
61
+ push('};');
62
+ }
63
+ push(`var client = new HttpClient(${clienthandler});`);
64
+ push('var request = new HttpRequestMessage');
65
+ push('{');
66
+ const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS', 'TRACE'];
67
+ method = method.toUpperCase();
68
+ if (method && methods.includes(method)) {
69
+ // buildin method
70
+ method = `HttpMethod.${method[0]}${method.substring(1).toLowerCase()}`;
71
+ }
72
+ else {
73
+ // custom method
74
+ method = `new HttpMethod("${method}")`;
75
+ }
76
+ push(`Method = ${method},`, 1);
77
+ push(`RequestUri = new Uri("${fullUrl}"),`, 1);
78
+ const headers = Object.keys(allHeaders).filter(header => {
79
+ switch (header.toLowerCase()) {
80
+ case 'content-type':
81
+ case 'content-length':
82
+ case 'accept-encoding':
83
+ // skip these headers
84
+ return false;
85
+ default:
86
+ return true;
87
+ }
88
+ });
89
+ if (headers.length) {
90
+ push('Headers =', 1);
91
+ push('{', 1);
92
+ headers.forEach(key => {
93
+ push(`{ "${key}", "${escapeForDoubleQuotes(allHeaders[key])}" },`, 2);
94
+ });
95
+ push('},', 1);
96
+ }
97
+ if (postData === null || postData === void 0 ? void 0 : postData.text) {
98
+ const contentType = postData.mimeType;
99
+ switch (contentType) {
100
+ case 'application/x-www-form-urlencoded':
101
+ push('Content = new FormUrlEncodedContent(new Dictionary<string, string>', 1);
102
+ push('{', 1);
103
+ (_a = postData.params) === null || _a === void 0 ? void 0 : _a.forEach(param => {
104
+ push(`{ "${param.name}", "${param.value}" },`, 2);
105
+ });
106
+ push('}),', 1);
107
+ break;
108
+ case 'multipart/form-data':
109
+ push('Content = new MultipartFormDataContent', 1);
110
+ push('{', 1);
111
+ (_b = postData.params) === null || _b === void 0 ? void 0 : _b.forEach(param => {
112
+ push(`new StringContent(${JSON.stringify(param.value || '')})`, 2);
113
+ push('{', 2);
114
+ push('Headers =', 3);
115
+ push('{', 3);
116
+ if (param.contentType) {
117
+ push(`ContentType = new MediaTypeHeaderValue("${param.contentType}"),`, 4);
118
+ }
119
+ push('ContentDisposition = new ContentDispositionHeaderValue("form-data")', 4);
120
+ push('{', 4);
121
+ push(`Name = "${param.name}",`, 5);
122
+ if (param.fileName) {
123
+ push(`FileName = "${param.fileName}",`, 5);
124
+ }
125
+ push('}', 4);
126
+ push('}', 3);
127
+ push('},', 2);
128
+ });
129
+ push('},', 1);
130
+ break;
131
+ default:
132
+ push(`Content = new StringContent(${JSON.stringify((postData === null || postData === void 0 ? void 0 : postData.text) || '')})`, 1);
133
+ push('{', 1);
134
+ push('Headers =', 2);
135
+ push('{', 2);
136
+ push(`ContentType = new MediaTypeHeaderValue("${contentType}")`, 3);
137
+ push('}', 2);
138
+ push('}', 1);
139
+ break;
140
+ }
141
+ }
142
+ push('};');
143
+ // send and read response
144
+ push('using (var response = await client.SendAsync(request))');
145
+ push('{');
146
+ push('response.EnsureSuccessStatusCode();', 1);
147
+ push('var body = await response.Content.ReadAsStringAsync();', 1);
148
+ push('Console.WriteLine(body);', 1);
149
+ push('}');
150
+ return join();
151
+ },
152
+ };
153
+
154
+ export { httpclient };
@@ -0,0 +1,181 @@
1
+ import { CodeBuilder } from '../httpsnippet-lite/dist/esm/helpers/code-builder.js';
2
+ import { getHeaderName, getHeader } from '../httpsnippet-lite/dist/esm/helpers/headers.js';
3
+
4
+ /**
5
+ * @description
6
+ * HTTP code snippet generator for Clojure using clj-http.
7
+ *
8
+ * @author
9
+ * @tggreene
10
+ *
11
+ * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author.
12
+ */
13
+ class Keyword {
14
+ constructor(name) {
15
+ this.name = '';
16
+ this.toString = () => `:${this.name}`;
17
+ this.name = name;
18
+ }
19
+ }
20
+ class File {
21
+ constructor(path) {
22
+ this.path = '';
23
+ this.toString = () => `(clojure.java.io/file "${this.path}")`;
24
+ this.path = path;
25
+ }
26
+ }
27
+ const jsType = (input) => {
28
+ if (input === undefined) {
29
+ return null;
30
+ }
31
+ if (input === null) {
32
+ return 'null';
33
+ }
34
+ return input.constructor.name.toLowerCase();
35
+ };
36
+ const objEmpty = (input) => {
37
+ if (jsType(input) === 'object') {
38
+ return Object.keys(input).length === 0;
39
+ }
40
+ return false;
41
+ };
42
+ const filterEmpty = (input) => {
43
+ Object.keys(input)
44
+ .filter(x => objEmpty(input[x]))
45
+ .forEach(x => {
46
+ delete input[x];
47
+ });
48
+ return input;
49
+ };
50
+ const padBlock = (padSize, input) => {
51
+ const padding = ' '.repeat(padSize);
52
+ return input.replace(/\n/g, `\n${padding}`);
53
+ };
54
+ const jsToEdn = (js) => {
55
+ switch (jsType(js)) {
56
+ case 'string':
57
+ return `"${js.replace(/"/g, '\\"')}"`;
58
+ case 'file':
59
+ return js.toString();
60
+ case 'keyword':
61
+ return js.toString();
62
+ case 'null':
63
+ return 'nil';
64
+ case 'regexp':
65
+ return `#"${js.source}"`;
66
+ case 'object': {
67
+ // simple vertical format
68
+ const obj = Object.keys(js)
69
+ .reduce((accumulator, key) => {
70
+ const val = padBlock(key.length + 2, jsToEdn(js[key]));
71
+ return `${accumulator}:${key} ${val}\n `;
72
+ }, '')
73
+ .trim();
74
+ return `{${padBlock(1, obj)}}`;
75
+ }
76
+ case 'array': {
77
+ // simple horizontal format
78
+ const arr = js
79
+ .reduce((accumulator, value) => `${accumulator} ${jsToEdn(value)}`, '')
80
+ .trim();
81
+ return `[${padBlock(1, arr)}]`;
82
+ }
83
+ default: // 'number' 'boolean'
84
+ return js.toString();
85
+ }
86
+ };
87
+ const clj_http = {
88
+ info: {
89
+ key: 'clj_http',
90
+ title: 'clj-http',
91
+ link: 'https://github.com/dakrone/clj-http',
92
+ description: 'An idiomatic clojure http client wrapping the apache client.',
93
+ },
94
+ convert: ({ queryObj, method, postData, url, allHeaders }, options) => {
95
+ const { push, join } = new CodeBuilder({ indent: options === null || options === void 0 ? void 0 : options.indent });
96
+ const methods = ['get', 'post', 'put', 'delete', 'patch', 'head', 'options'];
97
+ method = method.toLowerCase();
98
+ if (!methods.includes(method)) {
99
+ push('Method not supported');
100
+ return join();
101
+ }
102
+ const params = {
103
+ headers: allHeaders,
104
+ 'query-params': queryObj,
105
+ };
106
+ switch (postData === null || postData === void 0 ? void 0 : postData.mimeType) {
107
+ case 'application/json':
108
+ {
109
+ params['content-type'] = new Keyword('json');
110
+ params['form-params'] = postData.jsonObj;
111
+ const header = getHeaderName(params.headers, 'content-type');
112
+ if (header) {
113
+ delete params.headers[header];
114
+ }
115
+ }
116
+ break;
117
+ case 'application/x-www-form-urlencoded':
118
+ {
119
+ params['form-params'] = postData.paramsObj;
120
+ const header = getHeaderName(params.headers, 'content-type');
121
+ if (header) {
122
+ delete params.headers[header];
123
+ }
124
+ }
125
+ break;
126
+ case 'text/plain':
127
+ {
128
+ params.body = postData.text;
129
+ const header = getHeaderName(params.headers, 'content-type');
130
+ if (header) {
131
+ delete params.headers[header];
132
+ }
133
+ }
134
+ break;
135
+ case 'multipart/form-data': {
136
+ if (postData.params) {
137
+ params.multipart = postData.params.map(param => {
138
+ if (param.fileName && !param.value) {
139
+ return {
140
+ name: param.name,
141
+ content: new File(param.fileName),
142
+ };
143
+ }
144
+ return {
145
+ name: param.name,
146
+ content: param.value,
147
+ };
148
+ });
149
+ const header = getHeaderName(params.headers, 'content-type');
150
+ if (header) {
151
+ delete params.headers[header];
152
+ }
153
+ }
154
+ break;
155
+ }
156
+ }
157
+ switch (getHeader(params.headers, 'accept')) {
158
+ case 'application/json':
159
+ {
160
+ params.accept = new Keyword('json');
161
+ const header = getHeaderName(params.headers, 'accept');
162
+ if (header) {
163
+ delete params.headers[header];
164
+ }
165
+ }
166
+ break;
167
+ }
168
+ push("(require '[clj-http.client :as client])\n");
169
+ if (objEmpty(filterEmpty(params))) {
170
+ push(`(client/${method} "${url}")`);
171
+ }
172
+ else {
173
+ const padding = 11 + method.length + url.length;
174
+ const formattedParams = padBlock(padding, jsToEdn(filterEmpty(params)));
175
+ push(`(client/${method} "${url}" ${formattedParams})`);
176
+ }
177
+ return join();
178
+ },
179
+ };
180
+
181
+ export { clj_http };
@@ -0,0 +1,43 @@
1
+ import { CodeBuilder } from '../httpsnippet-lite/dist/esm/helpers/code-builder.js';
2
+ import { escapeForDoubleQuotes } from '../httpsnippet-lite/dist/esm/helpers/escape.js';
3
+
4
+ const libcurl = {
5
+ info: {
6
+ key: 'libcurl',
7
+ title: 'Libcurl',
8
+ link: 'http://curl.haxx.se/libcurl',
9
+ description: 'Simple REST and HTTP API Client for C',
10
+ },
11
+ convert: ({ method, fullUrl, headersObj, allHeaders, postData }) => {
12
+ const { push, blank, join } = new CodeBuilder();
13
+ push('CURL *hnd = curl_easy_init();');
14
+ blank();
15
+ push(`curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "${method.toUpperCase()}");`);
16
+ push(`curl_easy_setopt(hnd, CURLOPT_URL, "${fullUrl}");`);
17
+ // Add headers, including the cookies
18
+ const headers = Object.keys(headersObj);
19
+ // construct headers
20
+ if (headers.length) {
21
+ blank();
22
+ push('struct curl_slist *headers = NULL;');
23
+ headers.forEach(header => {
24
+ push(`headers = curl_slist_append(headers, "${header}: ${escapeForDoubleQuotes(headersObj[header])}");`);
25
+ });
26
+ push('curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);');
27
+ }
28
+ // construct cookies
29
+ if (allHeaders.cookie) {
30
+ blank();
31
+ push(`curl_easy_setopt(hnd, CURLOPT_COOKIE, "${allHeaders.cookie}");`);
32
+ }
33
+ if (postData === null || postData === void 0 ? void 0 : postData.text) {
34
+ blank();
35
+ push(`curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, ${JSON.stringify(postData.text)});`);
36
+ }
37
+ blank();
38
+ push('CURLcode ret = curl_easy_perform(hnd);');
39
+ return join();
40
+ },
41
+ };
42
+
43
+ export { libcurl };
@@ -0,0 +1,113 @@
1
+ import { CodeBuilder } from '../httpsnippet-lite/dist/esm/helpers/code-builder.js';
2
+ import { quote } from '../httpsnippet-lite/dist/esm/helpers/shell.js';
3
+
4
+ /**
5
+ * @description
6
+ * HTTP code snippet generator for the Shell using HTTPie.
7
+ *
8
+ * @author
9
+ * @AhmadNassri
10
+ *
11
+ * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author.
12
+ */
13
+ const httpie = {
14
+ info: {
15
+ key: 'httpie',
16
+ title: 'HTTPie',
17
+ link: 'http://httpie.org/',
18
+ description: 'a CLI, cURL-like tool for humans',
19
+ },
20
+ convert: ({ allHeaders, postData, queryObj, fullUrl, method, url }, options) => {
21
+ const opts = {
22
+ body: false,
23
+ cert: false,
24
+ headers: false,
25
+ indent: ' ',
26
+ pretty: false,
27
+ print: false,
28
+ queryParams: false,
29
+ short: false,
30
+ style: false,
31
+ timeout: false,
32
+ verbose: false,
33
+ verify: false,
34
+ ...options,
35
+ };
36
+ const { push, join, unshift } = new CodeBuilder({
37
+ indent: opts.indent,
38
+ // @ts-expect-error SEEMS LEGIT
39
+ join: opts.indent !== false ? ` \\\n${opts.indent}` : ' ',
40
+ });
41
+ let raw = false;
42
+ const flags = [];
43
+ if (opts.headers) {
44
+ flags.push(opts.short ? '-h' : '--headers');
45
+ }
46
+ if (opts.body) {
47
+ flags.push(opts.short ? '-b' : '--body');
48
+ }
49
+ if (opts.verbose) {
50
+ flags.push(opts.short ? '-v' : '--verbose');
51
+ }
52
+ if (opts.print) {
53
+ flags.push(`${opts.short ? '-p' : '--print'}=${opts.print}`);
54
+ }
55
+ if (opts.verify) {
56
+ flags.push(`--verify=${opts.verify}`);
57
+ }
58
+ if (opts.cert) {
59
+ flags.push(`--cert=${opts.cert}`);
60
+ }
61
+ if (opts.pretty) {
62
+ flags.push(`--pretty=${opts.pretty}`);
63
+ }
64
+ if (opts.style) {
65
+ flags.push(`--style=${opts.style}`);
66
+ }
67
+ if (opts.timeout) {
68
+ flags.push(`--timeout=${opts.timeout}`);
69
+ }
70
+ // construct query params
71
+ if (opts.queryParams) {
72
+ Object.keys(queryObj).forEach(name => {
73
+ const value = queryObj[name];
74
+ if (Array.isArray(value)) {
75
+ value.forEach(val => {
76
+ push(`${name}==${quote(val)}`);
77
+ });
78
+ }
79
+ else {
80
+ push(`${name}==${quote(value)}`);
81
+ }
82
+ });
83
+ }
84
+ // construct headers
85
+ Object.keys(allHeaders)
86
+ .sort()
87
+ .forEach(key => {
88
+ push(`${key}:${quote(allHeaders[key])}`);
89
+ });
90
+ if ((postData === null || postData === void 0 ? void 0 : postData.mimeType) === 'application/x-www-form-urlencoded') {
91
+ // construct post params
92
+ if (postData.params && postData.params.length) {
93
+ flags.push(opts.short ? '-f' : '--form');
94
+ postData.params.forEach(param => {
95
+ push(`${param.name}=${quote(param.value)}`);
96
+ });
97
+ }
98
+ }
99
+ else {
100
+ raw = true;
101
+ }
102
+ const cliFlags = flags.length ? `${flags.join(' ')} ` : '';
103
+ url = quote(opts.queryParams ? url : fullUrl);
104
+ unshift(`http ${cliFlags}${method} ${url}`);
105
+ if (raw && (postData === null || postData === void 0 ? void 0 : postData.text)) {
106
+ const postDataText = quote(postData.text);
107
+ unshift(`echo ${postDataText} | `);
108
+ }
109
+ return join();
110
+ },
111
+ };
112
+
113
+ export { httpie };