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