refactor: remove mock-fs from dev dependency

This commit is contained in:
harttle
2019-02-19 22:28:27 +08:00
parent f432aade6a
commit 852c6ad453
70 changed files with 711 additions and 795 deletions
+51
View File
@@ -0,0 +1,51 @@
import { last } from '../util/underscore'
import IFS from './ifs'
function domResolve (root, path) {
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, filepath, ext) {
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()
})
}
async function exists () {
return true
}
export default { readFile, resolve, exists } as IFS
+5
View File
@@ -0,0 +1,5 @@
export default interface IFS {
exists: (filepath?: string) => Promise<boolean>
readFile: (filepath:string) => Promise<string>
resolve: (root: string, file: string, ext: string) => string
}
+22
View File
@@ -0,0 +1,22 @@
import * as _ from '../util/underscore'
import { resolve, extname } from 'path'
import { stat, readFile } from 'fs'
import IFS from './ifs'
const statAsync = _.promisify(stat) as (filepath: string) => Promise<object>
const readFileAsync = _.promisify(readFile) as (filepath: string, encoding: string) => Promise<string>
const fs: IFS = {
exists: filepath => {
return statAsync(filepath).then(() => true).catch(() => false)
},
readFile: filepath => {
return readFileAsync(filepath, 'utf8')
},
resolve: (root: string, file: string, ext: string) => {
if (!extname(file)) file += ext
return resolve(root, file)
}
}
export default fs