/
index.js
54 lines (42 loc) · 1.27 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
'use strict'
// woot
const normalizeEmail = require('normalize-email')
const normalizeUrl = require('normalize-url')
const run = str => {
if (!str) {
return { error: 'missing param' }
}
str = str.trim()
if (str.split('.').filter(Boolean).length < 2) {
return { error: 'need something on both sides of the "."' }
}
const pAt = str.indexOf('@')
const pSlash = str.indexOf('/')
const bothAtSlash = pAt !== -1 && pSlash !== -1
try {
if (bothAtSlash && pSlash < pAt) {
return { url: normalizeUrl(str, { stripWWW: false }) }
}
const [name, domain] = str.replace(/^mailto:/, '').split('@')
if (!domain) {
return { url: normalizeUrl(str, { stripWWW: false }) }
}
if (bothAtSlash && pAt < pSlash) {
return { error: 'bad email (/)' }
}
const email = normalizeEmail(`${name}@${domain}`)
const [nameNormalized] = email.split('@')
const d = normalizeUrl(domain, { stripWWW: false }).slice(7)
if (email === `${nameNormalized}@${d}`) {
return { email }
} else {
// FIXME: should not error, êxample should be "punycoded"
}
// see test "idn email fixed"
// should never be reached
return { error: 'unexpected error' }
} catch (error) {
return { error }
}
}
module.exports = run