/
index.js
461 lines (409 loc) · 14.9 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
import 'bootstrap'
import { detect } from 'detect-browser'
import './main.scss'
import { languages } from './languages.js'
import hljs from 'highlight.js/lib/core'
import plaintext from 'highlight.js/lib/languages/plaintext'
import bash from 'highlight.js/lib/languages/bash'
import c from 'highlight.js/lib/languages/c'
import clojure from 'highlight.js/lib/languages/clojure'
import csharp from 'highlight.js/lib/languages/csharp'
import dart from 'highlight.js/lib/languages/dart'
import elixir from 'highlight.js/lib/languages/elixir'
import go from 'highlight.js/lib/languages/go'
import http from 'highlight.js/lib/languages/http'
import java from 'highlight.js/lib/languages/java'
import javascript from 'highlight.js/lib/languages/javascript'
import json from 'highlight.js/lib/languages/json'
import julia from 'highlight.js/lib/languages/julia'
import kotlin from 'highlight.js/lib/languages/kotlin'
import lua from 'highlight.js/lib/languages/lua'
import matlab from 'highlight.js/lib/languages/matlab'
import objectivec from 'highlight.js/lib/languages/objectivec'
import ocaml from 'highlight.js/lib/languages/ocaml'
import perl from 'highlight.js/lib/languages/perl'
import php from 'highlight.js/lib/languages/php'
import powershell from 'highlight.js/lib/languages/powershell'
import python from 'highlight.js/lib/languages/python'
import r from 'highlight.js/lib/languages/r'
import ruby from 'highlight.js/lib/languages/ruby'
import rust from 'highlight.js/lib/languages/rust'
import swift from 'highlight.js/lib/languages/swift'
import yaml from 'highlight.js/lib/languages/yaml'
import getExampleTemplate from './examples/get.sh'
import postExampleTemplate from './examples/post.sh'
import authExampleText from './examples/auth.sh'
import jsonExampleText from './examples/json.sh'
import filesExampleText from './examples/files.sh'
import formExampleText from './examples/form.sh'
hljs.registerLanguage('plaintext', plaintext)
hljs.registerLanguage('bash', bash)
hljs.registerLanguage('c', c)
hljs.registerLanguage('clojure', clojure)
hljs.registerLanguage('csharp', csharp)
hljs.registerLanguage('dart', dart)
hljs.registerLanguage('elixir', elixir)
hljs.registerLanguage('go', go)
hljs.registerLanguage('http', http)
hljs.registerLanguage('java', java)
hljs.registerLanguage('javascript', javascript)
hljs.registerLanguage('json', json)
hljs.registerLanguage('julia', julia)
hljs.registerLanguage('kotlin', kotlin)
hljs.registerLanguage('lua', lua)
hljs.registerLanguage('matlab', matlab)
hljs.registerLanguage('objectivec', objectivec)
hljs.registerLanguage('ocaml', ocaml)
hljs.registerLanguage('perl', perl)
hljs.registerLanguage('php', php)
hljs.registerLanguage('powershell', powershell)
hljs.registerLanguage('python', python)
hljs.registerLanguage('r', r)
hljs.registerLanguage('ruby', ruby)
hljs.registerLanguage('rust', rust)
hljs.registerLanguage('swift', swift)
hljs.registerLanguage('yaml', yaml)
// TODO: include a Windows screenshot for Chrome and Firefox.
//
// TODO: put the curl input in the URL?
// TODO: print a diff of the raw resulting requests?
//
// TODO: add check box for scanning the clipboard?
// TODO: translate the site. The top languages are
// chinese
// russian
// portuguese
// japanese
// korean
// french
// spanish
// https://techblog.willshouse.com/2012/01/03/most-common-user-agents/
let useragent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36'
// For fun and future-proofing, put the user's
// actual User Agent in the examples
if (window.navigator &&
window.navigator.userAgent &&
window.navigator.userAgent.trim() &&
!/[^a-z0-9-/().;, _]/i.test(window.navigator.userAgent)) {
useragent = window.navigator.userAgent
}
const getExampleText = getExampleTemplate.replace('{{useragent}}', useragent)
const postExampleText = postExampleTemplate.replace('{{useragent}}', useragent)
const changeHighlight = (language) => {
if (languages[language] && languages[language].hljs) {
language = languages[language].hljs
}
const newClass = 'language-' + language
let seen = false
const generatedCodeEl = document.getElementById('generated-code')
for (const cls of generatedCodeEl.classList) {
if (cls === newClass) {
seen = true
} else if (cls.startsWith('language-')) {
generatedCodeEl.classList.remove(cls)
}
}
if (!seen) {
generatedCodeEl.classList.add(newClass)
}
const navbar = document.getElementById('language-navbar')
if (language === 'plaintext') {
navbar.classList.add('error')
} else {
navbar.classList.remove('error')
}
generatedCodeEl.removeAttribute('data-highlighted');
hljs.highlightElement(generatedCodeEl)
}
const changeLanguage = function (language) {
window.history.replaceState('', '', '/' + language + '/')
const languageSelect = document.getElementById('language-select')
languageSelect.value = language
const languageNavbar = document.getElementById('language-navbar')
// const newActiveElem = e.target.classList.contains('dropdown-item') ? : e.target
const newActiveElem = languageNavbar.querySelector(`a[href="/${language}/"]`)
for (const item of languageNavbar.querySelectorAll('.nav-link, .dropdown-item')) {
item.classList.remove('active')
}
newActiveElem.classList.add('active')
if (newActiveElem.classList.contains('dropdown-item')) {
const parent = newActiveElem.parentElement.parentElement.parentElement.getElementsByClassName('dropdown-toggle')[0]
if (parent) {
parent.classList.add('active')
}
}
document.getElementById('language-select').value = language
changeHighlight(language)
try {
if (Object.prototype.hasOwnProperty.call(languages, language)) {
// The initial title in the HTML is a bit more verbose for Google
// If the user clicks on the language they already opened again,
// don't needlessly change the title
const initialTitle = 'Convert curl commands to ' + languages[language].title
const newTitle = 'curl to ' + (languages[language].shortTitle || languages[language].title)
if (document.title !== newTitle && document.title !== initialTitle) {
document.title = newTitle
}
}
} catch {}
return language
}
const getLanguage = function () {
const languageSelect = document.getElementById('language-select')
return languageSelect.value
}
const showIssuePromo = () => {
document.getElementById('issue-promo').style.display = 'inline-block'
}
const hideIssuePromo = () => {
document.getElementById('issue-promo').style.display = 'none'
}
const showCopyToClipboard = () => {
document.getElementById('copy-to-clipboard').style.display = 'inline-block'
}
const hideCopyToClipboard = () => {
document.getElementById('copy-to-clipboard').style.display = 'none'
}
const showExample = function (code) {
const inputBox = document.getElementById('curl-code');
inputBox.value = code.trim();
inputBox.dispatchEvent(new Event('input', { bubbles: true, composed: true }));
}
const convert = function () {
let curlCode = document.getElementById('curl-code').value
try {
window.sessionStorage.setItem('prev-curl-command', curlCode)
} catch {}
let generatedCode
let error
const language = getLanguage()
let warnings = []
// Convert the placeholder text as a demo
if (!curlCode) {
curlCode = 'curl example.com'
}
// Remove leading $
if (curlCode.match(/^\s*\$\s+curl\s+/)) {
curlCode = curlCode.replace(/^\s*\$\s*/, '')
}
// If command starts with a non-breaking space, replace all of them with a space
if (curlCode.startsWith('curl\u00A0')) {
curlCode = curlCode.replace(/\u00A0/g, ' ')
}
if (!curlCode.trim()) {
error = ''
hideIssuePromo()
hideCopyToClipboard()
} else {
try {
const converter = languages[language].converter;
[generatedCode, warnings] = converter(curlCode, warnings)
// remove trailing newline
if (generatedCode.endsWith('\n')) {
generatedCode = generatedCode.slice(0, -1)
}
hideIssuePromo()
showCopyToClipboard()
} catch (e) {
console.error(e)
const origErrorMsg = e.toString()
if (origErrorMsg) {
if (origErrorMsg.startsWith('Error: ')) {
error = origErrorMsg
} else {
error = 'Error parsing curl command: ' + origErrorMsg
}
} else if (!curlCode.trim().startsWith('curl')) {
error = 'Error parsing curl command. Your input should start with the word "curl"'
} else {
error = 'Error parsing curl command.'
}
changeHighlight('plaintext')
showIssuePromo()
hideCopyToClipboard()
}
}
const generatedCodeEl = document.getElementById('generated-code')
const warningsEl = document.getElementById('warnings')
// We need to hide the element that has the padding
const warningsContainerEl = document.getElementById('warnings-container')
if (!error) {
generatedCodeEl.textContent = generatedCode
changeHighlight(language)
} else {
generatedCodeEl.textContent = error
changeHighlight('plaintext')
}
if (userOS === 'windows' && curlCode.split('^', 6).length > 5) {
warnings.push(['copy-as-cmd', 'Did you click "Copy as cURL (cmd)" instead of "Copy as cURL (bash)"? Only bash commands are supported.'])
}
if (warnings && warnings.length) {
warningsEl.textContent = warnings.map(w => w[1]).join('\n')
warningsContainerEl.style.display = 'inline-block'
} else {
warningsEl.textContent = ''
warningsContainerEl.style.display = 'none'
}
}
let startingLanguage = ''
const path = window.location.pathname.replace(/^\/+/, '').replace(/\/+$/, '')
const hash = window.location.hash.replace('#', '')
// Backwards compatibility. The language used to be in the hash, like
// https://curlconverter.com/#elixir
// now it's in the path
// https://curlconverter.com/elixir/
if (!path && hash) {
// backwards compat
if (hash === 'browser') {
startingLanguage = 'javascript'
} else if (hash === 'node') {
startingLanguage = 'node-fetch'
} else {
startingLanguage = hash
}
} else if (path && path === 'cfml') {
startingLanguage = 'coldfusion'
} else {
startingLanguage = path
}
if (Object.prototype.hasOwnProperty.call(languages, startingLanguage)) {
changeLanguage(startingLanguage)
}
const curlCodeInput = document.getElementById('curl-code')
curlCodeInput.addEventListener('input', convert)
// listen for change in select
const languageSelect = document.getElementById('language-select')
languageSelect.addEventListener('change', function () {
const language = document.getElementById('language-select').value
changeLanguage(language)
convert()
})
const languageNavbar = document.getElementById('language-navbar')
const languageNavbarItems = languageNavbar.querySelectorAll('.nav-link:not(.dropdown-toggle):not(.nav-link-outbound), .dropdown-item')
for (const navbarItem of languageNavbarItems) {
navbarItem.addEventListener('click', function (e) {
e.preventDefault()
const language = new URL(e.target.href).pathname.replace(/^\/+/, '').replace(/\/+$/, '').split('/')[0]
changeLanguage(language)
convert()
})
}
const getExample = document.getElementById('get-example')
getExample.addEventListener('click', function (e) {
e.preventDefault() // Don't scroll to the top of the page
showExample(getExampleText)
})
const postExample = document.getElementById('post-example')
postExample.addEventListener('click', function (e) {
e.preventDefault()
showExample(postExampleText)
})
const basicAuthExample = document.getElementById('basic-auth-example')
basicAuthExample.addEventListener('click', function (e) {
e.preventDefault()
showExample(authExampleText)
})
const jsonExample = document.getElementById('json-example')
jsonExample.addEventListener('click', function (e) {
e.preventDefault()
showExample(jsonExampleText)
})
const filesExample = document.getElementById('files-example')
filesExample.addEventListener('click', function (e) {
e.preventDefault()
showExample(filesExampleText)
})
const formExample = document.getElementById('form-example')
formExample.addEventListener('click', function (e) {
e.preventDefault()
showExample(formExampleText)
})
const copyToClipboardEl = document.getElementById('copy-to-clipboard')
copyToClipboardEl.addEventListener('click', (e) => {
e.preventDefault()
const generatedCodeEl = document.getElementById('generated-code')
const selection = window.getSelection()
const range = document.createRange()
range.selectNodeContents(generatedCodeEl)
selection.removeAllRanges()
selection.addRange(range)
navigator.clipboard.writeText(generatedCodeEl.textContent)
})
const browsers = ['chrome', 'safari', 'firefox']
const browserNames = {
'chrome': 'chrome',
'chromium-webview': 'chrome',
'edge': 'chrome',
'edge-chromium': 'chrome',
'yandexbrowser': 'chrome',
'opera': 'chrome',
'opera-mini': 'chrome',
'android': 'chrome',
'firefox': 'firefox',
'safari': 'safari',
'ios': 'safari',
'ios-webview': 'safari',
'edge-ios': 'safari'
}
let userBrowser = 'chrome'
let userOS = 'mac'
try {
const detectedBrowser = detect()
if (detectedBrowser && detectedBrowser.name) {
userBrowser = browserNames[detectedBrowser.name] || 'chrome'
if (detectedBrowser.os && detectedBrowser.os.toLowerCase().startsWith('windows')) {
userOS = 'windows'
}
}
} catch {}
const showInstructions = function (browser) {
if (!browsers.includes(browser)) {
browser = userBrowser
}
for (const b of browsers) {
const el = document.getElementById(b)
if (b === browser) {
el.classList.remove('d-none')
} else {
el.classList.add('d-none')
}
}
const screenshot = document.getElementById('screenshot')
const [width, height] = {
chrome: [648, 354],
firefox: [733, 251],
safari: [658, 373]
}[browser]
const newInnerHTML = `
<source srcset="/images/${browser}.webp, /images/${browser}@2x.webp 2x" type="image/webp">
<img class="img-fluid mx-auto d-block" src="/images/${browser}.png" srcset="/images/${browser}@2x.png 2x" width="${width}" height="${height}"alt="screenshot of browser DevTools showing how to copy a network request as curl">
`
if (screenshot.innerHTML !== newInnerHTML) {
screenshot.innerHTML = newInnerHTML
}
}
for (const b of browsers) {
const basicAuthExamples = document.getElementsByClassName('to-' + b)
for (const basicAuthExample of basicAuthExamples) {
basicAuthExample.addEventListener('click', function (e) {
e.preventDefault()
const browser = [...e.target.classList].filter(c => c.startsWith('to-'))
if (browser.length) {
showInstructions(browser[0].replace(/^to-/, ''))
} else {
showInstructions()
}
})
}
}
const inputBox = document.getElementById('curl-code')
try {
const prevCommand = window.sessionStorage.getItem('prev-curl-command')
if (prevCommand && !inputBox.value) {
inputBox.value = prevCommand
}
} catch {}
inputBox.removeAttribute('disabled')
inputBox.focus()
convert()
showInstructions()