@readme/httpsnippet 7.1.1 → 8.0.0

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 (42) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +24 -25
  3. package/dist/{chunk-DTZD7L6R.mjs → chunk-IAWYVBVW.js} +78 -61
  4. package/dist/chunk-IAWYVBVW.js.map +1 -0
  5. package/dist/{chunk-BCCGHMCJ.mjs → chunk-KT7MO6Z4.js} +1 -1
  6. package/dist/{chunk-UEOS42PC.mjs → chunk-Y7NI4MMY.js} +1 -1
  7. package/dist/helpers/code-builder.cjs +65 -0
  8. package/dist/helpers/code-builder.cjs.map +1 -0
  9. package/dist/helpers/code-builder.js +1 -63
  10. package/dist/helpers/code-builder.js.map +1 -1
  11. package/dist/helpers/reducer.cjs +20 -0
  12. package/dist/helpers/reducer.cjs.map +1 -0
  13. package/dist/helpers/reducer.js +1 -18
  14. package/dist/helpers/reducer.js.map +1 -1
  15. package/dist/{index-c415b193.d.ts → index-babe3117.d.ts} +10 -6
  16. package/dist/{index-ae5e535e.d.ts → index-c8003aae.d.ts} +11 -7
  17. package/dist/index.cjs +3745 -0
  18. package/dist/index.cjs.map +1 -0
  19. package/dist/{index.d.mts → index.d.cts} +3 -3
  20. package/dist/index.d.ts +1 -1
  21. package/dist/index.js +179 -3767
  22. package/dist/index.js.map +1 -1
  23. package/dist/targets/index.cjs +3512 -0
  24. package/dist/targets/index.cjs.map +1 -0
  25. package/dist/targets/{index.d.mts → index.d.cts} +3 -3
  26. package/dist/targets/index.d.ts +1 -1
  27. package/dist/targets/index.js +2 -3493
  28. package/dist/targets/index.js.map +1 -1
  29. package/package.json +36 -41
  30. package/dist/chunk-DTZD7L6R.mjs.map +0 -1
  31. package/dist/helpers/code-builder.mjs +0 -3
  32. package/dist/helpers/code-builder.mjs.map +0 -1
  33. package/dist/helpers/reducer.mjs +0 -3
  34. package/dist/helpers/reducer.mjs.map +0 -1
  35. package/dist/index.mjs +0 -287
  36. package/dist/index.mjs.map +0 -1
  37. package/dist/targets/index.mjs +0 -4
  38. package/dist/targets/index.mjs.map +0 -1
  39. /package/dist/{chunk-BCCGHMCJ.mjs.map → chunk-KT7MO6Z4.js.map} +0 -0
  40. /package/dist/{chunk-UEOS42PC.mjs.map → chunk-Y7NI4MMY.js.map} +0 -0
  41. /package/dist/helpers/{code-builder.d.mts → code-builder.d.cts} +0 -0
  42. /package/dist/helpers/{reducer.d.mts → reducer.d.cts} +0 -0
