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