-
-
Notifications
You must be signed in to change notification settings - Fork 237
/
Copy pathbrowser.ts
65 lines (55 loc) · 1.63 KB
/
browser.ts
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
import { last } from '../util/underscore'
import IFS from './ifs'
function domResolve (root: string, path: string) {
const base = document.createElement('base')
base.href = root
const head = document.getElementsByTagName('head')[0]
head.insertBefore(base, head.firstChild)
const a = document.createElement('a')
a.href = path
const resolved = a.href
head.removeChild(base)
return resolved
}
function resolve (root: string, filepath: string, ext: string) {
if (root.length && last(root) !== '/') root += '/'
const url = domResolve(root, filepath)
return url.replace(/^(\w+:\/\/[^/]+)(\/[^?]+)/, (str, origin, path) => {
const last = path.split('/').pop()
if (/\.\w+$/.test(last)) return str
return origin + path + ext
})
}
async function readFile (url: string): Promise<string> {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.responseText as string)
} else {
reject(new Error(xhr.statusText))
}
}
xhr.onerror = () => {
reject(new Error('An error occurred whilst receiving the response.'))
}
xhr.open('GET', url)
xhr.send()
})
}
function readFileSync (url: string): string {
const xhr = new XMLHttpRequest()
xhr.open('GET', url, false)
xhr.send()
if (xhr.status < 200 || xhr.status >= 300) {
throw new Error(xhr.statusText)
}
return xhr.responseText as string
}
async function exists () {
return true
}
function existsSync () {
return true
}
export default { readFile, resolve, exists, existsSync, readFileSync } as IFS