package/dist/index.js CHANGED
@@ -1,3560 +1,10 @@
1
- 'use strict';
2
-
3
- var url = require('url');
4
- var eventStream = require('event-stream');
5
- var FormData = require('form-data');
6
- var qs = require('qs');
7
- var stringifyObject9 = require('stringify-object');
8
-
9
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
-
11
- function _interopNamespace(e) {
12
- if (e && e.__esModule) return e;
13
- var n = Object.create(null);
14
- if (e) {
15
- Object.keys(e).forEach(function (k) {
16
- if (k !== 'default') {
17
- var d = Object.getOwnPropertyDescriptor(e, k);
18
- Object.defineProperty(n, k, d.get ? d : {
19
- enumerable: true,
20
- get: function () { return e[k]; }
21
- });
22
- }
23
- });
24
- }
25
- n.default = e;
26
- return Object.freeze(n);
27
- }
28
-
29
- var eventStream__namespace = /*#__PURE__*/_interopNamespace(eventStream);
30
- var FormData__default = /*#__PURE__*/_interopDefault(FormData);
31
- var stringifyObject9__default = /*#__PURE__*/_interopDefault(stringifyObject9);
32
-
33
- // src/index.ts
34
-
35
- // src/helpers/form-data.ts
36
- var carriage = "\r\n";
37
- var dashes = "-".repeat(2);
38
- var NAME = Symbol.toStringTag;
39
- var isBlob = (object) => typeof object === "object" && typeof object.arrayBuffer === "function" && typeof object.type === "string" && typeof object.stream === "function" && typeof object.constructor === "function" && /^(Blob|File)$/.test(object[NAME]);
40
- var getFooter = (boundary) => `${dashes}${boundary}${dashes}${carriage.repeat(2)}`;
41
- var getHeader = (boundary, name, field) => {
42
- let header = "";
43
- header += `${dashes}${boundary}${carriage}`;
44
- header += `Content-Disposition: form-data; name="${name}"`;
45
- if (isBlob(field)) {
46
- header += `; filename="${field.name}"${carriage}`;
47
- header += `Content-Type: ${field.type || "application/octet-stream"}`;
48
- }
49
- return `${header}${carriage.repeat(2)}`;
50
- };
51
- var formDataIterator = function* (form, boundary) {
52
- for (const [name, value] of form) {
53
- yield getHeader(boundary, name, value);
54
- if (isBlob(value)) {
55
- yield* value.stream();
56
- } else {
57
- yield value;
58
- }
59
- yield carriage;
60
- }
61
- yield getFooter(boundary);
62
- };
63
-
64
- // src/helpers/headers.ts
65
- var getHeaderName = (headers, name) => Object.keys(headers).find((header) => header.toLowerCase() === name.toLowerCase());
66
- var getHeader2 = (headers, name) => {
67
- const headerName = getHeaderName(headers, name);
68
- if (!headerName) {
69
- return void 0;
70
- }
71
- return headers[headerName];
72
- };
73
- var hasHeader = (headers, name) => Boolean(getHeaderName(headers, name));
74
- var isMimeTypeJSON = (mimeType) => ["application/json", "application/x-json", "text/json", "text/x-json", "+json"].some(
75
- (type) => mimeType.indexOf(type) > -1
76
- );
77
-
78
- // src/helpers/reducer.ts
79
- var reducer = (accumulator, pair) => {
80
- const currentValue = accumulator[pair.name];
81
- if (currentValue === void 0) {
82
- accumulator[pair.name] = pair.value;
83
- return accumulator;
84
- }
85
- if (Array.isArray(currentValue)) {
86
- currentValue.push(pair.value);
87
- return accumulator;
88
- }
89
- accumulator[pair.name] = [currentValue, pair.value];
90
- return accumulator;
91
- };
92
-
93
- // src/helpers/code-builder.ts
94
- var DEFAULT_INDENTATION_CHARACTER = "";
95
- var DEFAULT_LINE_JOIN = "\n";
96
- var CodeBuilder = class {
97
- /**
98
- * Helper object to format and aggragate lines of code.
99
- * Lines are aggregated in a `code` array, and need to be joined to obtain a proper code snippet.
100
- */
101
- constructor({ indent, join } = {}) {
102
- this.postProcessors = [];
103
- this.code = [];
104
- this.indentationCharacter = DEFAULT_INDENTATION_CHARACTER;
105
- this.lineJoin = DEFAULT_LINE_JOIN;
106
- /**
107
- * Add given indentation level to given line of code
108
- */
109
- this.indentLine = (line, indentationLevel = 0) => {
110
- const indent = this.indentationCharacter.repeat(indentationLevel);
111
- return `${indent}${line}`;
112
- };
113
- /**
114
- * Add the line at the beginning of the current lines
115
- */
116
- this.unshift = (line, indentationLevel) => {
117
- const newLine = this.indentLine(line, indentationLevel);
118
- this.code.unshift(newLine);
119
- };
120
- /**
121
- * Add the line at the end of the current lines
122
- */
123
- this.push = (line, indentationLevel) => {
124
- const newLine = this.indentLine(line, indentationLevel);
125
- this.code.push(newLine);
126
- };
127
- /**
128
- * Add an empty line at the end of current lines
129
- */
130
- this.blank = () => {
131
- this.code.push("");
132
- };
133
- /**
134
- * Concatenate all current lines using the given lineJoin, then apply any replacers that may have been added
135
- */
136
- this.join = () => {
137
- const unreplacedCode = this.code.join(this.lineJoin);
138
- const replacedOutput = this.postProcessors.reduce((accumulator, replacer) => replacer(accumulator), unreplacedCode);
139
- return replacedOutput;
140
- };
141
- /**
142
- * Often when writing modules you may wish to add a literal tag or bit of metadata that you wish to transform after other processing as a final step.
143
- * To do so, you can provide a PostProcessor function and it will be run automatically for you when you call `join()` later on.
144
- */
145
- this.addPostProcessor = (postProcessor) => {
146
- this.postProcessors = [...this.postProcessors, postProcessor];
147
- };
148
- this.indentationCharacter = indent || DEFAULT_INDENTATION_CHARACTER;
149
- this.lineJoin = join ?? DEFAULT_LINE_JOIN;
150
- }
151
- };
152
-
153
- // src/helpers/escape.ts
154
- function escapeString(rawValue, options = {}) {
155
- const { delimiter = '"', escapeChar = "\\", escapeNewlines = true } = options;
156
- const stringValue = rawValue.toString();
157
- return [...stringValue].map((c2) => {
158
- if (c2 === "\b") {
159
- return `${escapeChar}b`;
160
- } else if (c2 === " ") {
161
- return `${escapeChar}t`;
162
- } else if (c2 === "\n") {
163
- if (escapeNewlines) {
164
- return `${escapeChar}n`;
165
- }
166
- return c2;
167
- } else if (c2 === "\f") {
168
- return `${escapeChar}f`;
169
- } else if (c2 === "\r") {
170
- if (escapeNewlines) {
171
- return `${escapeChar}r`;
172
- }
173
- return c2;
174
- } else if (c2 === escapeChar) {
175
- return escapeChar + escapeChar;
176
- } else if (c2 === delimiter) {
177
- return escapeChar + delimiter;
178
- } else if (c2 < " " || c2 > "~") {
179
- return JSON.stringify(c2).slice(1, -1);
180
- }
181
- return c2;
182
- }).join("");
183
- }
184
- var escapeForSingleQuotes = (value) => escapeString(value, { delimiter: "'" });
185
- var escapeForDoubleQuotes = (value) => escapeString(value, { delimiter: '"' });
186
-
187
- // src/targets/c/libcurl/client.ts
188
- var libcurl = {
189
- info: {
190
- key: "libcurl",
191
- title: "Libcurl",
192
- link: "http://curl.haxx.se/libcurl",
193
- description: "Simple REST and HTTP API Client for C"
194
- },
195
- convert: ({ method, fullUrl, headersObj, allHeaders, postData }) => {
196
- const { push, blank, join } = new CodeBuilder();
197
- push("CURL *hnd = curl_easy_init();");
198
- blank();
199
- push(`curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "${method.toUpperCase()}");`);
200
- push("curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout);");
201
- push(`curl_easy_setopt(hnd, CURLOPT_URL, "${fullUrl}");`);
202
- const headers = Object.keys(headersObj);
203
- if (headers.length) {
204
- blank();
205
- push("struct curl_slist *headers = NULL;");
206
- headers.forEach((header) => {
207
- push(`headers = curl_slist_append(headers, "${header}: ${escapeForDoubleQuotes(headersObj[header])}");`);
208
- });
209
- push("curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);");
210
- }
211
- if (allHeaders.cookie) {
212
- blank();
213
- push(`curl_easy_setopt(hnd, CURLOPT_COOKIE, "${allHeaders.cookie}");`);
214
- }
215
- if (postData.text) {
216
- blank();
217
- push(`curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, ${JSON.stringify(postData.text)});`);
218
- }
219
- blank();
220
- push("CURLcode ret = curl_easy_perform(hnd);");
221
- return join();
222
- }
223
- };
224
-
225
- // src/targets/c/target.ts
226
- var c = {
227
- info: {
228
- key: "c",
229
- title: "C",
230
- extname: ".c",
231
- default: "libcurl",
232
- cli: "c"
233
- },
234
- clientsById: {
235
- libcurl
236
- }
237
- };
238
-
239
- // src/targets/clojure/clj_http/client.ts
240
- var Keyword = class {
241
- constructor(name) {
242
- this.name = "";
243
- this.toString = () => `:${this.name}`;
244
- this.name = name;
245
- }
246
- };
247
- var File = class {
248
- constructor(path) {
249
- this.path = "";
250
- this.toString = () => `(clojure.java.io/file "${this.path}")`;
251
- this.path = path;
252
- }
253
- };
254
- var jsType = (input) => {
255
- if (input === void 0) {
256
- return null;
257
- }
258
- if (input === null) {
259
- return "null";
260
- }
261
- return input.constructor.name.toLowerCase();
262
- };
263
- var objEmpty = (input) => {
264
- if (input === void 0) {
265
- return true;
266
- } else if (jsType(input) === "object") {
267
- return Object.keys(input).length === 0;
268
- }
269
- return false;
270
- };
271
- var filterEmpty = (input) => {
272
- Object.keys(input).filter((x) => objEmpty(input[x])).forEach((x) => {
273
- delete input[x];
274
- });
275
- return input;
276
- };
277
- var padBlock = (padSize, input) => {
278
- const padding = " ".repeat(padSize);
279
- return input.replace(/\n/g, `
280
- ${padding}`);
281
- };
282
- var jsToEdn = (js) => {
283
- switch (jsType(js)) {
284
- case "string":
285
- return `"${js.replace(/"/g, '\\"')}"`;
286
- case "file":
287
- return js.toString();
288
- case "keyword":
289
- return js.toString();
290
- case "null":
291
- return "nil";
292
- case "regexp":
293
- return `#"${js.source}"`;
294
- case "object": {
295
- const obj = Object.keys(js).reduce((accumulator, key) => {
296
- const val = padBlock(key.length + 2, jsToEdn(js[key]));
297
- return `${accumulator}:${key} ${val}
298
- `;
299
- }, "").trim();
300
- return `{${padBlock(1, obj)}}`;
301
- }
302
- case "array": {
303
- const arr = js.reduce((accumulator, value) => `${accumulator} ${jsToEdn(value)}`, "").trim();
304
- return `[${padBlock(1, arr)}]`;
305
- }
306
- default:
307
- return js.toString();
308
- }
309
- };
310
- var clj_http = {
311
- info: {
312
- key: "clj_http",
313
- title: "clj-http",
314
- link: "https://github.com/dakrone/clj-http",
315
- description: "An idiomatic clojure http client wrapping the apache client."
316
- },
317
- convert: ({ queryObj, method, postData, url, allHeaders }, options) => {
318
- const { push, join } = new CodeBuilder({ indent: options?.indent });
319
- const methods = ["get", "post", "put", "delete", "patch", "head", "options"];
320
- method = method.toLowerCase();
321
- if (!methods.includes(method)) {
322
- push("Method not supported");
323
- return join();
324
- }
325
- const params2 = {
326
- headers: allHeaders,
327
- "query-params": queryObj
328
- };
329
- switch (postData.mimeType) {
330
- case "application/json":
331
- {
332
- params2["content-type"] = new Keyword("json");
333
- params2["form-params"] = postData.jsonObj;
334
- const header = getHeaderName(params2.headers, "content-type");
335
- if (header) {
336
- delete params2.headers[header];
337
- }
338
- }
339
- break;
340
- case "application/x-www-form-urlencoded":
341
- {
342
- params2["form-params"] = postData.paramsObj;
343
- const header = getHeaderName(params2.headers, "content-type");
344
- if (header) {
345
- delete params2.headers[header];
346
- }
347
- }
348
- break;
349
- case "text/plain":
350
- {
351
- params2.body = postData.text;
352
- const header = getHeaderName(params2.headers, "content-type");
353
- if (header) {
354
- delete params2.headers[header];
355
- }
356
- }
357
- break;
358
- case "multipart/form-data": {
359
- if (postData.params) {
360
- params2.multipart = postData.params.map((param) => {
361
- if (param.fileName && !param.value) {
362
- return {
363
- name: param.name,
364
- content: new File(param.fileName)
365
- };
366
- }
367
- return {
368
- name: param.name,
369
- content: param.value
370
- };
371
- });
372
- const header = getHeaderName(params2.headers, "content-type");
373
- if (header) {
374
- delete params2.headers[header];
375
- }
376
- }
377
- break;
378
- }
379
- }
380
- switch (getHeader2(params2.headers, "accept")) {
381
- case "application/json":
382
- {
383
- params2.accept = new Keyword("json");
384
- const header = getHeaderName(params2.headers, "accept");
385
- if (header) {
386
- delete params2.headers[header];
387
- }
388
- }
389
- break;
390
- }
391
- push("(require '[clj-http.client :as client])\n");
392
- if (objEmpty(filterEmpty(params2))) {
393
- push(`(client/${method} "${url}")`);
394
- } else {
395
- const padding = 11 + method.length + url.length;
396
- const formattedParams = padBlock(padding, jsToEdn(filterEmpty(params2)));
397
- push(`(client/${method} "${url}" ${formattedParams})`);
398
- }
399
- return join();
400
- }
401
- };
402
-
403
- // src/targets/clojure/target.ts
404
- var clojure = {
405
- info: {
406
- key: "clojure",
407
- title: "Clojure",
408
- extname: ".clj",
409
- default: "clj_http"
410
- },
411
- clientsById: {
412
- clj_http
413
- }
414
- };
415
-
416
- // src/targets/csharp/httpclient/client.ts
417
- var getDecompressionMethods = (allHeaders) => {
418
- let acceptEncodings = getHeader2(allHeaders, "accept-encoding");
419
- if (!acceptEncodings) {
420
- return [];
421
- }
422
- const supportedMethods2 = {
423
- gzip: "DecompressionMethods.GZip",
424
- deflate: "DecompressionMethods.Deflate"
425
- };
426
- const methods = [];
427
- if (typeof acceptEncodings === "string") {
428
- acceptEncodings = [acceptEncodings];
429
- }
430
- acceptEncodings.forEach((acceptEncoding) => {
431
- acceptEncoding.split(",").forEach((encoding) => {
432
- const match = /\s*([^;\s]+)/.exec(encoding);
433
- if (match) {
434
- const method = supportedMethods2[match[1]];
435
- if (method) {
436
- methods.push(method);
437
- }
438
- }
439
- });
440
- });
441
- return methods;
442
- };
443
- var httpclient = {
444
- info: {
445
- key: "httpclient",
446
- title: "HttpClient",
447
- link: "https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient",
448
- description: ".NET Standard HTTP Client"
449
- },
450
- convert: ({ allHeaders, postData, method, fullUrl }, options) => {
451
- const opts = {
452
- indent: " ",
453
- ...options
454
- };
455
- const { push, join } = new CodeBuilder({ indent: opts.indent });
456
- push("using System.Net.Http.Headers;");
457
- let clienthandler = "";
458
- const cookies = Boolean(allHeaders.cookie);
459
- const decompressionMethods = getDecompressionMethods(allHeaders);
460
- if (cookies || decompressionMethods.length) {
461
- clienthandler = "clientHandler";
462
- push("var clientHandler = new HttpClientHandler");
463
- push("{");
464
- if (cookies) {
465
- push("UseCookies = false,", 1);
466
- }
467
- if (decompressionMethods.length) {
468
- push(`AutomaticDecompression = ${decompressionMethods.join(" | ")},`, 1);
469
- }
470
- push("};");
471
- }
472
- push(`var client = new HttpClient(${clienthandler});`);
473
- push("var request = new HttpRequestMessage");
474
- push("{");
475
- const methods = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS", "TRACE"];
476
- method = method.toUpperCase();
477
- if (method && methods.includes(method)) {
478
- method = `HttpMethod.${method[0]}${method.substring(1).toLowerCase()}`;
479
- } else {
480
- method = `new HttpMethod("${method}")`;
481
- }
482
- push(`Method = ${method},`, 1);
483
- push(`RequestUri = new Uri("${fullUrl}"),`, 1);
484
- const headers = Object.keys(allHeaders).filter((header) => {
485
- switch (header.toLowerCase()) {
486
- case "content-type":
487
- case "content-length":
488
- case "accept-encoding":
489
- return false;
490
- default:
491
- return true;
492
- }
493
- });
494
- if (headers.length) {
495
- push("Headers =", 1);
496
- push("{", 1);
497
- headers.forEach((key) => {
498
- push(`{ "${key}", "${escapeForDoubleQuotes(allHeaders[key])}" },`, 2);
499
- });
500
- push("},", 1);
501
- }
502
- if (postData.text) {
503
- const contentType = postData.mimeType;
504
- switch (contentType) {
505
- case "application/x-www-form-urlencoded":
506
- push("Content = new FormUrlEncodedContent(new Dictionary<string, string>", 1);
507
- push("{", 1);
508
- postData.params?.forEach((param) => {
509
- push(`{ "${param.name}", "${param.value}" },`, 2);
510
- });
511
- push("}),", 1);
512
- break;
513
- case "multipart/form-data":
514
- push("Content = new MultipartFormDataContent", 1);
515
- push("{", 1);
516
- postData.params?.forEach((param) => {
517
- push(`new StringContent(${JSON.stringify(param.value || "")})`, 2);
518
- push("{", 2);
519
- push("Headers =", 3);
520
- push("{", 3);
521
- if (param.contentType) {
522
- push(`ContentType = new MediaTypeHeaderValue("${param.contentType}"),`, 4);
523
- }
524
- push('ContentDisposition = new ContentDispositionHeaderValue("form-data")', 4);
525
- push("{", 4);
526
- push(`Name = "${param.name}",`, 5);
527
- if (param.fileName) {
528
- push(`FileName = "${param.fileName}",`, 5);
529
- }
530
- push("}", 4);
531
- push("}", 3);
532
- push("},", 2);
533
- });
534
- push("},", 1);
535
- break;
536
- default:
537
- push(`Content = new StringContent(${JSON.stringify(postData.text || "")})`, 1);
538
- push("{", 1);
539
- push("Headers =", 2);
540
- push("{", 2);
541
- push(`ContentType = new MediaTypeHeaderValue("${contentType}")`, 3);
542
- push("}", 2);
543
- push("}", 1);
544
- break;
545
- }
546
- }
547
- push("};");
548
- push("using (var response = await client.SendAsync(request))");
549
- push("{");
550
- push("response.EnsureSuccessStatusCode();", 1);
551
- push("var body = await response.Content.ReadAsStringAsync();", 1);
552
- push("Console.WriteLine(body);", 1);
553
- push("}");
554
- return join();
555
- }
556
- };
557
-
558
- // src/targets/csharp/restsharp/client.ts
559
- function title(s) {
560
- return s[0].toUpperCase() + s.slice(1).toLowerCase();
561
- }
562
- var restsharp = {
563
- info: {
564
- key: "restsharp",
565
- title: "RestSharp",
566
- link: "http://restsharp.org/",
567
- description: "Simple REST and HTTP API Client for .NET"
568
- },
569
- convert: ({ method, fullUrl, headersObj, cookies, postData, uriObj }) => {
570
- const { push, join } = new CodeBuilder();
571
- const isSupportedMethod = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"].includes(
572
- method.toUpperCase()
573
- );
574
- if (!isSupportedMethod) {
575
- return "Method not supported";
576
- }
577
- push("using RestSharp;\n\n");
578
- push(`var options = new RestClientOptions("${fullUrl}");`);
579
- push("var client = new RestClient(options);");
580
- push('var request = new RestRequest("");');
581
- const isMultipart = postData.mimeType && postData.mimeType === "multipart/form-data";
582
- if (isMultipart) {
583
- push("request.AlwaysMultipartFormData = true;");
584
- }
585
- Object.keys(headersObj).forEach((key) => {
586
- if (postData.mimeType && key.toLowerCase() === "content-type" && postData.text) {
587
- if (isMultipart && postData.boundary) {
588
- push(`request.FormBoundary = "${postData.boundary}";`);
589
- }
590
- return;
591
- }
592
- push(`request.AddHeader("${key}", "${escapeForDoubleQuotes(headersObj[key])}");`);
593
- });
594
- cookies.forEach(({ name, value }) => {
595
- push(`request.AddCookie("${name}", "${escapeForDoubleQuotes(value)}", "${uriObj.pathname}", "${uriObj.host}");`);
596
- });
597
- switch (postData.mimeType) {
598
- case "multipart/form-data":
599
- if (!postData.params)
600
- break;
601
- postData.params.forEach((param) => {
602
- if (param.fileName) {
603
- push(`request.AddFile("${param.name}", "${param.fileName}");`);
604
- } else {
605
- push(`request.AddParameter("${param.name}", "${param.value}");`);
606
- }
607
- });
608
- break;
609
- case "application/x-www-form-urlencoded":
610
- if (!postData.params)
611
- break;
612
- postData.params.forEach((param) => {
613
- push(`request.AddParameter("${param.name}", "${param.value}");`);
614
- });
615
- break;
616
- case "application/json": {
617
- if (!postData.text)
618
- break;
619
- const text = JSON.stringify(postData.text);
620
- push(`request.AddJsonBody(${text}, false);`);
621
- break;
622
- }
623
- default:
624
- if (!postData.text)
625
- break;
626
- push(`request.AddStringBody("${postData.text}", "${postData.mimeType}");`);
627
- }
628
- push(`var response = await client.${title(method)}Async(request);
629
- `);
630
- push('Console.WriteLine("{0}", response.Content);\n');
631
- return join();
632
- }
633
- };
634
-
635
- // src/targets/csharp/target.ts
636
- var csharp = {
637
- info: {
638
- key: "csharp",
639
- title: "C#",
640
- extname: ".cs",
641
- default: "restsharp",
642
- cli: "dotnet"
643
- },
644
- clientsById: {
645
- httpclient,
646
- restsharp
647
- }
648
- };
649
-
650
- // src/targets/go/native/client.ts
651
- var native = {
652
- info: {
653
- key: "native",
654
- title: "NewRequest",
655
- link: "http://golang.org/pkg/net/http/#NewRequest",
656
- description: "Golang HTTP client request"
657
- },
658
- convert: ({ postData, method, allHeaders, fullUrl }, options = {}) => {
659
- const { blank, push, join } = new CodeBuilder({ indent: " " });
660
- const { showBoilerplate = true, checkErrors = false, printBody = true, timeout = -1 } = options;
661
- const errorPlaceholder = checkErrors ? "err" : "_";
662
- const indent = showBoilerplate ? 1 : 0;
663
- const errorCheck = () => {
664
- if (checkErrors) {
665
- push("if err != nil {", indent);
666
- push("panic(err)", indent + 1);
667
- push("}", indent);
668
- }
669
- };
670
- if (showBoilerplate) {
671
- push("package main");
672
- blank();
673
- push("import (");
674
- push('"fmt"', indent);
675
- if (timeout > 0) {
676
- push('"time"', indent);
677
- }
678
- if (postData.text) {
679
- push('"strings"', indent);
680
- }
681
- push('"net/http"', indent);
682
- if (printBody) {
683
- push('"io"', indent);
684
- }
685
- push(")");
686
- blank();
687
- push("func main() {");
688
- blank();
689
- }
690
- const hasTimeout = timeout > 0;
691
- const hasClient = hasTimeout;
692
- const client = hasClient ? "client" : "http.DefaultClient";
693
- if (hasClient) {
694
- push("client := http.Client{", indent);
695
- if (hasTimeout) {
696
- push(`Timeout: time.Duration(${timeout} * time.Second),`, indent + 1);
697
- }
698
- push("}", indent);
699
- blank();
700
- }
701
- push(`url := "${fullUrl}"`, indent);
702
- blank();
703
- if (postData.text) {
704
- push(`payload := strings.NewReader(${JSON.stringify(postData.text)})`, indent);
705
- blank();
706
- push(`req, ${errorPlaceholder} := http.NewRequest("${method}", url, payload)`, indent);
707
- blank();
708
- } else {
709
- push(`req, ${errorPlaceholder} := http.NewRequest("${method}", url, nil)`, indent);
710
- blank();
711
- }
712
- errorCheck();
713
- if (Object.keys(allHeaders).length) {
714
- Object.keys(allHeaders).forEach((key) => {
715
- push(`req.Header.Add("${key}", "${escapeForDoubleQuotes(allHeaders[key])}")`, indent);
716
- });
717
- blank();
718
- }
719
- push(`res, ${errorPlaceholder} := ${client}.Do(req)`, indent);
720
- errorCheck();
721
- if (printBody) {
722
- blank();
723
- push("defer res.Body.Close()", indent);
724
- push(`body, ${errorPlaceholder} := io.ReadAll(res.Body)`, indent);
725
- errorCheck();
726
- }
727
- blank();
728
- if (printBody) {
729
- push("fmt.Println(string(body))", indent);
730
- }
731
- if (showBoilerplate) {
732
- blank();
733
- push("}");
734
- }
735
- return join();
736
- }
737
- };
738
-
739
- // src/targets/go/target.ts
740
- var go = {
741
- info: {
742
- key: "go",
743
- title: "Go",
744
- extname: ".go",
745
- default: "native",
746
- cli: "go"
747
- },
748
- clientsById: {
749
- native
750
- }
751
- };
752
-
753
- // src/targets/http/http1.1/client.ts
754
- var CRLF = "\r\n";
755
- var http11 = {
756
- info: {
757
- key: "http1.1",
758
- title: "HTTP/1.1",
759
- link: "https://tools.ietf.org/html/rfc7230",
760
- description: "HTTP/1.1 request string in accordance with RFC 7230"
761
- },
762
- convert: ({ method, fullUrl, uriObj, httpVersion, allHeaders, postData }, options) => {
763
- const opts = {
764
- absoluteURI: false,
765
- autoContentLength: true,
766
- autoHost: true,
767
- ...options
768
- };
769
- const { blank, push, join } = new CodeBuilder({ indent: "", join: CRLF });
770
- const requestUrl = opts.absoluteURI ? fullUrl : uriObj.path;
771
- push(`${method} ${requestUrl} ${httpVersion}`);
772
- const headerKeys = Object.keys(allHeaders);
773
- headerKeys.forEach((key) => {
774
- const keyCapitalized = key.toLowerCase().replace(/(^|-)(\w)/g, (input) => input.toUpperCase());
775
- push(`${keyCapitalized}: ${allHeaders[key]}`);
776
- });
777
- if (opts.autoHost && !headerKeys.includes("host")) {
778
- push(`Host: ${uriObj.host}`);
779
- }
780
- if (opts.autoContentLength && postData.text && !headerKeys.includes("content-length")) {
781
- const length = Buffer.byteLength(postData.text, "ascii").toString();
782
- push(`Content-Length: ${length}`);
783
- }
784
- blank();
785
- const headerSection = join();
786
- const messageBody = postData.text || "";
787
- return `${headerSection}${CRLF}${messageBody}`;
788
- }
789
- };
790
-
791
- // src/targets/http/target.ts
792
- var http = {
793
- info: {
794
- key: "http",
795
- title: "HTTP",
796
- extname: null,
797
- default: "1.1"
798
- },
799
- clientsById: {
800
- "http1.1": http11
801
- }
802
- };
803
-
804
- // src/targets/java/asynchttp/client.ts
805
- var asynchttp = {
806
- info: {
807
- key: "asynchttp",
808
- title: "AsyncHttp",
809
- link: "https://github.com/AsyncHttpClient/async-http-client",
810
- description: "Asynchronous Http and WebSocket Client library for Java"
811
- },
812
- convert: ({ method, allHeaders, postData, fullUrl }, options) => {
813
- const opts = {
814
- indent: " ",
815
- ...options
816
- };
817
- const { blank, push, join } = new CodeBuilder({ indent: opts.indent });
818
- push("AsyncHttpClient client = new DefaultAsyncHttpClient();");
819
- push(`client.prepare("${method.toUpperCase()}", "${fullUrl}")`);
820
- Object.keys(allHeaders).forEach((key) => {
821
- push(`.setHeader("${key}", "${escapeForDoubleQuotes(allHeaders[key])}")`, 1);
822
- });
823
- if (postData.text) {
824
- push(`.setBody(${JSON.stringify(postData.text)})`, 1);
825
- }
826
- push(".execute()", 1);
827
- push(".toCompletableFuture()", 1);
828
- push(".thenAccept(System.out::println)", 1);
829
- push(".join();", 1);
830
- blank();
831
- push("client.close();");
832
- return join();
833
- }
834
- };
835
-
836
- // src/targets/java/nethttp/client.ts
837
- var nethttp = {
838
- info: {
839
- key: "nethttp",
840
- title: "java.net.http",
841
- link: "https://openjdk.java.net/groups/net/httpclient/intro.html",
842
- description: "Java Standardized HTTP Client API"
843
- },
844
- convert: ({ allHeaders, fullUrl, method, postData }, options) => {
845
- const opts = {
846
- indent: " ",
847
- ...options
848
- };
849
- const { push, join } = new CodeBuilder({ indent: opts.indent });
850
- push("HttpRequest request = HttpRequest.newBuilder()");
851
- push(`.uri(URI.create("${fullUrl}"))`, 2);
852
- Object.keys(allHeaders).forEach((key) => {
853
- push(`.header("${key}", "${escapeForDoubleQuotes(allHeaders[key])}")`, 2);
854
- });
855
- if (postData.text) {
856
- push(
857
- `.method("${method.toUpperCase()}", HttpRequest.BodyPublishers.ofString(${JSON.stringify(postData.text)}))`,
858
- 2
859
- );
860
- } else {
861
- push(`.method("${method.toUpperCase()}", HttpRequest.BodyPublishers.noBody())`, 2);
862
- }
863
- push(".build();", 2);
864
- push(
865
- "HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());"
866
- );
867
- push("System.out.println(response.body());");
868
- return join();
869
- }
870
- };
871
-
872
- // src/targets/java/okhttp/client.ts
873
- var okhttp = {
874
- info: {
875
- key: "okhttp",
876
- title: "OkHttp",
877
- link: "http://square.github.io/okhttp/",
878
- description: "An HTTP Request Client Library"
879
- },
880
- convert: ({ postData, method, fullUrl, allHeaders }, options) => {
881
- const opts = {
882
- indent: " ",
883
- ...options
884
- };
885
- const { push, blank, join } = new CodeBuilder({ indent: opts.indent });
886
- const methods = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD"];
887
- const methodsWithBody = ["POST", "PUT", "DELETE", "PATCH"];
888
- push("OkHttpClient client = new OkHttpClient();");
889
- blank();
890
- if (postData.text) {
891
- if (postData.boundary) {
892
- push(`MediaType mediaType = MediaType.parse("${postData.mimeType}; boundary=${postData.boundary}");`);
893
- } else {
894
- push(`MediaType mediaType = MediaType.parse("${postData.mimeType}");`);
895
- }
896
- push(`RequestBody body = RequestBody.create(mediaType, ${JSON.stringify(postData.text)});`);
897
- }
898
- push("Request request = new Request.Builder()");
899
- push(`.url("${fullUrl}")`, 1);
900
- if (!methods.includes(method.toUpperCase())) {
901
- if (postData.text) {
902
- push(`.method("${method.toUpperCase()}", body)`, 1);
903
- } else {
904
- push(`.method("${method.toUpperCase()}", null)`, 1);
905
- }
906
- } else if (methodsWithBody.includes(method.toUpperCase())) {
907
- if (postData.text) {
908
- push(`.${method.toLowerCase()}(body)`, 1);
909
- } else {
910
- push(`.${method.toLowerCase()}(null)`, 1);
911
- }
912
- } else {
913
- push(`.${method.toLowerCase()}()`, 1);
914
- }
915
- Object.keys(allHeaders).forEach((key) => {
916
- push(`.addHeader("${key}", "${escapeForDoubleQuotes(allHeaders[key])}")`, 1);
917
- });
918
- push(".build();", 1);
919
- blank();
920
- push("Response response = client.newCall(request).execute();");
921
- return join();
922
- }
923
- };
924
-
925
- // src/targets/java/unirest/client.ts
926
- var unirest = {
927
- info: {
928
- key: "unirest",
929
- title: "Unirest",
930
- link: "http://unirest.io/java.html",
931
- description: "Lightweight HTTP Request Client Library"
932
- },
933
- convert: ({ method, allHeaders, postData, fullUrl }, options) => {
934
- const opts = {
935
- indent: " ",
936
- ...options
937
- };
938
- const { join, push } = new CodeBuilder({ indent: opts.indent });
939
- const methods = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"];
940
- if (!methods.includes(method.toUpperCase())) {
941
- push(`HttpResponse<String> response = Unirest.customMethod("${method.toUpperCase()}","${fullUrl}")`);
942
- } else {
943
- push(`HttpResponse<String> response = Unirest.${method.toLowerCase()}("${fullUrl}")`);
944
- }
945
- Object.keys(allHeaders).forEach((key) => {
946
- push(`.header("${key}", "${escapeForDoubleQuotes(allHeaders[key])}")`, 1);
947
- });
948
- if (postData.text) {
949
- push(`.body(${JSON.stringify(postData.text)})`, 1);
950
- }
951
- push(".asString();", 1);
952
- return join();
953
- }
954
- };
955
-
956
- // src/targets/java/target.ts
957
- var java = {
958
- info: {
959
- key: "java",
960
- title: "Java",
961
- extname: ".java",
962
- default: "unirest"
963
- },
964
- clientsById: {
965
- asynchttp,
966
- nethttp,
967
- okhttp,
968
- unirest
969
- }
970
- };
971
- var axios = {
972
- info: {
973
- key: "axios",
974
- title: "Axios",
975
- link: "https://github.com/axios/axios",
976
- description: "Promise based HTTP client for the browser and node.js"
977
- },
978
- convert: ({ allHeaders, method, url, queryObj, postData }, options) => {
979
- const opts = {
980
- indent: " ",
981
- ...options
982
- };
983
- const { blank, push, join, addPostProcessor } = new CodeBuilder({ indent: opts.indent });
984
- push("import axios from 'axios';");
985
- blank();
986
- const requestOptions = {
987
- method,
988
- url
989
- };
990
- if (Object.keys(queryObj).length) {
991
- requestOptions.params = queryObj;
992
- }
993
- if (Object.keys(allHeaders).length) {
994
- requestOptions.headers = allHeaders;
995
- }
996
- switch (postData.mimeType) {
997
- case "application/x-www-form-urlencoded":
998
- if (postData.params) {
999
- push("const encodedParams = new URLSearchParams();");
1000
- postData.params.forEach((param) => {
1001
- push(`encodedParams.set('${param.name}', '${param.value}');`);
1002
- });
1003
- blank();
1004
- requestOptions.data = "encodedParams,";
1005
- addPostProcessor((code) => code.replace(/'encodedParams,'/, "encodedParams,"));
1006
- }
1007
- break;
1008
- case "application/json":
1009
- if (postData.jsonObj) {
1010
- requestOptions.data = postData.jsonObj;
1011
- }
1012
- break;
1013
- case "multipart/form-data":
1014
- if (!postData.params) {
1015
- break;
1016
- }
1017
- push("const form = new FormData();");
1018
- postData.params.forEach((param) => {
1019
- push(`form.append('${param.name}', '${param.value || param.fileName || ""}');`);
1020
- });
1021
- blank();
1022
- requestOptions.data = "[form]";
1023
- break;
1024
- default:
1025
- if (postData.text) {
1026
- requestOptions.data = postData.text;
1027
- }
1028
- }
1029
- const optionString = stringifyObject9__default.default(requestOptions, {
1030
- indent: " ",
1031
- inlineCharacterLimit: 80
1032
- }).replace('"[form]"', "form");
1033
- push(`const options = ${optionString};`);
1034
- blank();
1035
- push("axios");
1036
- push(".request(options)", 1);
1037
- push(".then(function (response) {", 1);
1038
- push("console.log(response.data);", 2);
1039
- push("})", 1);
1040
- push(".catch(function (error) {", 1);
1041
- push("console.error(error);", 2);
1042
- push("});", 1);
1043
- return join();
1044
- }
1045
- };
1046
- var fetch = {
1047
- info: {
1048
- key: "fetch",
1049
- title: "fetch",
1050
- link: "https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch",
1051
- description: "Perform asynchronous HTTP requests with the Fetch API"
1052
- },
1053
- convert: ({ method, allHeaders, postData, fullUrl }, inputOpts) => {
1054
- const opts = {
1055
- indent: " ",
1056
- credentials: null,
1057
- ...inputOpts
1058
- };
1059
- const { blank, join, push } = new CodeBuilder({ indent: opts.indent });
1060
- const options = {
1061
- method
1062
- };
1063
- if (Object.keys(allHeaders).length) {
1064
- options.headers = allHeaders;
1065
- }
1066
- if (opts.credentials !== null) {
1067
- options.credentials = opts.credentials;
1068
- }
1069
- switch (postData.mimeType) {
1070
- case "application/x-www-form-urlencoded":
1071
- options.body = postData.paramsObj ? postData.paramsObj : postData.text;
1072
- break;
1073
- case "application/json":
1074
- if (postData.jsonObj) {
1075
- options.body = postData.jsonObj;
1076
- }
1077
- break;
1078
- case "multipart/form-data":
1079
- if (!postData.params) {
1080
- break;
1081
- }
1082
- const contentTypeHeader = getHeaderName(allHeaders, "content-type");
1083
- if (contentTypeHeader) {
1084
- delete allHeaders[contentTypeHeader];
1085
- }
1086
- push("const form = new FormData();");
1087
- postData.params.forEach((param) => {
1088
- push(`form.append('${param.name}', '${param.value || param.fileName || ""}');`);
1089
- });
1090
- blank();
1091
- break;
1092
- default:
1093
- if (postData.text) {
1094
- options.body = postData.text;
1095
- }
1096
- }
1097
- if (options.headers && !Object.keys(options.headers).length) {
1098
- delete options.headers;
1099
- }
1100
- push(
1101
- `const options = ${stringifyObject9__default.default(options, {
1102
- indent: opts.indent,
1103
- inlineCharacterLimit: 80,
1104
- // The Fetch API body only accepts string parameters, but stringified JSON can be difficult
1105
- // to read, so we keep the object as a literal and use this transform function to wrap the
1106
- // literal in a `JSON.stringify` call.
1107
- transform: (object, property, originalResult) => {
1108
- if (property === "body") {
1109
- if (postData.mimeType === "application/x-www-form-urlencoded") {
1110
- return `new URLSearchParams(${originalResult})`;
1111
- } else if (postData.mimeType === "application/json") {
1112
- return `JSON.stringify(${originalResult})`;
1113
- }
1114
- }
1115
- return originalResult;
1116
- }
1117
- })};`
1118
- );
1119
- blank();
1120
- if (postData.params && postData.mimeType === "multipart/form-data") {
1121
- push("options.body = form;");
1122
- blank();
1123
- }
1124
- push(`fetch('${fullUrl}', options)`);
1125
- push(".then(response => response.json())", 1);
1126
- push(".then(response => console.log(response))", 1);
1127
- push(".catch(err => console.error(err));", 1);
1128
- return join();
1129
- }
1130
- };
1131
- var jquery = {
1132
- info: {
1133
- key: "jquery",
1134
- title: "jQuery",
1135
- link: "http://api.jquery.com/jquery.ajax/",
1136
- description: "Perform an asynchronous HTTP (Ajax) requests with jQuery"
1137
- },
1138
- convert: ({ fullUrl, method, allHeaders, postData }, options) => {
1139
- const opts = {
1140
- indent: " ",
1141
- ...options
1142
- };
1143
- const { blank, push, join } = new CodeBuilder({ indent: opts.indent });
1144
- const settings = {
1145
- async: true,
1146
- crossDomain: true,
1147
- url: fullUrl,
1148
- method,
1149
- headers: allHeaders
1150
- };
1151
- switch (postData.mimeType) {
1152
- case "application/x-www-form-urlencoded":
1153
- settings.data = postData.paramsObj ? postData.paramsObj : postData.text;
1154
- break;
1155
- case "application/json":
1156
- settings.processData = false;
1157
- settings.data = postData.text;
1158
- break;
1159
- case "multipart/form-data":
1160
- if (!postData.params) {
1161
- break;
1162
- }
1163
- push("const form = new FormData();");
1164
- postData.params.forEach((param) => {
1165
- push(`form.append('${param.name}', '${param.value || param.fileName || ""}');`);
1166
- });
1167
- settings.processData = false;
1168
- settings.contentType = false;
1169
- settings.mimeType = "multipart/form-data";
1170
- settings.data = "[form]";
1171
- if (hasHeader(allHeaders, "content-type")) {
1172
- if (getHeader2(allHeaders, "content-type")?.includes("boundary")) {
1173
- const headerName = getHeaderName(allHeaders, "content-type");
1174
- if (headerName) {
1175
- delete settings.headers[headerName];
1176
- }
1177
- }
1178
- }
1179
- blank();
1180
- break;
1181
- default:
1182
- if (postData.text) {
1183
- settings.data = postData.text;
1184
- }
1185
- }
1186
- const stringifiedSettings = stringifyObject9__default.default(settings, { indent: opts.indent }).replace("'[form]'", "form");
1187
- push(`const settings = ${stringifiedSettings};`);
1188
- blank();
1189
- push("$.ajax(settings).done(function (response) {");
1190
- push("console.log(response);", 1);
1191
- push("});");
1192
- return join();
1193
- }
1194
- };
1195
- var xhr = {
1196
- info: {
1197
- key: "xhr",
1198
- title: "XMLHttpRequest",
1199
- link: "https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest",
1200
- description: "W3C Standard API that provides scripted client functionality"
1201
- },
1202
- convert: ({ postData, allHeaders, method, fullUrl }, options) => {
1203
- const opts = {
1204
- indent: " ",
1205
- cors: true,
1206
- ...options
1207
- };
1208
- const { blank, push, join } = new CodeBuilder({ indent: opts.indent });
1209
- switch (postData.mimeType) {
1210
- case "application/json":
1211
- push(
1212
- `const data = JSON.stringify(${stringifyObject9__default.default(postData.jsonObj, {
1213
- indent: opts.indent
1214
- })});`
1215
- );
1216
- blank();
1217
- break;
1218
- case "multipart/form-data":
1219
- if (!postData.params) {
1220
- break;
1221
- }
1222
- push("const data = new FormData();");
1223
- postData.params.forEach((param) => {
1224
- push(`data.append('${param.name}', '${param.value || param.fileName || ""}');`);
1225
- });
1226
- if (hasHeader(allHeaders, "content-type")) {
1227
- if (getHeader2(allHeaders, "content-type")?.includes("boundary")) {
1228
- const headerName = getHeaderName(allHeaders, "content-type");
1229
- if (headerName) {
1230
- delete allHeaders[headerName];
1231
- }
1232
- }
1233
- }
1234
- blank();
1235
- break;
1236
- default:
1237
- push(`const data = ${postData.text ? `'${postData.text}'` : "null"};`);
1238
- blank();
1239
- }
1240
- push("const xhr = new XMLHttpRequest();");
1241
- if (opts.cors) {
1242
- push("xhr.withCredentials = true;");
1243
- }
1244
- blank();
1245
- push("xhr.addEventListener('readystatechange', function () {");
1246
- push("if (this.readyState === this.DONE) {", 1);
1247
- push("console.log(this.responseText);", 2);
1248
- push("}", 1);
1249
- push("});");
1250
- blank();
1251
- push(`xhr.open('${method}', '${fullUrl}');`);
1252
- Object.keys(allHeaders).forEach((key) => {
1253
- push(`xhr.setRequestHeader('${key}', '${escapeForSingleQuotes(allHeaders[key])}');`);
1254
- });
1255
- blank();
1256
- push("xhr.send(data);");
1257
- return join();
1258
- }
1259
- };
1260
-
1261
- // src/targets/javascript/target.ts
1262
- var javascript = {
1263
- info: {
1264
- key: "javascript",
1265
- title: "JavaScript",
1266
- extname: ".js",
1267
- default: "xhr"
1268
- },
1269
- clientsById: {
1270
- xhr,
1271
- axios,
1272
- fetch,
1273
- jquery
1274
- }
1275
- };
1276
-
1277
- // src/targets/json/native/client.ts
1278
- var native2 = {
1279
- info: {
1280
- key: "native",
1281
- title: "Native JSON",
1282
- link: "https://www.json.org/json-en.html",
1283
- description: "A JSON represetation of any HAR payload."
1284
- },
1285
- convert: ({ postData }, inputOpts) => {
1286
- const opts = {
1287
- indent: " ",
1288
- ...inputOpts
1289
- };
1290
- let payload = "";
1291
- switch (postData.mimeType) {
1292
- case "application/x-www-form-urlencoded":
1293
- payload = postData.paramsObj ? postData.paramsObj : postData.text;
1294
- break;
1295
- case "application/json":
1296
- if (postData.jsonObj) {
1297
- payload = postData.jsonObj;
1298
- }
1299
- break;
1300
- case "multipart/form-data":
1301
- if (!postData.params) {
1302
- break;
1303
- }
1304
- const multipartPayload = {};
1305
- postData.params.forEach((param) => {
1306
- multipartPayload[param.name] = param.value;
1307
- });
1308
- payload = multipartPayload;
1309
- break;
1310
- default:
1311
- if (postData.text) {
1312
- payload = postData.text;
1313
- }
1314
- }
1315
- if (typeof payload === "undefined" || payload === "") {
1316
- return "No JSON body";
1317
- }
1318
- return JSON.stringify(payload, null, opts.indent);
1319
- }
1320
- };
1321
-
1322
- // src/targets/json/target.ts
1323
- var json = {
1324
- info: {
1325
- key: "json",
1326
- title: "JSON",
1327
- extname: ".json",
1328
- default: "native"
1329
- },
1330
- clientsById: {
1331
- native: native2
1332
- }
1333
- };
1334
-
1335
- // src/targets/kotlin/okhttp/client.ts
1336
- var okhttp2 = {
1337
- info: {
1338
- key: "okhttp",
1339
- title: "OkHttp",
1340
- link: "http://square.github.io/okhttp/",
1341
- description: "An HTTP Request Client Library"
1342
- },
1343
- convert: ({ postData, fullUrl, method, allHeaders }, options) => {
1344
- const opts = {
1345
- indent: " ",
1346
- ...options
1347
- };
1348
- const { blank, join, push } = new CodeBuilder({ indent: opts.indent });
1349
- const methods = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD"];
1350
- const methodsWithBody = ["POST", "PUT", "DELETE", "PATCH"];
1351
- push("val client = OkHttpClient()");
1352
- blank();
1353
- if (postData.text) {
1354
- if (postData.boundary) {
1355
- push(`val mediaType = MediaType.parse("${postData.mimeType}; boundary=${postData.boundary}")`);
1356
- } else {
1357
- push(`val mediaType = MediaType.parse("${postData.mimeType}")`);
1358
- }
1359
- push(`val body = RequestBody.create(mediaType, ${JSON.stringify(postData.text)})`);
1360
- }
1361
- push("val request = Request.Builder()");
1362
- push(`.url("${fullUrl}")`, 1);
1363
- if (!methods.includes(method.toUpperCase())) {
1364
- if (postData.text) {
1365
- push(`.method("${method.toUpperCase()}", body)`, 1);
1366
- } else {
1367
- push(`.method("${method.toUpperCase()}", null)`, 1);
1368
- }
1369
- } else if (methodsWithBody.includes(method.toUpperCase())) {
1370
- if (postData.text) {
1371
- push(`.${method.toLowerCase()}(body)`, 1);
1372
- } else {
1373
- push(`.${method.toLowerCase()}(null)`, 1);
1374
- }
1375
- } else {
1376
- push(`.${method.toLowerCase()}()`, 1);
1377
- }
1378
- Object.keys(allHeaders).forEach((key) => {
1379
- push(`.addHeader("${key}", "${escapeForDoubleQuotes(allHeaders[key])}")`, 1);
1380
- });
1381
- push(".build()", 1);
1382
- blank();
1383
- push("val response = client.newCall(request).execute()");
1384
- return join();
1385
- }
1386
- };
1387
-
1388
- // src/targets/kotlin/target.ts
1389
- var kotlin = {
1390
- info: {
1391
- key: "kotlin",
1392
- title: "Kotlin",
1393
- extname: ".kt",
1394
- default: "okhttp"
1395
- },
1396
- clientsById: {
1397
- okhttp: okhttp2
1398
- }
1399
- };
1400
- var axios2 = {
1401
- info: {
1402
- key: "axios",
1403
- title: "Axios",
1404
- link: "https://github.com/axios/axios",
1405
- description: "Promise based HTTP client for the browser and node.js"
1406
- },
1407
- convert: ({ method, fullUrl, allHeaders, postData }, options) => {
1408
- const opts = {
1409
- indent: " ",
1410
- ...options
1411
- };
1412
- const { blank, join, push, addPostProcessor } = new CodeBuilder({ indent: opts.indent });
1413
- push("const axios = require('axios');");
1414
- const reqOpts = {
1415
- method,
1416
- url: fullUrl
1417
- };
1418
- if (Object.keys(allHeaders).length) {
1419
- reqOpts.headers = allHeaders;
1420
- }
1421
- switch (postData.mimeType) {
1422
- case "application/x-www-form-urlencoded":
1423
- if (postData.params) {
1424
- push("const { URLSearchParams } = require('url');");
1425
- blank();
1426
- push("const encodedParams = new URLSearchParams();");
1427
- postData.params.forEach((param) => {
1428
- push(`encodedParams.set('${param.name}', '${param.value}');`);
1429
- });
1430
- blank();
1431
- reqOpts.data = "encodedParams,";
1432
- addPostProcessor((code) => code.replace(/'encodedParams,'/, "encodedParams,"));
1433
- }
1434
- break;
1435
- case "application/json":
1436
- blank();
1437
- if (postData.jsonObj) {
1438
- reqOpts.data = postData.jsonObj;
1439
- }
1440
- break;
1441
- default:
1442
- blank();
1443
- if (postData.text) {
1444
- reqOpts.data = postData.text;
1445
- }
1446
- }
1447
- const stringifiedOptions = stringifyObject9__default.default(reqOpts, { indent: " ", inlineCharacterLimit: 80 });
1448
- push(`const options = ${stringifiedOptions};`);
1449
- blank();
1450
- push("axios");
1451
- push(".request(options)", 1);
1452
- push(".then(function (response) {", 1);
1453
- push("console.log(response.data);", 2);
1454
- push("})", 1);
1455
- push(".catch(function (error) {", 1);
1456
- push("console.error(error);", 2);
1457
- push("});", 1);
1458
- return join();
1459
- }
1460
- };
1461
- var fetch2 = {
1462
- info: {
1463
- key: "fetch",
1464
- title: "Fetch",
1465
- link: "https://github.com/bitinn/node-fetch",
1466
- description: "Simplified HTTP node-fetch client"
1467
- },
1468
- convert: ({ method, fullUrl, postData, headersObj, cookies }, options) => {
1469
- const opts = {
1470
- indent: " ",
1471
- ...options
1472
- };
1473
- let includeFS = false;
1474
- const { blank, push, join, unshift } = new CodeBuilder({ indent: opts.indent });
1475
- push("const fetch = require('node-fetch');");
1476
- const url = fullUrl;
1477
- const reqOpts = {
1478
- method
1479
- };
1480
- if (Object.keys(headersObj).length) {
1481
- reqOpts.headers = headersObj;
1482
- }
1483
- switch (postData.mimeType) {
1484
- case "application/x-www-form-urlencoded":
1485
- unshift("const { URLSearchParams } = require('url');");
1486
- push("const encodedParams = new URLSearchParams();");
1487
- blank();
1488
- postData.params?.forEach((param) => {
1489
- push(`encodedParams.set('${param.name}', '${param.value}');`);
1490
- });
1491
- reqOpts.body = "encodedParams";
1492
- break;
1493
- case "application/json":
1494
- if (postData.jsonObj) {
1495
- reqOpts.body = postData.jsonObj;
1496
- }
1497
- break;
1498
- case "multipart/form-data":
1499
- if (!postData.params) {
1500
- break;
1501
- }
1502
- const contentTypeHeader = getHeaderName(headersObj, "content-type");
1503
- if (contentTypeHeader) {
1504
- delete headersObj[contentTypeHeader];
1505
- }
1506
- unshift("const FormData = require('form-data');");
1507
- push("const formData = new FormData();");
1508
- blank();
1509
- postData.params.forEach((param) => {
1510
- if (!param.fileName && !param.fileName && !param.contentType) {
1511
- push(`formData.append('${param.name}', '${param.value}');`);
1512
- return;
1513
- }
1514
- if (param.fileName) {
1515
- includeFS = true;
1516
- push(`formData.append('${param.name}', fs.createReadStream('${param.fileName}'));`);
1517
- }
1518
- });
1519
- break;
1520
- default:
1521
- if (postData.text) {
1522
- reqOpts.body = postData.text;
1523
- }
1524
- }
1525
- if (cookies.length) {
1526
- const cookiesString = cookies.map(({ name, value }) => `${encodeURIComponent(name)}=${encodeURIComponent(value)}`).join("; ");
1527
- if (reqOpts.headers) {
1528
- reqOpts.headers.cookie = cookiesString;
1529
- } else {
1530
- reqOpts.headers = {};
1531
- reqOpts.headers.cookie = cookiesString;
1532
- }
1533
- }
1534
- blank();
1535
- push(`const url = '${url}';`);
1536
- if (reqOpts.headers && !Object.keys(reqOpts.headers).length) {
1537
- delete reqOpts.headers;
1538
- }
1539
- const stringifiedOptions = stringifyObject9__default.default(reqOpts, {
1540
- indent: " ",
1541
- inlineCharacterLimit: 80,
1542
- // The Fetch API body only accepts string parameters, but stringified JSON can be difficult to
1543
- // read, so we keep the object as a literal and use this transform function to wrap the literal
1544
- // in a `JSON.stringify` call.
1545
- transform: (object, property, originalResult) => {
1546
- if (property === "body" && postData.mimeType === "application/json") {
1547
- return `JSON.stringify(${originalResult})`;
1548
- }
1549
- return originalResult;
1550
- }
1551
- });
1552
- push(`const options = ${stringifiedOptions};`);
1553
- blank();
1554
- if (includeFS) {
1555
- unshift("const fs = require('fs');");
1556
- }
1557
- if (postData.params && postData.mimeType === "multipart/form-data") {
1558
- push("options.body = formData;");
1559
- blank();
1560
- }
1561
- push("fetch(url, options)");
1562
- push(".then(res => res.json())", 1);
1563
- push(".then(json => console.log(json))", 1);
1564
- push(".catch(err => console.error('error:' + err));", 1);
1565
- return join().replace(/'encodedParams'/, "encodedParams").replace(/"fs\.createReadStream\(\\"(.+)\\"\)"/, 'fs.createReadStream("$1")');
1566
- }
1567
- };
1568
- var native3 = {
1569
- info: {
1570
- key: "native",
1571
- title: "HTTP",
1572
- link: "http://nodejs.org/api/http.html#http_http_request_options_callback",
1573
- description: "Node.js native HTTP interface"
1574
- },
1575
- convert: ({ uriObj, method, allHeaders, postData }, options = {}) => {
1576
- const { indent = " " } = options;
1577
- const { blank, join, push, unshift } = new CodeBuilder({ indent });
1578
- const reqOpts = {
1579
- method,
1580
- hostname: uriObj.hostname,
1581
- port: uriObj.port,
1582
- path: uriObj.path,
1583
- headers: allHeaders
1584
- };
1585
- push(`const http = require('${uriObj.protocol?.replace(":", "")}');`);
1586
- blank();
1587
- push(`const options = ${stringifyObject9__default.default(reqOpts, { indent })};`);
1588
- blank();
1589
- push("const req = http.request(options, function (res) {");
1590
- push("const chunks = [];", 1);
1591
- blank();
1592
- push("res.on('data', function (chunk) {", 1);
1593
- push("chunks.push(chunk);", 2);
1594
- push("});", 1);
1595
- blank();
1596
- push("res.on('end', function () {", 1);
1597
- push("const body = Buffer.concat(chunks);", 2);
1598
- push("console.log(body.toString());", 2);
1599
- push("});", 1);
1600
- push("});");
1601
- blank();
1602
- switch (postData.mimeType) {
1603
- case "application/x-www-form-urlencoded":
1604
- if (postData.paramsObj) {
1605
- unshift("const qs = require('querystring');");
1606
- push(
1607
- `req.write(qs.stringify(${stringifyObject9__default.default(postData.paramsObj, {
1608
- indent: " ",
1609
- inlineCharacterLimit: 80
1610
- })}));`
1611
- );
1612
- }
1613
- break;
1614
- case "application/json":
1615
- if (postData.jsonObj) {
1616
- push(
1617
- `req.write(JSON.stringify(${stringifyObject9__default.default(postData.jsonObj, {
1618
- indent: " ",
1619
- inlineCharacterLimit: 80
1620
- })}));`
1621
- );
1622
- }
1623
- break;
1624
- default:
1625
- if (postData.text) {
1626
- push(`req.write(${stringifyObject9__default.default(postData.text, { indent })});`);
1627
- }
1628
- }
1629
- push("req.end();");
1630
- return join();
1631
- }
1632
- };
1633
- var request = {
1634
- info: {
1635
- key: "request",
1636
- title: "Request",
1637
- link: "https://github.com/request/request",
1638
- description: "Simplified HTTP request client"
1639
- },
1640
- convert: ({ method, url, fullUrl, postData, headersObj, cookies }, options) => {
1641
- const opts = {
1642
- indent: " ",
1643
- ...options
1644
- };
1645
- let includeFS = false;
1646
- const { push, blank, join, unshift, addPostProcessor } = new CodeBuilder({ indent: opts.indent });
1647
- push("const request = require('request');");
1648
- blank();
1649
- const reqOpts = {
1650
- method,
1651
- url: fullUrl
1652
- };
1653
- if (Object.keys(headersObj).length) {
1654
- reqOpts.headers = headersObj;
1655
- }
1656
- switch (postData.mimeType) {
1657
- case "application/x-www-form-urlencoded":
1658
- reqOpts.form = postData.paramsObj;
1659
- break;
1660
- case "application/json":
1661
- if (postData.jsonObj) {
1662
- reqOpts.body = postData.jsonObj;
1663
- reqOpts.json = true;
1664
- }
1665
- break;
1666
- case "multipart/form-data":
1667
- if (!postData.params) {
1668
- break;
1669
- }
1670
- reqOpts.formData = {};
1671
- postData.params.forEach((param) => {
1672
- if (!param.fileName && !param.fileName && !param.contentType) {
1673
- reqOpts.formData[param.name] = param.value;
1674
- return;
1675
- }
1676
- let attachment = {};
1677
- if (param.fileName) {
1678
- includeFS = true;
1679
- attachment = {
1680
- value: `fs.createReadStream(${param.fileName})`,
1681
- options: {
1682
- filename: param.fileName,
1683
- contentType: param.contentType ? param.contentType : null
1684
- }
1685
- };
1686
- } else if (param.value) {
1687
- attachment.value = param.value;
1688
- }
1689
- reqOpts.formData[param.name] = attachment;
1690
- });
1691
- addPostProcessor((code) => code.replace(/'fs\.createReadStream\((.*)\)'/, "fs.createReadStream('$1')"));
1692
- break;
1693
- default:
1694
- if (postData.text) {
1695
- reqOpts.body = postData.text;
1696
- }
1697
- }
1698
- if (cookies.length) {
1699
- reqOpts.jar = "JAR";
1700
- push("const jar = request.jar();");
1701
- cookies.forEach(({ name, value }) => {
1702
- push(`jar.setCookie(request.cookie('${encodeURIComponent(name)}=${encodeURIComponent(value)}'), '${url}');`);
1703
- });
1704
- blank();
1705
- addPostProcessor((code) => code.replace(/'JAR'/, "jar"));
1706
- }
1707
- if (includeFS) {
1708
- unshift("const fs = require('fs');");
1709
- }
1710
- push(`const options = ${stringifyObject9__default.default(reqOpts, { indent: " ", inlineCharacterLimit: 80 })};`);
1711
- blank();
1712
- push("request(options, function (error, response, body) {");
1713
- push("if (error) throw new Error(error);", 1);
1714
- blank();
1715
- push("console.log(body);", 1);
1716
- push("});");
1717
- return join();
1718
- }
1719
- };
1720
- var unirest2 = {
1721
- info: {
1722
- key: "unirest",
1723
- title: "Unirest",
1724
- link: "http://unirest.io/nodejs.html",
1725
- description: "Lightweight HTTP Request Client Library"
1726
- },
1727
- convert: ({ method, url, cookies, queryObj, postData, headersObj }, options) => {
1728
- const opts = {
1729
- indent: " ",
1730
- ...options
1731
- };
1732
- let includeFS = false;
1733
- const { addPostProcessor, blank, join, push, unshift } = new CodeBuilder({
1734
- indent: opts.indent
1735
- });
1736
- push("const unirest = require('unirest');");
1737
- blank();
1738
- push(`const req = unirest('${method}', '${url}');`);
1739
- blank();
1740
- if (cookies.length) {
1741
- push("const CookieJar = unirest.jar();");
1742
- cookies.forEach((cookie) => {
1743
- push(`CookieJar.add('${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}', '${url}');`);
1744
- });
1745
- push("req.jar(CookieJar);");
1746
- blank();
1747
- }
1748
- if (Object.keys(queryObj).length) {
1749
- push(`req.query(${stringifyObject9__default.default(queryObj, { indent: opts.indent })});`);
1750
- blank();
1751
- }
1752
- if (Object.keys(headersObj).length) {
1753
- push(`req.headers(${stringifyObject9__default.default(headersObj, { indent: opts.indent })});`);
1754
- blank();
1755
- }
1756
- switch (postData.mimeType) {
1757
- case "application/x-www-form-urlencoded":
1758
- if (postData.paramsObj) {
1759
- push(`req.form(${stringifyObject9__default.default(postData.paramsObj, { indent: opts.indent })});`);
1760
- blank();
1761
- }
1762
- break;
1763
- case "application/json":
1764
- if (postData.jsonObj) {
1765
- push("req.type('json');");
1766
- push(`req.send(${stringifyObject9__default.default(postData.jsonObj, { indent: opts.indent })});`);
1767
- blank();
1768
- }
1769
- break;
1770
- case "multipart/form-data": {
1771
- if (!postData.params) {
1772
- break;
1773
- }
1774
- const multipart = [];
1775
- postData.params.forEach((param) => {
1776
- const part = {};
1777
- if (param.fileName && !param.value) {
1778
- includeFS = true;
1779
- part.body = `fs.createReadStream('${param.fileName}')`;
1780
- addPostProcessor((code) => code.replace(/'fs\.createReadStream\(\\'(.+)\\'\)'/, "fs.createReadStream('$1')"));
1781
- } else if (param.value) {
1782
- part.body = param.value;
1783
- }
1784
- if (part.body) {
1785
- if (param.contentType) {
1786
- part["content-type"] = param.contentType;
1787
- }
1788
- multipart.push(part);
1789
- }
1790
- });
1791
- push(`req.multipart(${stringifyObject9__default.default(multipart, { indent: opts.indent })});`);
1792
- blank();
1793
- break;
1794
- }
1795
- default:
1796
- if (postData.text) {
1797
- push(`req.send(${stringifyObject9__default.default(postData.text, { indent: opts.indent })});`);
1798
- blank();
1799
- }
1800
- }
1801
- if (includeFS) {
1802
- unshift("const fs = require('fs');");
1803
- }
1804
- push("req.end(function (res) {");
1805
- push("if (res.error) throw new Error(res.error);", 1);
1806
- blank();
1807
- push("console.log(res.body);", 1);
1808
- push("});");
1809
- return join();
1810
- }
1811
- };
1812
-
1813
- // src/targets/node/target.ts
1814
- var node = {
1815
- info: {
1816
- key: "node",
1817
- title: "Node.js",
1818
- extname: ".js",
1819
- default: "native",
1820
- cli: "node %s"
1821
- },
1822
- clientsById: {
1823
- native: native3,
1824
- request,
1825
- unirest: unirest2,
1826
- axios: axios2,
1827
- fetch: fetch2
1828
- }
1829
- };
1830
-
1831
- // src/targets/objc/helpers.ts
1832
- var nsDeclaration = (nsClass, name, parameters, indent) => {
1833
- const opening = `${nsClass} *${name} = `;
1834
- const literal = literalRepresentation(parameters, indent ? opening.length : void 0);
1835
- return `${opening}${literal};`;
1836
- };
1837
- var literalRepresentation = (value, indentation) => {
1838
- const join = indentation === void 0 ? ", " : `,
1839
- ${" ".repeat(indentation)}`;
1840
- switch (Object.prototype.toString.call(value)) {
1841
- case "[object Number]":
1842
- return `@${value}`;
1843
- case "[object Array]": {
1844
- const valuesRepresentation = value.map((val) => literalRepresentation(val));
1845
- return `@[ ${valuesRepresentation.join(join)} ]`;
1846
- }
1847
- case "[object Object]": {
1848
- const keyValuePairs = [];
1849
- Object.keys(value).forEach((key) => {
1850
- keyValuePairs.push(`@"${key}": ${literalRepresentation(value[key])}`);
1851
- });
1852
- return `@{ ${keyValuePairs.join(join)} }`;
1853
- }
1854
- case "[object Boolean]":
1855
- return value ? "@YES" : "@NO";
1856
- default:
1857
- if (value === null || value === void 0) {
1858
- return "";
1859
- }
1860
- return `@"${value.toString().replace(/"/g, '\\"')}"`;
1861
- }
1862
- };
1863
-
1864
- // src/targets/objc/nsurlsession/client.ts
1865
- var nsurlsession = {
1866
- info: {
1867
- key: "nsurlsession",
1868
- title: "NSURLSession",
1869
- link: "https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSession_class/index.html",
1870
- description: "Foundation's NSURLSession request"
1871
- },
1872
- convert: ({ allHeaders, postData, method, fullUrl }, options) => {
1873
- const opts = {
1874
- indent: " ",
1875
- pretty: true,
1876
- timeout: 10,
1877
- ...options
1878
- };
1879
- const { push, join, blank } = new CodeBuilder({ indent: opts.indent });
1880
- const req = {
1881
- hasHeaders: false,
1882
- hasBody: false
1883
- };
1884
- push("#import <Foundation/Foundation.h>");
1885
- if (Object.keys(allHeaders).length) {
1886
- req.hasHeaders = true;
1887
- blank();
1888
- push(nsDeclaration("NSDictionary", "headers", allHeaders, opts.pretty));
1889
- }
1890
- if (postData.text || postData.jsonObj || postData.params) {
1891
- req.hasBody = true;
1892
- switch (postData.mimeType) {
1893
- case "application/x-www-form-urlencoded":
1894
- if (postData.params?.length) {
1895
- blank();
1896
- const [head, ...tail] = postData.params;
1897
- push(
1898
- `NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"${head.name}=${head.value}" dataUsingEncoding:NSUTF8StringEncoding]];`
1899
- );
1900
- tail.forEach(({ name, value }) => {
1901
- push(`[postData appendData:[@"&${name}=${value}" dataUsingEncoding:NSUTF8StringEncoding]];`);
1902
- });
1903
- } else {
1904
- req.hasBody = false;
1905
- }
1906
- break;
1907
- case "application/json":
1908
- if (postData.jsonObj) {
1909
- push(nsDeclaration("NSDictionary", "parameters", postData.jsonObj, opts.pretty));
1910
- blank();
1911
- push("NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];");
1912
- }
1913
- break;
1914
- case "multipart/form-data":
1915
- push(nsDeclaration("NSArray", "parameters", postData.params || [], opts.pretty));
1916
- push(`NSString *boundary = @"${postData.boundary}";`);
1917
- blank();
1918
- push("NSError *error;");
1919
- push("NSMutableString *body = [NSMutableString string];");
1920
- push("for (NSDictionary *param in parameters) {");
1921
- push('[body appendFormat:@"--%@\\r\\n", boundary];', 1);
1922
- push('if (param[@"fileName"]) {', 1);
1923
- push(
1924
- '[body appendFormat:@"Content-Disposition:form-data; name=\\"%@\\"; filename=\\"%@\\"\\r\\n", param[@"name"], param[@"fileName"]];',
1925
- 2
1926
- );
1927
- push('[body appendFormat:@"Content-Type: %@\\r\\n\\r\\n", param[@"contentType"]];', 2);
1928
- push(
1929
- '[body appendFormat:@"%@", [NSString stringWithContentsOfFile:param[@"fileName"] encoding:NSUTF8StringEncoding error:&error]];',
1930
- 2
1931
- );
1932
- push("if (error) {", 2);
1933
- push('NSLog(@"%@", error);', 3);
1934
- push("}", 2);
1935
- push("} else {", 1);
1936
- push('[body appendFormat:@"Content-Disposition:form-data; name=\\"%@\\"\\r\\n\\r\\n", param[@"name"]];', 2);
1937
- push('[body appendFormat:@"%@", param[@"value"]];', 2);
1938
- push("}", 1);
1939
- push("}");
1940
- push('[body appendFormat:@"\\r\\n--%@--\\r\\n", boundary];');
1941
- push("NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding];");
1942
- break;
1943
- default:
1944
- blank();
1945
- push(
1946
- `NSData *postData = [[NSData alloc] initWithData:[@"${postData.text}" dataUsingEncoding:NSUTF8StringEncoding]];`
1947
- );
1948
- }
1949
- }
1950
- blank();
1951
- push(`NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"${fullUrl}"]`);
1952
- push(" cachePolicy:NSURLRequestUseProtocolCachePolicy");
1953
- push(` timeoutInterval:${opts.timeout.toFixed(1)}];`);
1954
- push(`[request setHTTPMethod:@"${method}"];`);
1955
- if (req.hasHeaders) {
1956
- push("[request setAllHTTPHeaderFields:headers];");
1957
- }
1958
- if (req.hasBody) {
1959
- push("[request setHTTPBody:postData];");
1960
- }
1961
- blank();
1962
- push("NSURLSession *session = [NSURLSession sharedSession];");
1963
- push("NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request");
1964
- push(
1965
- " completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {"
1966
- );
1967
- push(" if (error) {", 1);
1968
- push(' NSLog(@"%@", error);', 2);
1969
- push(" } else {", 1);
1970
- push(
1971
- " NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;",
1972
- 2
1973
- );
1974
- push(' NSLog(@"%@", httpResponse);', 2);
1975
- push(" }", 1);
1976
- push(" }];");
1977
- push("[dataTask resume];");
1978
- return join();
1979
- }
1980
- };
1981
-
1982
- // src/targets/objc/target.ts
1983
- var objc = {
1984
- info: {
1985
- key: "objc",
1986
- title: "Objective-C",
1987
- extname: ".m",
1988
- default: "nsurlsession"
1989
- },
1990
- clientsById: {
1991
- nsurlsession
1992
- }
1993
- };
1994
-
1995
- // src/targets/ocaml/cohttp/client.ts
1996
- var cohttp = {
1997
- info: {
1998
- key: "cohttp",
1999
- title: "CoHTTP",
2000
- link: "https://github.com/mirage/ocaml-cohttp",
2001
- description: "Cohttp is a very lightweight HTTP server using Lwt or Async for OCaml"
2002
- },
2003
- convert: ({ fullUrl, allHeaders, postData, method }, options) => {
2004
- const opts = {
2005
- indent: " ",
2006
- ...options
2007
- };
2008
- const methods = ["get", "post", "head", "delete", "patch", "put", "options"];
2009
- const { push, blank, join } = new CodeBuilder({ indent: opts.indent });
2010
- push("open Cohttp_lwt_unix");
2011
- push("open Cohttp");
2012
- push("open Lwt");
2013
- blank();
2014
- push(`let uri = Uri.of_string "${fullUrl}" in`);
2015
- const headers = Object.keys(allHeaders);
2016
- if (headers.length === 1) {
2017
- push(
2018
- `let headers = Header.add (Header.init ()) "${headers[0]}" "${escapeForDoubleQuotes(
2019
- allHeaders[headers[0]]
2020
- )}" in`
2021
- );
2022
- } else if (headers.length > 1) {
2023
- push("let headers = Header.add_list (Header.init ()) [");
2024
- headers.forEach((key) => {
2025
- push(`("${key}", "${escapeForDoubleQuotes(allHeaders[key])}");`, 1);
2026
- });
2027
- push("] in");
2028
- }
2029
- if (postData.text) {
2030
- push(`let body = Cohttp_lwt_body.of_string ${JSON.stringify(postData.text)} in`);
2031
- }
2032
- blank();
2033
- const h = headers.length ? "~headers " : "";
2034
- const b = postData.text ? "~body " : "";
2035
- const m = methods.includes(method.toLowerCase()) ? `\`${method.toUpperCase()}` : `(Code.method_of_string "${method}")`;
2036
- push(`Client.call ${h}${b}${m} uri`);
2037
- push(">>= fun (res, body_stream) ->");
2038
- push("(* Do stuff with the result *)", 1);
2039
- return join();
2040
- }
2041
- };
2042
-
2043
- // src/targets/ocaml/target.ts
2044
- var ocaml = {
2045
- info: {
2046
- key: "ocaml",
2047
- title: "OCaml",
2048
- extname: ".ml",
2049
- default: "cohttp"
2050
- },
2051
- clientsById: {
2052
- cohttp
2053
- }
2054
- };
2055
-
2056
- // src/targets/php/helpers.ts
2057
- var convertType = (obj, indent, lastIndent) => {
2058
- lastIndent = lastIndent || "";
2059
- indent = indent || "";
2060
- switch (Object.prototype.toString.call(obj)) {
2061
- case "[object Boolean]":
2062
- return obj;
2063
- case "[object Null]":
2064
- return "null";
2065
- case "[object Undefined]":
2066
- return "null";
2067
- case "[object String]":
2068
- return `'${escapeString(obj, { delimiter: "'", escapeNewlines: false })}'`;
2069
- case "[object Number]":
2070
- return obj.toString();
2071
- case "[object Array]": {
2072
- const contents = obj.map((item) => convertType(item, `${indent}${indent}`, indent)).join(`,
2073
- ${indent}`);
2074
- return `[
2075
- ${indent}${contents}
2076
- ${lastIndent}]`;
2077
- }
2078
- case "[object Object]": {
2079
- const result = [];
2080
- for (const i in obj) {
2081
- if (Object.prototype.hasOwnProperty.call(obj, i)) {
2082
- result.push(`${convertType(i, indent)} => ${convertType(obj[i], `${indent}${indent}`, indent)}`);
2083
- }
2084
- }
2085
- return `[
2086
- ${indent}${result.join(`,
2087
- ${indent}`)}
2088
- ${lastIndent}]`;
2089
- }
2090
- default:
2091
- return "null";
2092
- }
2093
- };
2094
- var supportedMethods = [
2095
- "ACL",
2096
- "BASELINE_CONTROL",
2097
- "CHECKIN",
2098
- "CHECKOUT",
2099
- "CONNECT",
2100
- "COPY",
2101
- "DELETE",
2102
- "GET",
2103
- "HEAD",
2104
- "LABEL",
2105
- "LOCK",
2106
- "MERGE",
2107
- "MKACTIVITY",
2108
- "MKCOL",
2109
- "MKWORKSPACE",
2110
- "MOVE",
2111
- "OPTIONS",
2112
- "POST",
2113
- "PROPFIND",
2114
- "PROPPATCH",
2115
- "PUT",
2116
- "REPORT",
2117
- "TRACE",
2118
- "UNCHECKOUT",
2119
- "UNLOCK",
2120
- "UPDATE",
2121
- "VERSION_CONTROL"
2122
- ];
2123
-
2124
- // src/targets/php/curl/client.ts
2125
- var curl = {
2126
- info: {
2127
- key: "curl",
2128
- title: "cURL",
2129
- link: "http://php.net/manual/en/book.curl.php",
2130
- description: "PHP with ext-curl"
2131
- },
2132
- convert: ({ uriObj, postData, fullUrl, method, httpVersion, cookies, headersObj }, options = {}) => {
2133
- const {
2134
- closingTag = false,
2135
- indent = " ",
2136
- maxRedirects = 10,
2137
- namedErrors = false,
2138
- noTags = false,
2139
- shortTags = false,
2140
- timeout = 30
2141
- } = options;
2142
- const { push, blank, join } = new CodeBuilder({ indent });
2143
- if (!noTags) {
2144
- push(shortTags ? "<?" : "<?php");
2145
- blank();
2146
- }
2147
- push("$curl = curl_init();");
2148
- blank();
2149
- const curlOptions = [
2150
- {
2151
- escape: true,
2152
- name: "CURLOPT_PORT",
2153
- value: uriObj.port
2154
- },
2155
- {
2156
- escape: true,
2157
- name: "CURLOPT_URL",
2158
- value: fullUrl
2159
- },
2160
- {
2161
- escape: false,
2162
- name: "CURLOPT_RETURNTRANSFER",
2163
- value: "true"
2164
- },
2165
- {
2166
- escape: true,
2167
- name: "CURLOPT_ENCODING",
2168
- value: ""
2169
- },
2170
- {
2171
- escape: false,
2172
- name: "CURLOPT_MAXREDIRS",
2173
- value: maxRedirects
2174
- },
2175
- {
2176
- escape: false,
2177
- name: "CURLOPT_TIMEOUT",
2178
- value: timeout
2179
- },
2180
- {
2181
- escape: false,
2182
- name: "CURLOPT_HTTP_VERSION",
2183
- value: httpVersion === "HTTP/1.0" ? "CURL_HTTP_VERSION_1_0" : "CURL_HTTP_VERSION_1_1"
2184
- },
2185
- {
2186
- escape: true,
2187
- name: "CURLOPT_CUSTOMREQUEST",
2188
- value: method
2189
- },
2190
- {
2191
- escape: !postData.jsonObj,
2192
- name: "CURLOPT_POSTFIELDS",
2193
- value: postData ? postData.jsonObj ? `json_encode(${convertType(postData.jsonObj, indent.repeat(2), indent)})` : postData.text : void 0
2194
- }
2195
- ];
2196
- push("curl_setopt_array($curl, [");
2197
- const curlopts = new CodeBuilder({ indent, join: `
2198
- ${indent}` });
2199
- curlOptions.forEach(({ value, name, escape: escape2 }) => {
2200
- if (value !== null && value !== void 0) {
2201
- curlopts.push(`${name} => ${escape2 ? JSON.stringify(value) : value},`);
2202
- }
2203
- });
2204
- const curlCookies = cookies.map((cookie) => `${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`);
2205
- if (curlCookies.length) {
2206
- curlopts.push(`CURLOPT_COOKIE => "${curlCookies.join("; ")}",`);
2207
- }
2208
- const headers = Object.keys(headersObj).sort().map((key) => `"${key}: ${escapeForDoubleQuotes(headersObj[key])}"`);
2209
- if (headers.length) {
2210
- curlopts.push("CURLOPT_HTTPHEADER => [");
2211
- curlopts.push(headers.join(`,
2212
- ${indent}${indent}`), 1);
2213
- curlopts.push("],");
2214
- }
2215
- push(curlopts.join(), 1);
2216
- push("]);");
2217
- blank();
2218
- push("$response = curl_exec($curl);");
2219
- push("$err = curl_error($curl);");
2220
- blank();
2221
- push("curl_close($curl);");
2222
- blank();
2223
- push("if ($err) {");
2224
- if (namedErrors) {
2225
- push('echo array_flip(get_defined_constants(true)["curl"])[$err];', 1);
2226
- } else {
2227
- push('echo "cURL Error #:" . $err;', 1);
2228
- }
2229
- push("} else {");
2230
- push("echo $response;", 1);
2231
- push("}");
2232
- if (!noTags && closingTag) {
2233
- blank();
2234
- push("?>");
2235
- }
2236
- return join();
2237
- }
2238
- };
2239
-
2240
- // src/targets/php/guzzle/client.ts
2241
- var guzzle = {
2242
- info: {
2243
- key: "guzzle",
2244
- title: "Guzzle",
2245
- link: "http://docs.guzzlephp.org/en/stable/",
2246
- description: "PHP with Guzzle"
2247
- },
2248
- convert: ({ postData, fullUrl, method, cookies, headersObj }, options) => {
2249
- const opts = {
2250
- closingTag: false,
2251
- indent: " ",
2252
- noTags: false,
2253
- shortTags: false,
2254
- ...options
2255
- };
2256
- const { push, blank, join } = new CodeBuilder({ indent: opts.indent });
2257
- const { code: requestCode, push: requestPush, join: requestJoin } = new CodeBuilder({ indent: opts.indent });
2258
- if (!opts.noTags) {
2259
- push(opts.shortTags ? "<?" : "<?php");
2260
- }
2261
- push("require_once('vendor/autoload.php');");
2262
- blank();
2263
- switch (postData.mimeType) {
2264
- case "application/x-www-form-urlencoded":
2265
- requestPush(`'form_params' => ${convertType(postData.paramsObj, opts.indent + opts.indent, opts.indent)},`, 1);
2266
- break;
2267
- case "multipart/form-data": {
2268
- const fields = [];
2269
- if (postData.params) {
2270
- postData.params.forEach((param) => {
2271
- if (param.fileName) {
2272
- const field = {
2273
- name: param.name,
2274
- filename: param.fileName,
2275
- contents: param.value
2276
- };
2277
- if (param.contentType) {
2278
- field.headers = { "Content-Type": param.contentType };
2279
- }
2280
- fields.push(field);
2281
- } else if (param.value) {
2282
- fields.push({
2283
- name: param.name,
2284
- contents: param.value
2285
- });
2286
- }
2287
- });
2288
- }
2289
- if (fields.length) {
2290
- requestPush(`'multipart' => ${convertType(fields, opts.indent + opts.indent, opts.indent)}`, 1);
2291
- if (hasHeader(headersObj, "content-type")) {
2292
- if (getHeader2(headersObj, "content-type")?.indexOf("boundary")) {
2293
- const headerName = getHeaderName(headersObj, "content-type");
2294
- if (headerName) {
2295
- delete headersObj[headerName];
2296
- }
2297
- }
2298
- }
2299
- }
2300
- break;
2301
- }
2302
- default:
2303
- if (postData.text) {
2304
- requestPush(`'body' => ${convertType(postData.text)},`, 1);
2305
- }
2306
- }
2307
- const headers = Object.keys(headersObj).sort().map(function(key) {
2308
- return `${opts.indent}${opts.indent}'${key}' => '${escapeForSingleQuotes(headersObj[key])}',`;
2309
- });
2310
- const cookieString = cookies.map((cookie) => `${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`).join("; ");
2311
- if (cookieString.length) {
2312
- headers.push(`${opts.indent}${opts.indent}'cookie' => '${escapeForSingleQuotes(cookieString)}',`);
2313
- }
2314
- if (headers.length) {
2315
- requestPush("'headers' => [", 1);
2316
- requestPush(headers.join("\n"));
2317
- requestPush("],", 1);
2318
- }
2319
- push("$client = new \\GuzzleHttp\\Client();");
2320
- blank();
2321
- if (requestCode.length) {
2322
- push(`$response = $client->request('${method}', '${fullUrl}', [`);
2323
- push(requestJoin());
2324
- push("]);");
2325
- } else {
2326
- push(`$response = $client->request('${method}', '${fullUrl}');`);
2327
- }
2328
- blank();
2329
- push("echo $response->getBody();");
2330
- if (!opts.noTags && opts.closingTag) {
2331
- blank();
2332
- push("?>");
2333
- }
2334
- return join();
2335
- }
2336
- };
2337
-
2338
- // src/targets/php/http1/client.ts
2339
- var http1 = {
2340
- info: {
2341
- key: "http1",
2342
- title: "HTTP v1",
2343
- link: "http://php.net/manual/en/book.http.php",
2344
- description: "PHP with pecl/http v1"
2345
- },
2346
- convert: ({ method, url, postData, queryObj, headersObj, cookiesObj }, options = {}) => {
2347
- const { closingTag = false, indent = " ", noTags = false, shortTags = false } = options;
2348
- const { push, blank, join } = new CodeBuilder({ indent });
2349
- if (!noTags) {
2350
- push(shortTags ? "<?" : "<?php");
2351
- blank();
2352
- }
2353
- if (!supportedMethods.includes(method.toUpperCase())) {
2354
- push(`HttpRequest::methodRegister('${method}');`);
2355
- }
2356
- push("$request = new HttpRequest();");
2357
- push(`$request->setUrl(${convertType(url)});`);
2358
- if (supportedMethods.includes(method.toUpperCase())) {
2359
- push(`$request->setMethod(HTTP_METH_${method.toUpperCase()});`);
2360
- } else {
2361
- push(`$request->setMethod(HttpRequest::HTTP_METH_${method.toUpperCase()});`);
2362
- }
2363
- blank();
2364
- if (Object.keys(queryObj).length) {
2365
- push(`$request->setQueryData(${convertType(queryObj, indent)});`);
2366
- blank();
2367
- }
2368
- if (Object.keys(headersObj).length) {
2369
- push(`$request->setHeaders(${convertType(headersObj, indent)});`);
2370
- blank();
2371
- }
2372
- if (Object.keys(cookiesObj).length) {
2373
- push(`$request->setCookies(${convertType(cookiesObj, indent)});`);
2374
- blank();
2375
- }
2376
- switch (postData.mimeType) {
2377
- case "application/x-www-form-urlencoded":
2378
- push(`$request->setContentType(${convertType(postData.mimeType)});`);
2379
- push(`$request->setPostFields(${convertType(postData.paramsObj, indent)});`);
2380
- blank();
2381
- break;
2382
- case "application/json":
2383
- push(`$request->setContentType(${convertType(postData.mimeType)});`);
2384
- push(`$request->setBody(json_encode(${convertType(postData.jsonObj, indent)}));`);
2385
- blank();
2386
- break;
2387
- default:
2388
- if (postData.text) {
2389
- push(`$request->setBody(${convertType(postData.text)});`);
2390
- blank();
2391
- }
2392
- }
2393
- push("try {");
2394
- push("$response = $request->send();", 1);
2395
- blank();
2396
- push("echo $response->getBody();", 1);
2397
- push("} catch (HttpException $ex) {");
2398
- push("echo $ex;", 1);
2399
- push("}");
2400
- if (!noTags && closingTag) {
2401
- blank();
2402
- push("?>");
2403
- }
2404
- return join();
2405
- }
2406
- };
2407
-
2408
- // src/targets/php/http2/client.ts
2409
- var http2 = {
2410
- info: {
2411
- key: "http2",
2412
- title: "HTTP v2",
2413
- link: "http://devel-m6w6.rhcloud.com/mdref/http",
2414
- description: "PHP with pecl/http v2"
2415
- },
2416
- convert: ({ postData, headersObj, method, queryObj, cookiesObj, url }, options = {}) => {
2417
- const { closingTag = false, indent = " ", noTags = false, shortTags = false } = options;
2418
- const { push, blank, join } = new CodeBuilder({ indent });
2419
- let hasBody = false;
2420
- if (!noTags) {
2421
- push(shortTags ? "<?" : "<?php");
2422
- blank();
2423
- }
2424
- push("$client = new http\\Client;");
2425
- push("$request = new http\\Client\\Request;");
2426
- blank();
2427
- switch (postData.mimeType) {
2428
- case "application/x-www-form-urlencoded":
2429
- push("$body = new http\\Message\\Body;");
2430
- push(`$body->append(new http\\QueryString(${convertType(postData.paramsObj, indent)}));`);
2431
- blank();
2432
- hasBody = true;
2433
- break;
2434
- case "multipart/form-data": {
2435
- if (!postData.params) {
2436
- break;
2437
- }
2438
- const files = [];
2439
- const fields = {};
2440
- postData.params.forEach(({ name, fileName, value, contentType }) => {
2441
- if (fileName) {
2442
- files.push({
2443
- name,
2444
- type: contentType,
2445
- file: fileName,
2446
- data: value
2447
- });
2448
- return;
2449
- }
2450
- if (value) {
2451
- fields[name] = value;
2452
- }
2453
- });
2454
- const field = Object.keys(fields).length ? convertType(fields, indent) : "null";
2455
- const formValue = files.length ? convertType(files, indent) : "null";
2456
- push("$body = new http\\Message\\Body;");
2457
- push(`$body->addForm(${field}, ${formValue});`);
2458
- if (hasHeader(headersObj, "content-type")) {
2459
- if (getHeader2(headersObj, "content-type")?.indexOf("boundary")) {
2460
- const headerName = getHeaderName(headersObj, "content-type");
2461
- if (headerName) {
2462
- delete headersObj[headerName];
2463
- }
2464
- }
2465
- }
2466
- blank();
2467
- hasBody = true;
2468
- break;
2469
- }
2470
- case "application/json":
2471
- push("$body = new http\\Message\\Body;");
2472
- push(`$body->append(json_encode(${convertType(postData.jsonObj, indent)}));`);
2473
- hasBody = true;
2474
- break;
2475
- default:
2476
- if (postData.text) {
2477
- push("$body = new http\\Message\\Body;");
2478
- push(`$body->append(${convertType(postData.text)});`);
2479
- blank();
2480
- hasBody = true;
2481
- }
2482
- }
2483
- push(`$request->setRequestUrl(${convertType(url)});`);
2484
- push(`$request->setRequestMethod(${convertType(method)});`);
2485
- if (hasBody) {
2486
- push("$request->setBody($body);");
2487
- blank();
2488
- }
2489
- if (Object.keys(queryObj).length) {
2490
- push(`$request->setQuery(new http\\QueryString(${convertType(queryObj, indent)}));`);
2491
- blank();
2492
- }
2493
- if (Object.keys(headersObj).length) {
2494
- push(`$request->setHeaders(${convertType(headersObj, indent)});`);
2495
- blank();
2496
- }
2497
- if (Object.keys(cookiesObj).length) {
2498
- blank();
2499
- push(`$client->setCookies(${convertType(cookiesObj, indent)});`);
2500
- blank();
2501
- }
2502
- push("$client->enqueue($request)->send();");
2503
- push("$response = $client->getResponse();");
2504
- blank();
2505
- push("echo $response->getBody();");
2506
- if (!noTags && closingTag) {
2507
- blank();
2508
- push("?>");
2509
- }
2510
- return join();
2511
- }
2512
- };
2513
-
2514
- // src/targets/php/target.ts
2515
- var php = {
2516
- info: {
2517
- key: "php",
2518
- title: "PHP",
2519
- extname: ".php",
2520
- default: "curl",
2521
- cli: "php %s"
2522
- },
2523
- clientsById: {
2524
- curl,
2525
- guzzle,
2526
- http1,
2527
- http2
2528
- }
2529
- };
2530
-
2531
- // src/targets/powershell/common.ts
2532
- var generatePowershellConvert = (command) => {
2533
- const convert = ({ method, headersObj, cookies, uriObj, fullUrl, postData, allHeaders }) => {
2534
- const { push, join } = new CodeBuilder();
2535
- const methods = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"];
2536
- if (!methods.includes(method.toUpperCase())) {
2537
- return "Method not supported";
2538
- }
2539
- const commandOptions = [];
2540
- const headers = Object.keys(headersObj);
2541
- if (headers.length) {
2542
- push("$headers=@{}");
2543
- headers.forEach((key) => {
2544
- if (key !== "connection") {
2545
- push(`$headers.Add("${key}", "${escapeString(headersObj[key], { escapeChar: "`" })}")`);
2546
- }
2547
- });
2548
- commandOptions.push("-Headers $headers");
2549
- }
2550
- if (cookies.length) {
2551
- push("$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession");
2552
- cookies.forEach((cookie) => {
2553
- push("$cookie = New-Object System.Net.Cookie");
2554
- push(`$cookie.Name = '${cookie.name}'`);
2555
- push(`$cookie.Value = '${cookie.value}'`);
2556
- push(`$cookie.Domain = '${uriObj.host}'`);
2557
- push("$session.Cookies.Add($cookie)");
2558
- });
2559
- commandOptions.push("-WebSession $session");
2560
- }
2561
- if (postData.text) {
2562
- commandOptions.push(
2563
- `-ContentType '${escapeString(getHeader2(allHeaders, "content-type"), { delimiter: "'", escapeChar: "`" })}'`
2564
- );
2565
- commandOptions.push(`-Body '${postData.text}'`);
2566
- }
2567
- push(`$response = ${command} -Uri '${fullUrl}' -Method ${method} ${commandOptions.join(" ")}`.trim());
2568
- return join();
2569
- };
2570
- return convert;
2571
- };
2572
-
2573
- // src/targets/powershell/restmethod/client.ts
2574
- var restmethod = {
2575
- info: {
2576
- key: "restmethod",
2577
- title: "Invoke-RestMethod",
2578
- link: "https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Invoke-RestMethod",
2579
- description: "Powershell Invoke-RestMethod client"
2580
- },
2581
- convert: generatePowershellConvert("Invoke-RestMethod")
2582
- };
2583
-
2584
- // src/targets/powershell/webrequest/client.ts
2585
- var webrequest = {
2586
- info: {
2587
- key: "webrequest",
2588
- title: "Invoke-WebRequest",
2589
- link: "https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Invoke-WebRequest",
2590
- description: "Powershell Invoke-WebRequest client"
2591
- },
2592
- convert: generatePowershellConvert("Invoke-WebRequest")
2593
- };
2594
-
2595
- // src/targets/powershell/target.ts
2596
- var powershell = {
2597
- info: {
2598
- key: "powershell",
2599
- title: "Powershell",
2600
- extname: ".ps1",
2601
- default: "webrequest"
2602
- },
2603
- clientsById: {
2604
- webrequest,
2605
- restmethod
2606
- }
2607
- };
2608
-
2609
- // src/targets/python/helpers.ts
2610
- function concatValues(concatType, values, pretty, indentation, indentLevel) {
2611
- const currentIndent = indentation.repeat(indentLevel);
2612
- const closingBraceIndent = indentation.repeat(indentLevel - 1);
2613
- const join = pretty ? `,
2614
- ${currentIndent}` : ", ";
2615
- const openingBrace = concatType === "object" ? "{" : "[";
2616
- const closingBrace = concatType === "object" ? "}" : "]";
2617
- if (pretty) {
2618
- return `${openingBrace}
2619
- ${currentIndent}${values.join(join)}
2620
- ${closingBraceIndent}${closingBrace}`;
2621
- }
2622
- if (concatType === "object" && values.length > 0) {
2623
- return `${openingBrace} ${values.join(join)} ${closingBrace}`;
2624
- }
2625
- return `${openingBrace}${values.join(join)}${closingBrace}`;
2626
- }
2627
- var literalRepresentation2 = (value, opts, indentLevel) => {
2628
- indentLevel = indentLevel === void 0 ? 1 : indentLevel + 1;
2629
- switch (Object.prototype.toString.call(value)) {
2630
- case "[object Number]":
2631
- return value;
2632
- case "[object Array]": {
2633
- let pretty = false;
2634
- const valuesRepresentation = value.map((v) => {
2635
- if (Object.prototype.toString.call(v) === "[object Object]") {
2636
- pretty = Object.keys(v).length > 1;
2637
- }
2638
- return literalRepresentation2(v, opts, indentLevel);
2639
- });
2640
- return concatValues("array", valuesRepresentation, pretty, opts.indent, indentLevel);
2641
- }
2642
- case "[object Object]": {
2643
- const keyValuePairs = [];
2644
- for (const key in value) {
2645
- keyValuePairs.push(`"${key}": ${literalRepresentation2(value[key], opts, indentLevel)}`);
2646
- }
2647
- return concatValues("object", keyValuePairs, opts.pretty && keyValuePairs.length > 1, opts.indent, indentLevel);
2648
- }
2649
- case "[object Null]":
2650
- return "None";
2651
- case "[object Boolean]":
2652
- return value ? "True" : "False";
2653
- default:
2654
- if (value === null || value === void 0) {
2655
- return "";
2656
- }
2657
- return `"${value.toString().replace(/"/g, '\\"')}"`;
2658
- }
2659
- };
2660
-
2661
- // src/targets/python/requests/client.ts
2662
- var builtInMethods = ["HEAD", "GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"];
2663
- var requests = {
2664
- info: {
2665
- key: "requests",
2666
- title: "Requests",
2667
- link: "http://docs.python-requests.org/en/latest/api/#requests.request",
2668
- description: "Requests HTTP library"
2669
- },
2670
- convert: ({ fullUrl, postData, allHeaders, method }, options) => {
2671
- const opts = {
2672
- indent: " ",
2673
- pretty: true,
2674
- ...options
2675
- };
2676
- const { push, blank, join, addPostProcessor } = new CodeBuilder({ indent: opts.indent });
2677
- push("import requests");
2678
- blank();
2679
- push(`url = "${fullUrl}"`);
2680
- blank();
2681
- const headers = allHeaders;
2682
- let payload = {};
2683
- const files = {};
2684
- let hasFiles = false;
2685
- let hasPayload = false;
2686
- let jsonPayload = false;
2687
- switch (postData.mimeType) {
2688
- case "application/json":
2689
- if (postData.jsonObj) {
2690
- push(`payload = ${literalRepresentation2(postData.jsonObj, opts)}`);
2691
- jsonPayload = true;
2692
- hasPayload = true;
2693
- }
2694
- break;
2695
- case "multipart/form-data":
2696
- if (!postData.params) {
2697
- break;
2698
- }
2699
- payload = {};
2700
- postData.params.forEach((p) => {
2701
- if (p.fileName) {
2702
- if (p.contentType) {
2703
- files[p.name] = `('${p.fileName}', open('${p.fileName}', 'rb'), '${p.contentType}')`;
2704
- } else {
2705
- files[p.name] = `('${p.fileName}', open('${p.fileName}', 'rb'))`;
2706
- }
2707
- hasFiles = true;
2708
- } else {
2709
- payload[p.name] = p.value;
2710
- hasPayload = true;
2711
- }
2712
- });
2713
- if (hasFiles) {
2714
- push(`files = ${literalRepresentation2(files, opts)}`);
2715
- if (hasPayload) {
2716
- push(`payload = ${literalRepresentation2(payload, opts)}`);
2717
- }
2718
- const headerName = getHeaderName(headers, "content-type");
2719
- if (headerName) {
2720
- delete headers[headerName];
2721
- }
2722
- } else {
2723
- const nonFilePayload = JSON.stringify(postData.text);
2724
- if (nonFilePayload) {
2725
- push(`payload = ${nonFilePayload}`);
2726
- hasPayload = true;
2727
- }
2728
- }
2729
- addPostProcessor(
2730
- (code) => code.replace(/"\('(.+)', open\('(.+)', 'rb'\)\)"/g, '("$1", open("$2", "rb"))').replace(/"\('(.+)', open\('(.+)', 'rb'\), '(.+)'\)"/g, '("$1", open("$2", "rb"), "$3")')
2731
- );
2732
- break;
2733
- default: {
2734
- if (postData.mimeType === "application/x-www-form-urlencoded" && postData.paramsObj) {
2735
- push(`payload = ${literalRepresentation2(postData.paramsObj, opts)}`);
2736
- hasPayload = true;
2737
- break;
2738
- }
2739
- const stringPayload = JSON.stringify(postData.text);
2740
- if (stringPayload) {
2741
- push(`payload = ${stringPayload}`);
2742
- hasPayload = true;
2743
- }
2744
- }
2745
- }
2746
- const headerCount = Object.keys(headers).length;
2747
- if (headerCount === 0 && (hasPayload || hasFiles)) {
2748
- blank();
2749
- } else if (headerCount === 1) {
2750
- Object.keys(headers).forEach((header) => {
2751
- push(`headers = {"${header}": "${escapeForDoubleQuotes(headers[header])}"}`);
2752
- blank();
2753
- });
2754
- } else if (headerCount > 1) {
2755
- let count = 1;
2756
- push("headers = {");
2757
- Object.keys(headers).forEach((header) => {
2758
- if (count !== headerCount) {
2759
- push(`"${header}": "${escapeForDoubleQuotes(headers[header])}",`, 1);
2760
- } else {
2761
- push(`"${header}": "${escapeForDoubleQuotes(headers[header])}"`, 1);
2762
- }
2763
- count += 1;
2764
- });
2765
- push("}");
2766
- blank();
2767
- }
2768
- let request2 = builtInMethods.includes(method) ? `response = requests.${method.toLowerCase()}(url` : `response = requests.request("${method}", url`;
2769
- if (hasPayload) {
2770
- if (jsonPayload) {
2771
- request2 += ", json=payload";
2772
- } else {
2773
- request2 += ", data=payload";
2774
- }
2775
- }
2776
- if (hasFiles) {
2777
- request2 += ", files=files";
2778
- }
2779
- if (headerCount > 0) {
2780
- request2 += ", headers=headers";
2781
- }
2782
- request2 += ")";
2783
- push(request2);
2784
- blank();
2785
- push("print(response.text)");
2786
- return join();
2787
- }
2788
- };
2789
-
2790
- // src/targets/python/target.ts
2791
- var python = {
2792
- info: {
2793
- key: "python",
2794
- title: "Python",
2795
- extname: ".py",
2796
- default: "requests",
2797
- cli: "python3 %s"
2798
- },
2799
- clientsById: {
2800
- requests
2801
- }
2802
- };
2803
-
2804
- // src/targets/r/httr/client.ts
2805
- var httr = {
2806
- info: {
2807
- key: "httr",
2808
- title: "httr",
2809
- link: "https://cran.r-project.org/web/packages/httr/vignettes/quickstart.html",
2810
- description: "httr: Tools for Working with URLs and HTTP"
2811
- },
2812
- convert: ({ url, queryObj, queryString, postData, allHeaders, method }) => {
2813
- const { push, blank, join } = new CodeBuilder();
2814
- push("library(httr)");
2815
- blank();
2816
- push(`url <- "${url}"`);
2817
- blank();
2818
- const qs = queryObj;
2819
- delete queryObj.key;
2820
- const queryCount = Object.keys(qs).length;
2821
- if (queryString.length === 1) {
2822
- push(`queryString <- list(${Object.keys(qs)} = "${Object.values(qs).toString()}")`);
2823
- blank();
2824
- } else if (queryString.length > 1) {
2825
- push("queryString <- list(");
2826
- Object.keys(qs).forEach((query, i) => {
2827
- if (i !== queryCount - 1) {
2828
- push(` ${query} = "${qs[query].toString()}",`);
2829
- } else {
2830
- push(` ${query} = "${qs[query].toString()}"`);
2831
- }
2832
- });
2833
- push(")");
2834
- blank();
2835
- }
2836
- const payload = JSON.stringify(postData.text);
2837
- if (payload) {
2838
- push(`payload <- ${payload}`);
2839
- blank();
2840
- }
2841
- if (postData.text || postData.jsonObj || postData.params) {
2842
- switch (postData.mimeType) {
2843
- case "application/x-www-form-urlencoded":
2844
- push('encode <- "form"');
2845
- blank();
2846
- break;
2847
- case "application/json":
2848
- push('encode <- "json"');
2849
- blank();
2850
- break;
2851
- case "multipart/form-data":
2852
- push('encode <- "multipart"');
2853
- blank();
2854
- break;
2855
- default:
2856
- push('encode <- "raw"');
2857
- blank();
2858
- break;
2859
- }
2860
- }
2861
- const cookieHeader = getHeader2(allHeaders, "cookie");
2862
- const acceptHeader = getHeader2(allHeaders, "accept");
2863
- const setCookies = cookieHeader ? `set_cookies(\`${String(cookieHeader).replace(/;/g, '", `').replace(/` /g, "`").replace(/[=]/g, '` = "')}")` : void 0;
2864
- const setAccept = acceptHeader ? `accept("${escapeForDoubleQuotes(acceptHeader)}")` : void 0;
2865
- const setContentType = `content_type("${escapeForDoubleQuotes(postData.mimeType)}")`;
2866
- const otherHeaders = Object.entries(allHeaders).filter(([key]) => !["cookie", "accept", "content-type"].includes(key.toLowerCase())).map(([key, value]) => `'${key}' = '${escapeForSingleQuotes(value)}'`).join(", ");
2867
- const setHeaders = otherHeaders ? `add_headers(${otherHeaders})` : void 0;
2868
- let request2 = `response <- VERB("${method}", url`;
2869
- if (payload) {
2870
- request2 += ", body = payload";
2871
- }
2872
- if (queryString.length) {
2873
- request2 += ", query = queryString";
2874
- }
2875
- const headerAdditions = [setHeaders, setContentType, setAccept, setCookies].filter((x) => !!x).join(", ");
2876
- if (headerAdditions) {
2877
- request2 += `, ${headerAdditions}`;
2878
- }
2879
- if (postData.text || postData.jsonObj || postData.params) {
2880
- request2 += ", encode = encode";
2881
- }
2882
- request2 += ")";
2883
- push(request2);
2884
- blank();
2885
- push('content(response, "text")');
2886
- return join();
2887
- }
2888
- };
2889
-
2890
- // src/targets/r/target.ts
2891
- var r = {
2892
- info: {
2893
- key: "r",
2894
- title: "R",
2895
- extname: ".r",
2896
- default: "httr"
2897
- },
2898
- clientsById: {
2899
- httr
2900
- }
2901
- };
2902
-
2903
- // src/targets/ruby/native/client.ts
2904
- var native4 = {
2905
- info: {
2906
- key: "native",
2907
- title: "net::http",
2908
- link: "http://ruby-doc.org/stdlib-2.2.1/libdoc/net/http/rdoc/Net/HTTP.html",
2909
- description: "Ruby HTTP client"
2910
- },
2911
- convert: ({ uriObj, method: rawMethod, fullUrl, postData, allHeaders }) => {
2912
- const { push, blank, join } = new CodeBuilder();
2913
- push("require 'uri'");
2914
- push("require 'net/http'");
2915
- blank();
2916
- const method = rawMethod.toUpperCase();
2917
- const methods = [
2918
- "GET",
2919
- "POST",
2920
- "HEAD",
2921
- "DELETE",
2922
- "PATCH",
2923
- "PUT",
2924
- "OPTIONS",
2925
- "COPY",
2926
- "LOCK",
2927
- "UNLOCK",
2928
- "MOVE",
2929
- "TRACE"
2930
- ];
2931
- const capMethod = method.charAt(0) + method.substring(1).toLowerCase();
2932
- if (!methods.includes(method)) {
2933
- push(`class Net::HTTP::${capMethod} < Net::HTTPRequest`);
2934
- push(` METHOD = '${method.toUpperCase()}'`);
2935
- push(` REQUEST_HAS_BODY = '${postData.text ? "true" : "false"}'`);
2936
- push(" RESPONSE_HAS_BODY = true");
2937
- push("end");
2938
- blank();
2939
- }
2940
- push(`url = URI("${fullUrl}")`);
2941
- blank();
2942
- push("http = Net::HTTP.new(url.host, url.port)");
2943
- if (uriObj.protocol === "https:") {
2944
- push("http.use_ssl = true");
2945
- }
2946
- blank();
2947
- push(`request = Net::HTTP::${capMethod}.new(url)`);
2948
- const headers = Object.keys(allHeaders);
2949
- if (headers.length) {
2950
- headers.forEach((key) => {
2951
- push(`request["${key}"] = '${escapeForSingleQuotes(allHeaders[key])}'`);
2952
- });
2953
- }
2954
- if (postData.text) {
2955
- push(`request.body = ${JSON.stringify(postData.text)}`);
2956
- }
2957
- blank();
2958
- push("response = http.request(request)");
2959
- push("puts response.read_body");
2960
- return join();
2961
- }
2962
- };
2963
-
2964
- // src/targets/ruby/target.ts
2965
- var ruby = {
2966
- info: {
2967
- key: "ruby",
2968
- title: "Ruby",
2969
- extname: ".rb",
2970
- default: "native"
2971
- },
2972
- clientsById: {
2973
- native: native4
2974
- }
2975
- };
2976
-
2977
- // src/helpers/shell.ts
2978
- var quote = (value = "") => {
2979
- const safe = /^[a-z0-9-_/.@%^=:]+$/i;
2980
- const isShellSafe = safe.test(value);
2981
- if (isShellSafe) {
2982
- return value;
2983
- }
2984
- return `'${value.replace(/'/g, "'\\''")}'`;
2985
- };
2986
- var escape = (value) => value.replace(/\r/g, "\\r").replace(/\n/g, "\\n");
2987
-
2988
- // src/targets/shell/curl/client.ts
2989
- var params = {
2990
- "http1.0": "0",
2991
- "url ": "",
2992
- cookie: "b",
2993
- data: "d",
2994
- form: "F",
2995
- globoff: "g",
2996
- header: "H",
2997
- insecure: "k",
2998
- request: "X"
2999
- };
3000
- var getArg = (short) => (longName) => {
3001
- if (short) {
3002
- const shortName = params[longName];
3003
- if (!shortName) {
3004
- return "";
3005
- }
3006
- return `-${shortName}`;
3007
- }
3008
- return `--${longName}`;
3009
- };
3010
- var curl2 = {
3011
- info: {
3012
- key: "curl",
3013
- title: "cURL",
3014
- link: "http://curl.haxx.se/",
3015
- description: "cURL is a command line tool and library for transferring data with URL syntax"
3016
- },
3017
- convert: ({ fullUrl, method, httpVersion, headersObj, allHeaders, postData }, options = {}) => {
3018
- const { indent = " ", short = false, binary = false, globOff = false } = options;
3019
- const indentJSON = " ";
3020
- const { push, join } = new CodeBuilder({
3021
- ...typeof indent === "string" ? { indent } : {},
3022
- join: indent !== false ? ` \\
3023
- ${indent}` : " "
3024
- });
3025
- const arg = getArg(short);
3026
- let formattedUrl = quote(fullUrl);
3027
- push(`curl ${arg("request")} ${method}`);
3028
- if (globOff) {
3029
- formattedUrl = unescape(formattedUrl);
3030
- push(arg("globoff"));
3031
- }
3032
- push(`${arg("url ")}${formattedUrl}`);
3033
- if (httpVersion === "HTTP/1.0") {
3034
- push(arg("http1.0"));
3035
- }
3036
- if (getHeader2(allHeaders, "accept-encoding")) {
3037
- push("--compressed");
3038
- }
3039
- if (postData.mimeType === "multipart/form-data") {
3040
- const contentTypeHeaderName = getHeaderName(headersObj, "content-type");
3041
- if (contentTypeHeaderName) {
3042
- const contentTypeHeader = headersObj[contentTypeHeaderName];
3043
- if (contentTypeHeaderName && contentTypeHeader) {
3044
- const noBoundary = String(contentTypeHeader).replace(/; boundary.+?(?=(;|$))/, "");
3045
- headersObj[contentTypeHeaderName] = noBoundary;
3046
- allHeaders[contentTypeHeaderName] = noBoundary;
3047
- }
3048
- }
3049
- }
3050
- Object.keys(headersObj).sort().forEach((key) => {
3051
- const header = `${key}: ${headersObj[key]}`;
3052
- push(`${arg("header")} ${quote(header)}`);
3053
- });
3054
- if (allHeaders.cookie) {
3055
- push(`${arg("cookie")} ${quote(allHeaders.cookie)}`);
3056
- }
3057
- switch (postData.mimeType) {
3058
- case "multipart/form-data":
3059
- postData.params?.forEach((param) => {
3060
- let post = "";
3061
- if (param.fileName) {
3062
- post = `${param.name}=@${param.fileName}`;
3063
- } else {
3064
- post = `${param.name}=${param.value}`;
3065
- }
3066
- push(`${arg("form")} ${quote(post)}`);
3067
- });
3068
- break;
3069
- case "application/x-www-form-urlencoded":
3070
- if (postData.params) {
3071
- postData.params.forEach((param) => {
3072
- const unencoded = param.name;
3073
- const encoded = encodeURIComponent(param.name);
3074
- const needsEncoding = encoded !== unencoded;
3075
- const name = needsEncoding ? encoded : unencoded;
3076
- const flag = binary ? "--data-binary" : `--data${needsEncoding ? "-urlencode" : ""}`;
3077
- push(`${flag} ${quote(`${name}=${param.value}`)}`);
3078
- });
3079
- } else {
3080
- push(`${binary ? "--data-binary" : arg("data")} ${quote(postData.text)}`);
3081
- }
3082
- break;
3083
- default:
3084
- if (!postData.text) {
3085
- break;
3086
- }
3087
- let builtPayload = false;
3088
- if (isMimeTypeJSON(postData.mimeType)) {
3089
- if (postData.text.length > 20) {
3090
- try {
3091
- const jsonPayload = JSON.parse(postData.text);
3092
- builtPayload = true;
3093
- if (postData.text.indexOf("'") > 0) {
3094
- push(
3095
- `${binary ? "--data-binary" : arg("data")} @- <<EOF
3096
- ${JSON.stringify(
3097
- jsonPayload,
3098
- null,
3099
- indentJSON
3100
- )}
3101
- EOF`
3102
- );
3103
- } else {
3104
- push(
3105
- `${binary ? "--data-binary" : arg("data")} '
3106
- ${JSON.stringify(jsonPayload, null, indentJSON)}
3107
- '`
3108
- );
3109
- }
3110
- } catch (err) {
3111
- }
3112
- }
3113
- }
3114
- if (!builtPayload) {
3115
- push(`${binary ? "--data-binary" : arg("data")} ${quote(postData.text)}`);
3116
- }
3117
- }
3118
- return join();
3119
- }
3120
- };
3121
-
3122
- // src/targets/shell/httpie/client.ts
3123
- var httpie = {
3124
- info: {
3125
- key: "httpie",
3126
- title: "HTTPie",
3127
- link: "http://httpie.org/",
3128
- description: "a CLI, cURL-like tool for humans"
3129
- },
3130
- convert: ({ allHeaders, postData, queryObj, fullUrl, method, url }, options) => {
3131
- const opts = {
3132
- body: false,
3133
- cert: false,
3134
- headers: false,
3135
- indent: " ",
3136
- pretty: false,
3137
- print: false,
3138
- queryParams: false,
3139
- short: false,
3140
- style: false,
3141
- timeout: false,
3142
- verbose: false,
3143
- verify: false,
3144
- ...options
3145
- };
3146
- const { push, join, unshift } = new CodeBuilder({
3147
- indent: opts.indent,
3148
- // @ts-expect-error SEEMS LEGIT
3149
- join: opts.indent !== false ? ` \\
3150
- ${opts.indent}` : " "
3151
- });
3152
- let raw = false;
3153
- const flags = [];
3154
- if (opts.headers) {
3155
- flags.push(opts.short ? "-h" : "--headers");
3156
- }
3157
- if (opts.body) {
3158
- flags.push(opts.short ? "-b" : "--body");
3159
- }
3160
- if (opts.verbose) {
3161
- flags.push(opts.short ? "-v" : "--verbose");
3162
- }
3163
- if (opts.print) {
3164
- flags.push(`${opts.short ? "-p" : "--print"}=${opts.print}`);
3165
- }
3166
- if (opts.verify) {
3167
- flags.push(`--verify=${opts.verify}`);
3168
- }
3169
- if (opts.cert) {
3170
- flags.push(`--cert=${opts.cert}`);
3171
- }
3172
- if (opts.pretty) {
3173
- flags.push(`--pretty=${opts.pretty}`);
3174
- }
3175
- if (opts.style) {
3176
- flags.push(`--style=${opts.style}`);
3177
- }
3178
- if (opts.timeout) {
3179
- flags.push(`--timeout=${opts.timeout}`);
3180
- }
3181
- if (opts.queryParams) {
3182
- Object.keys(queryObj).forEach((name) => {
3183
- const value = queryObj[name];
3184
- if (Array.isArray(value)) {
3185
- value.forEach((val) => {
3186
- push(`${name}==${quote(val)}`);
3187
- });
3188
- } else {
3189
- push(`${name}==${quote(value)}`);
3190
- }
3191
- });
3192
- }
3193
- Object.keys(allHeaders).sort().forEach((key) => {
3194
- push(`${key}:${quote(allHeaders[key])}`);
3195
- });
3196
- if (postData.mimeType === "application/x-www-form-urlencoded") {
3197
- if (postData.params && postData.params.length) {
3198
- flags.push(opts.short ? "-f" : "--form");
3199
- postData.params.forEach((param) => {
3200
- push(`${param.name}=${quote(param.value)}`);
3201
- });
3202
- }
3203
- } else {
3204
- raw = true;
3205
- }
3206
- const cliFlags = flags.length ? `${flags.join(" ")} ` : "";
3207
- url = quote(opts.queryParams ? url : fullUrl);
3208
- unshift(`http ${cliFlags}${method} ${url}`);
3209
- if (raw && postData.text) {
3210
- const postDataText = quote(postData.text);
3211
- unshift(`echo ${postDataText} | `);
3212
- }
3213
- return join();
3214
- }
3215
- };
3216
-
3217
- // src/targets/shell/wget/client.ts
3218
- var wget = {
3219
- info: {
3220
- key: "wget",
3221
- title: "Wget",
3222
- link: "https://www.gnu.org/software/wget/",
3223
- description: "a free software package for retrieving files using HTTP, HTTPS"
3224
- },
3225
- convert: ({ method, postData, allHeaders, fullUrl }, options) => {
3226
- const opts = {
3227
- indent: " ",
3228
- short: false,
3229
- verbose: false,
3230
- ...options
3231
- };
3232
- const { push, join } = new CodeBuilder({
3233
- ...typeof opts.indent === "string" ? { indent: opts.indent } : {},
3234
- join: opts.indent !== false ? ` \\
3235
- ${opts.indent}` : " "
3236
- });
3237
- if (opts.verbose) {
3238
- push(`wget ${opts.short ? "-v" : "--verbose"}`);
3239
- } else {
3240
- push(`wget ${opts.short ? "-q" : "--quiet"}`);
3241
- }
3242
- push(`--method ${quote(method)}`);
3243
- Object.keys(allHeaders).forEach((key) => {
3244
- const header = `${key}: ${allHeaders[key]}`;
3245
- push(`--header ${quote(header)}`);
3246
- });
3247
- if (postData.text) {
3248
- push(`--body-data ${escape(quote(postData.text))}`);
3249
- }
3250
- push(opts.short ? "-O" : "--output-document");
3251
- push(`- ${quote(fullUrl)}`);
3252
- return join();
3253
- }
3254
- };
3255
-
3256
- // src/targets/shell/target.ts
3257
- var shell = {
3258
- info: {
3259
- key: "shell",
3260
- title: "Shell",
3261
- extname: ".sh",
3262
- default: "curl",
3263
- cli: "%s"
3264
- },
3265
- clientsById: {
3266
- curl: curl2,
3267
- httpie,
3268
- wget
3269
- }
3270
- };
3271
-
3272
- // src/targets/swift/helpers.ts
3273
- var buildString = (length, str) => str.repeat(length);
3274
- var concatArray = (arr, pretty, indentation, indentLevel) => {
3275
- const currentIndent = buildString(indentLevel, indentation);
3276
- const closingBraceIndent = buildString(indentLevel - 1, indentation);
3277
- const join = pretty ? `,
3278
- ${currentIndent}` : ", ";
3279
- if (pretty) {
3280
- return `[
3281
- ${currentIndent}${arr.join(join)}
3282
- ${closingBraceIndent}]`;
3283
- }
3284
- return `[${arr.join(join)}]`;
3285
- };
3286
- var literalDeclaration = (name, parameters, opts) => `let ${name} = ${literalRepresentation3(parameters, opts)}`;
3287
- var literalRepresentation3 = (value, opts, indentLevel) => {
3288
- indentLevel = indentLevel === void 0 ? 1 : indentLevel + 1;
3289
- switch (Object.prototype.toString.call(value)) {
3290
- case "[object Number]":
3291
- return value;
3292
- case "[object Array]": {
3293
- let pretty = false;
3294
- const valuesRepresentation = value.map((v) => {
3295
- if (Object.prototype.toString.call(v) === "[object Object]") {
3296
- pretty = Object.keys(v).length > 1;
3297
- }
3298
- return literalRepresentation3(v, opts, indentLevel);
3299
- });
3300
- return concatArray(valuesRepresentation, pretty, opts.indent, indentLevel);
3301
- }
3302
- case "[object Object]": {
3303
- const keyValuePairs = [];
3304
- for (const key in value) {
3305
- keyValuePairs.push(`"${key}": ${literalRepresentation3(value[key], opts, indentLevel)}`);
3306
- }
3307
- return concatArray(
3308
- keyValuePairs,
3309
- // @ts-expect-error needs better types
3310
- opts.pretty && keyValuePairs.length > 1,
3311
- // @ts-expect-error needs better types
3312
- opts.indent,
3313
- indentLevel
3314
- );
3315
- }
3316
- case "[object Boolean]":
3317
- return value.toString();
3318
- default:
3319
- if (value === null || value === void 0) {
3320
- return "";
3321
- }
3322
- return `"${value.toString().replace(/"/g, '\\"')}"`;
3323
- }
3324
- };
3325
-
3326
- // src/targets/swift/nsurlsession/client.ts
3327
- var nsurlsession2 = {
3328
- info: {
3329
- key: "nsurlsession",
3330
- title: "NSURLSession",
3331
- link: "https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSession_class/index.html",
3332
- description: "Foundation's NSURLSession request"
3333
- },
3334
- convert: ({ allHeaders, postData, fullUrl, method }, options) => {
3335
- const opts = {
3336
- indent: " ",
3337
- pretty: true,
3338
- timeout: "10",
3339
- ...options
3340
- };
3341
- const { push, blank, join } = new CodeBuilder({ indent: opts.indent });
3342
- const req = {
3343
- hasHeaders: false,
3344
- hasBody: false
3345
- };
3346
- push("import Foundation");
3347
- if (Object.keys(allHeaders).length) {
3348
- req.hasHeaders = true;
3349
- blank();
3350
- push(literalDeclaration("headers", allHeaders, opts));
3351
- }
3352
- if (postData.text || postData.jsonObj || postData.params) {
3353
- req.hasBody = true;
3354
- switch (postData.mimeType) {
3355
- case "application/x-www-form-urlencoded":
3356
- blank();
3357
- if (postData.params?.length) {
3358
- const [head, ...tail] = postData.params;
3359
- push(`let postData = NSMutableData(data: "${head.name}=${head.value}".data(using: String.Encoding.utf8)!)`);
3360
- tail.forEach(({ name, value }) => {
3361
- push(`postData.append("&${name}=${value}".data(using: String.Encoding.utf8)!)`);
3362
- });
3363
- } else {
3364
- req.hasBody = false;
3365
- }
3366
- break;
3367
- case "application/json":
3368
- if (postData.jsonObj) {
3369
- push(`${literalDeclaration("parameters", postData.jsonObj, opts)} as [String : Any]`);
3370
- blank();
3371
- push("let postData = JSONSerialization.data(withJSONObject: parameters, options: [])");
3372
- }
3373
- break;
3374
- case "multipart/form-data":
3375
- push(literalDeclaration("parameters", postData.params, opts));
3376
- blank();
3377
- push(`let boundary = "${postData.boundary}"`);
3378
- blank();
3379
- push('var body = ""');
3380
- push("var error: NSError? = nil");
3381
- push("for param in parameters {");
3382
- push('let paramName = param["name"]!', 1);
3383
- push('body += "--\\(boundary)\\r\\n"', 1);
3384
- push('body += "Content-Disposition:form-data; name=\\"\\(paramName)\\""', 1);
3385
- push('if let filename = param["fileName"] {', 1);
3386
- push('let contentType = param["content-type"]!', 2);
3387
- push("let fileContent = String(contentsOfFile: filename, encoding: String.Encoding.utf8)", 2);
3388
- push("if (error != nil) {", 2);
3389
- push("print(error as Any)", 3);
3390
- push("}", 2);
3391
- push('body += "; filename=\\"\\(filename)\\"\\r\\n"', 2);
3392
- push('body += "Content-Type: \\(contentType)\\r\\n\\r\\n"', 2);
3393
- push("body += fileContent", 2);
3394
- push('} else if let paramValue = param["value"] {', 1);
3395
- push('body += "\\r\\n\\r\\n\\(paramValue)"', 2);
3396
- push("}", 1);
3397
- push("}");
3398
- break;
3399
- default:
3400
- blank();
3401
- push(`let postData = NSData(data: "${postData.text}".data(using: String.Encoding.utf8)!)`);
3402
- }
3403
- }
3404
- blank();
3405
- push(`let request = NSMutableURLRequest(url: NSURL(string: "${fullUrl}")! as URL,`);
3406
- push(" cachePolicy: .useProtocolCachePolicy,");
3407
- push(
3408
- // @ts-expect-error needs better types
3409
- ` timeoutInterval: ${parseInt(opts.timeout, 10).toFixed(1)})`
3410
- );
3411
- push(`request.httpMethod = "${method}"`);
3412
- if (req.hasHeaders) {
3413
- push("request.allHTTPHeaderFields = headers");
3414
- }
3415
- if (req.hasBody) {
3416
- push("request.httpBody = postData as Data");
3417
- }
3418
- blank();
3419
- push("let session = URLSession.shared");
3420
- push(
3421
- "let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in"
3422
- );
3423
- push("if (error != nil) {", 1);
3424
- push("print(error as Any)", 2);
3425
- push("} else {", 1);
3426
- push("let httpResponse = response as? HTTPURLResponse", 2);
3427
- push("print(httpResponse)", 2);
3428
- push("}", 1);
3429
- push("})");
3430
- blank();
3431
- push("dataTask.resume()");
3432
- return join();
3433
- }
3434
- };
3435
-
3436
- // src/targets/swift/target.ts
3437
- var swift = {
3438
- info: {
3439
- key: "swift",
3440
- title: "Swift",
3441
- extname: ".swift",
3442
- default: "nsurlsession"
3443
- },
3444
- clientsById: {
3445
- nsurlsession: nsurlsession2
3446
- }
3447
- };
3448
-
3449
- // src/targets/index.ts
3450
- var targets = {
3451
- c,
3452
- clojure,
3453
- csharp,
3454
- go,
3455
- http,
3456
- java,
3457
- javascript,
3458
- json,
3459
- kotlin,
3460
- node,
3461
- objc,
3462
- ocaml,
3463
- php,
3464
- powershell,
3465
- python,
3466
- r,
3467
- ruby,
3468
- shell,
3469
- swift
3470
- };
3471
- var isTarget = (target) => {
3472
- if (typeof target !== "object" || target === null || Array.isArray(target)) {
3473
- const got = target === null ? "null" : Array.isArray(target) ? "array" : typeof target;
3474
- throw new Error(`you tried to add a target which is not an object, got type: "${got}"`);
3475
- }
3476
- if (!Object.prototype.hasOwnProperty.call(target, "info")) {
3477
- throw new Error("targets must contain an `info` object");
3478
- }
3479
- if (!Object.prototype.hasOwnProperty.call(target.info, "key")) {
3480
- throw new Error("targets must have an `info` object with the property `key`");
3481
- }
3482
- if (!target.info.key) {
3483
- throw new Error("target key must be a unique string");
3484
- }
3485
- if (Object.prototype.hasOwnProperty.call(targets, target.info.key)) {
3486
- throw new Error(`a target already exists with this key, \`${target.info.key}\``);
3487
- }
3488
- if (!Object.prototype.hasOwnProperty.call(target.info, "title")) {
3489
- throw new Error("targets must have an `info` object with the property `title`");
3490
- }
3491
- if (!target.info.title) {
3492
- throw new Error("target title must be a non-zero-length string");
3493
- }
3494
- if (!Object.prototype.hasOwnProperty.call(target.info, "extname")) {
3495
- throw new Error("targets must have an `info` object with the property `extname`");
3496
- }
3497
- if (!Object.prototype.hasOwnProperty.call(target, "clientsById") || !target.clientsById || Object.keys(target.clientsById).length === 0) {
3498
- throw new Error(
3499
- `No clients provided in target ${target.info.key}. You must provide the property \`clientsById\` containg your clients.`
3500
- );
3501
- }
3502
- if (!Object.prototype.hasOwnProperty.call(target.info, "default")) {
3503
- throw new Error("targets must have an `info` object with the property `default`");
3504
- }
3505
- if (!Object.prototype.hasOwnProperty.call(target.clientsById, target.info.default)) {
3506
- throw new Error(
3507
- `target ${target.info.key} is configured with a default client ${target.info.default}, but no such client was found in the property \`clientsById\` (found ${JSON.stringify(
3508
- Object.keys(target.clientsById)
3509
- )})`
3510
- );
3511
- }
3512
- Object.values(target.clientsById).forEach(isClient);
3513
- return true;
3514
- };
3515
- var addTarget = (target) => {
3516
- if (!isTarget(target)) ;
3517
- targets[target.info.key] = target;
3518
- };
3519
- var isClient = (client) => {
3520
- if (!client) {
3521
- throw new Error("clients must be objects");
3522
- }
3523
- if (!Object.prototype.hasOwnProperty.call(client, "info")) {
3524
- throw new Error("targets client must contain an `info` object");
3525
- }
3526
- if (!Object.prototype.hasOwnProperty.call(client.info, "key")) {
3527
- throw new Error("targets client must have an `info` object with property `key`");
3528
- }
3529
- if (!client.info.key) {
3530
- throw new Error("client.info.key must contain an identifier unique to this target");
3531
- }
3532
- if (!Object.prototype.hasOwnProperty.call(client.info, "title")) {
3533
- throw new Error("targets client must have an `info` object with property `title`");
3534
- }
3535
- if (!Object.prototype.hasOwnProperty.call(client.info, "description")) {
3536
- throw new Error("targets client must have an `info` object with property `description`");
3537
- }
3538
- if (!Object.prototype.hasOwnProperty.call(client.info, "link")) {
3539
- throw new Error("targets client must have an `info` object with property `link`");
3540
- }
3541
- if (!Object.prototype.hasOwnProperty.call(client, "convert") || typeof client.convert !== "function") {
3542
- throw new Error("targets client must have a `convert` property containing a conversion function");
3543
- }
3544
- return true;
3545
- };
3546
- var addTargetClient = (targetId, client) => {
3547
- if (!isClient(client)) ;
3548
- if (!Object.prototype.hasOwnProperty.call(targets, targetId)) {
3549
- throw new Error(`Sorry, but no ${targetId} target exists to add clients to`);
3550
- }
3551
- if (Object.prototype.hasOwnProperty.call(targets[targetId], client.info.key)) {
3552
- throw new Error(
3553
- `the target ${targetId} already has a client with the key ${client.info.key}, please use a different key`
3554
- );
3555
- }
3556
- targets[targetId].clientsById[client.info.key] = client;
3557
- };
1
+ import { reducer } from './chunk-KT7MO6Z4.js';
2
+ import { targets, getHeaderName } from './chunk-IAWYVBVW.js';
3
+ export { addTarget, addTargetClient } from './chunk-IAWYVBVW.js';
4
+ import './chunk-Y7NI4MMY.js';
5
+ import { parse, format } from 'url';
6
+ import formDataToString from 'formdata-to-string';
7
+ import { stringify } from 'qs';
3558
8
 
3559
9
  // src/helpers/utils.ts
3560
10
  var availableTargets = () => Object.keys(targets).map((targetId) => ({
@@ -3563,198 +13,41 @@ var availableTargets = () => Object.keys(targets).map((targetId) => ({
3563
13
  (clientId) => targets[targetId].clientsById[clientId].info
3564
14
  )
3565
15
  }));
3566
- var extname = (targetId) => targets[targetId]?.info.extname || "";
16
+ var extname = (targetId, clientId) => {
17
+ const target = targets[targetId];
18
+ if (!target) {
19
+ return "";
20
+ }
21
+ return target.clientsById[clientId]?.info.extname || "";
22
+ };
3567
23
 
3568
24
  // src/index.ts
3569
- var { map: eventStreamMap } = eventStream__namespace;
3570
25
  var isHarEntry = (value) => typeof value === "object" && "log" in value && typeof value.log === "object" && "entries" in value.log && Array.isArray(value.log.entries);
3571
26
  var HTTPSnippet = class {
3572
27
  constructor(input, opts = {}) {
28
+ this.initCalled = false;
29
+ this.entries = [];
3573
30
  this.requests = [];
3574
- this.prepare = (harRequest, options) => {
3575
- const request2 = {
3576
- ...harRequest,
3577
- fullUrl: "",
3578
- uriObj: {},
3579
- queryObj: {},
3580
- headersObj: {},
3581
- cookiesObj: {},
3582
- allHeaders: {}
3583
- };
3584
- if (request2.queryString && request2.queryString.length) {
3585
- request2.queryObj = request2.queryString.reduce(reducer, {});
3586
- }
3587
- if (request2.headers && request2.headers.length) {
3588
- const http2VersionRegex = /^HTTP\/2/;
3589
- request2.headersObj = request2.headers.reduce((accumulator, { name, value }) => {
3590
- const headerName = http2VersionRegex.exec(request2.httpVersion) ? name.toLocaleLowerCase() : name;
3591
- return {
3592
- ...accumulator,
3593
- [headerName]: value
3594
- };
3595
- }, {});
3596
- }
3597
- if (request2.cookies && request2.cookies.length) {
3598
- request2.cookiesObj = request2.cookies.reduceRight(
3599
- (accumulator, { name, value }) => ({
3600
- ...accumulator,
3601
- [name]: value
3602
- }),
3603
- {}
3604
- );
3605
- }
3606
- const cookies = request2.cookies?.map(({ name, value }) => {
3607
- if (options.harIsAlreadyEncoded) {
3608
- return `${name}=${value}`;
3609
- }
3610
- return `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
3611
- });
3612
- if (cookies?.length) {
3613
- request2.allHeaders.cookie = cookies.join("; ");
3614
- }
3615
- switch (request2.postData.mimeType) {
3616
- case "multipart/mixed":
3617
- case "multipart/related":
3618
- case "multipart/form-data":
3619
- case "multipart/alternative":
3620
- request2.postData.text = "";
3621
- request2.postData.mimeType = "multipart/form-data";
3622
- if (request2.postData?.params) {
3623
- const form = new FormData__default.default();
3624
- const isNativeFormData = typeof form[Symbol.iterator] === "function";
3625
- const boundary = "---011000010111000001101001";
3626
- if (!isNativeFormData) {
3627
- form._boundary = boundary;
3628
- }
3629
- request2.postData?.params.forEach((param) => {
3630
- const name = param.name;
3631
- const value = param.value || "";
3632
- const filename = param.fileName || null;
3633
- if (isNativeFormData) {
3634
- if (isBlob(value)) {
3635
- form.append(name, value, filename);
3636
- } else {
3637
- form.append(name, value);
3638
- }
3639
- } else {
3640
- form.append(name, value, {
3641
- // @ts-expect-error TODO
3642
- filename,
3643
- // @ts-expect-error TODO
3644
- contentType: param.contentType || null
3645
- });
3646
- }
3647
- });
3648
- if (isNativeFormData) {
3649
- for (const data of formDataIterator(form, boundary)) {
3650
- request2.postData.text += data;
3651
- }
3652
- } else {
3653
- form.pipe(
3654
- // @ts-expect-error TODO
3655
- eventStreamMap((data) => {
3656
- request2.postData.text += data;
3657
- })
3658
- );
3659
- }
3660
- request2.postData.boundary = boundary;
3661
- const contentTypeHeader = getHeaderName(request2.headersObj, "content-type") || "content-type";
3662
- request2.headersObj[contentTypeHeader] = `multipart/form-data; boundary=${boundary}`;
3663
- }
3664
- break;
3665
- case "application/x-www-form-urlencoded":
3666
- if (!request2.postData.params) {
3667
- request2.postData.text = "";
3668
- } else {
3669
- request2.postData.paramsObj = request2.postData.params.reduce(reducer, {});
3670
- request2.postData.text = qs.stringify(request2.postData.paramsObj);
3671
- }
3672
- break;
3673
- case "text/json":
3674
- case "text/x-json":
3675
- case "application/json":
3676
- case "application/x-json":
3677
- request2.postData.mimeType = "application/json";
3678
- if (request2.postData.text) {
3679
- try {
3680
- request2.postData.jsonObj = JSON.parse(request2.postData.text);
3681
- } catch (e) {
3682
- request2.postData.mimeType = "text/plain";
3683
- }
3684
- }
3685
- break;
3686
- }
3687
- const allHeaders = {
3688
- ...request2.allHeaders,
3689
- ...request2.headersObj
3690
- };
3691
- const urlWithParsedQuery = url.parse(request2.url, true, true);
3692
- request2.queryObj = {
3693
- ...request2.queryObj,
3694
- ...urlWithParsedQuery.query
3695
- };
3696
- let search;
3697
- if (options.harIsAlreadyEncoded) {
3698
- search = qs.stringify(request2.queryObj, {
3699
- encode: false,
3700
- indices: false
3701
- });
3702
- } else {
3703
- search = qs.stringify(request2.queryObj, {
3704
- indices: false
3705
- });
3706
- }
3707
- const uriObj = {
3708
- ...urlWithParsedQuery,
3709
- query: request2.queryObj,
3710
- search,
3711
- path: search ? `${urlWithParsedQuery.pathname}?${search}` : urlWithParsedQuery.pathname
3712
- };
3713
- const url$1 = url.format({
3714
- ...urlWithParsedQuery,
3715
- query: null,
3716
- search: null
3717
- });
3718
- const fullUrl = url.format({
3719
- ...urlWithParsedQuery,
3720
- ...uriObj
3721
- });
3722
- return {
3723
- ...request2,
3724
- allHeaders,
3725
- fullUrl,
3726
- url: url$1,
3727
- uriObj
3728
- };
3729
- };
3730
- this.convert = (targetId, clientId, options) => {
3731
- if (!options && clientId) {
3732
- options = clientId;
3733
- }
3734
- const target = targets[targetId];
3735
- if (!target) {
3736
- return false;
3737
- }
3738
- const { convert } = target.clientsById[clientId || target.info.default];
3739
- const results = this.requests.map((request2) => convert(request2, options));
3740
- return results.length === 1 ? results[0] : results;
3741
- };
3742
- let entries = [];
3743
- const options = {
31
+ this.options = {};
32
+ this.options = {
3744
33
  harIsAlreadyEncoded: false,
3745
34
  ...opts
3746
35
  };
3747
36
  this.requests = [];
3748
37
  if (isHarEntry(input)) {
3749
- entries = input.log.entries;
38
+ this.entries = input.log.entries;
3750
39
  } else {
3751
- entries = [
40
+ this.entries = [
3752
41
  {
3753
42
  request: input
3754
43
  }
3755
44
  ];
3756
45
  }
3757
- entries.forEach(({ request: request2 }) => {
46
+ }
47
+ async init() {
48
+ this.initCalled = true;
49
+ const promises = [];
50
+ this.entries.forEach(({ request }) => {
3758
51
  const req = {
3759
52
  bodySize: 0,
3760
53
  headersSize: 0,
@@ -3763,49 +56,168 @@ var HTTPSnippet = class {
3763
56
  httpVersion: "HTTP/1.1",
3764
57
  queryString: [],
3765
58
  postData: {
3766
- mimeType: request2.postData?.mimeType || "application/octet-stream"
59
+ mimeType: request.postData?.mimeType || "application/octet-stream"
3767
60
  },
3768
- ...request2
61
+ ...request
3769
62
  };
3770
63
  if (req.postData && !req.postData.mimeType) {
3771
64
  req.postData.mimeType = "application/octet-stream";
3772
65
  }
3773
- this.requests.push(this.prepare(req, options));
66
+ promises.push(this.prepare(req, this.options));
67
+ });
68
+ this.requests = await Promise.all(promises);
69
+ return this;
70
+ }
71
+ async prepare(harRequest, options) {
72
+ const request = {
73
+ ...harRequest,
74
+ fullUrl: "",
75
+ uriObj: {},
76
+ queryObj: {},
77
+ headersObj: {},
78
+ cookiesObj: {},
79
+ allHeaders: {}
80
+ };
81
+ if (request.queryString && request.queryString.length) {
82
+ request.queryObj = request.queryString.reduce(reducer, {});
83
+ }
84
+ if (request.headers && request.headers.length) {
85
+ const http2VersionRegex = /^HTTP\/2/;
86
+ request.headersObj = request.headers.reduce((accumulator, { name, value }) => {
87
+ const headerName = http2VersionRegex.exec(request.httpVersion) ? name.toLocaleLowerCase() : name;
88
+ return {
89
+ ...accumulator,
90
+ [headerName]: value
91
+ };
92
+ }, {});
93
+ }
94
+ if (request.cookies && request.cookies.length) {
95
+ request.cookiesObj = request.cookies.reduceRight(
96
+ (accumulator, { name, value }) => ({
97
+ ...accumulator,
98
+ [name]: value
99
+ }),
100
+ {}
101
+ );
102
+ }
103
+ const cookies = request.cookies?.map(({ name, value }) => {
104
+ if (options.harIsAlreadyEncoded) {
105
+ return `${name}=${value}`;
106
+ }
107
+ return `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
108
+ });
109
+ if (cookies?.length) {
110
+ request.allHeaders.cookie = cookies.join("; ");
111
+ }
112
+ switch (request.postData.mimeType) {
113
+ case "multipart/mixed":
114
+ case "multipart/related":
115
+ case "multipart/form-data":
116
+ case "multipart/alternative":
117
+ request.postData.text = "";
118
+ request.postData.mimeType = "multipart/form-data";
119
+ if (request.postData?.params) {
120
+ const form = new FormData();
121
+ request.postData?.params.forEach((param) => {
122
+ const name = param.name;
123
+ const value = param.value || "";
124
+ const filename = param.fileName || null;
125
+ const contentType = param.contentType || "";
126
+ if (filename) {
127
+ form.append(name, new Blob([value], { type: contentType }), filename);
128
+ } else {
129
+ form.append(name, value);
130
+ }
131
+ });
132
+ const boundary = "---011000010111000001101001";
133
+ request.postData.boundary = boundary;
134
+ request.postData.text = await formDataToString(form, { boundary });
135
+ const contentTypeHeader = getHeaderName(request.headersObj, "content-type") || "content-type";
136
+ request.headersObj[contentTypeHeader] = `multipart/form-data; boundary=${boundary}`;
137
+ }
138
+ break;
139
+ case "application/x-www-form-urlencoded":
140
+ if (!request.postData.params) {
141
+ request.postData.text = "";
142
+ } else {
143
+ request.postData.paramsObj = request.postData.params.reduce(reducer, {});
144
+ request.postData.text = stringify(request.postData.paramsObj);
145
+ }
146
+ break;
147
+ case "text/json":
148
+ case "text/x-json":
149
+ case "application/json":
150
+ case "application/x-json":
151
+ request.postData.mimeType = "application/json";
152
+ if (request.postData.text) {
153
+ try {
154
+ request.postData.jsonObj = JSON.parse(request.postData.text);
155
+ } catch (e) {
156
+ request.postData.mimeType = "text/plain";
157
+ }
158
+ }
159
+ break;
160
+ }
161
+ const allHeaders = {
162
+ ...request.allHeaders,
163
+ ...request.headersObj
164
+ };
165
+ const urlWithParsedQuery = parse(request.url, true, true);
166
+ request.queryObj = {
167
+ ...request.queryObj,
168
+ ...urlWithParsedQuery.query
169
+ };
170
+ let search;
171
+ if (options.harIsAlreadyEncoded) {
172
+ search = stringify(request.queryObj, {
173
+ encode: false,
174
+ indices: false
175
+ });
176
+ } else {
177
+ search = stringify(request.queryObj, {
178
+ indices: false
179
+ });
180
+ }
181
+ const uriObj = {
182
+ ...urlWithParsedQuery,
183
+ query: request.queryObj,
184
+ search,
185
+ path: search ? `${urlWithParsedQuery.pathname}?${search}` : urlWithParsedQuery.pathname
186
+ };
187
+ const url = format({
188
+ ...urlWithParsedQuery,
189
+ query: null,
190
+ search: null
3774
191
  });
192
+ const fullUrl = format({
193
+ ...urlWithParsedQuery,
194
+ ...uriObj
195
+ });
196
+ return {
197
+ ...request,
198
+ allHeaders,
199
+ fullUrl,
200
+ url,
201
+ uriObj
202
+ };
203
+ }
204
+ async convert(targetId, clientId, options) {
205
+ if (!this.initCalled) {
206
+ await this.init();
207
+ }
208
+ if (!options && clientId) {
209
+ options = clientId;
210
+ }
211
+ const target = targets[targetId];
212
+ if (!target) {
213
+ return false;
214
+ }
215
+ const { convert } = target.clientsById[clientId || target.info.default];
216
+ const results = this.requests.map((request) => convert(request, options));
217
+ return results.length === 1 ? results[0] : results;
3775
218
  }
3776
219
  };
3777
- /**
3778
- * @license https://raw.githubusercontent.com/node-fetch/node-fetch/master/LICENSE.md
3779
- *
3780
- * The MIT License (MIT)
3781
- *
3782
- * Copyright (c) 2016 - 2020 Node Fetch Team
3783
- *
3784
- * Permission is hereby granted, free of charge, to any person obtaining a copy
3785
- * of this software and associated documentation files (the "Software"), to deal
3786
- * in the Software without restriction, including without limitation the rights
3787
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
3788
- * copies of the Software, and to permit persons to whom the Software is
3789
- * furnished to do so, subject to the following conditions:
3790
- *
3791
- * The above copyright notice and this permission notice shall be included in all
3792
- * copies or substantial portions of the Software.
3793
- *
3794
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
3795
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
3796
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
3797
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
3798
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
3799
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
3800
- * SOFTWARE.
3801
- *
3802
- * Extracted from https://github.com/node-fetch/node-fetch/blob/64c5c296a0250b852010746c76144cb9e14698d9/src/utils/form-data.js
3803
- */
3804
220
 
3805
- exports.HTTPSnippet = HTTPSnippet;
3806
- exports.addTarget = addTarget;
3807
- exports.addTargetClient = addTargetClient;
3808
- exports.availableTargets = availableTargets;
3809
- exports.extname = extname;
221
+ export { HTTPSnippet, availableTargets, extname };
3810
222
  //# sourceMappingURL=out.js.map
3811
223
  //# sourceMappingURL=index.js.map