This repository has been archived by the owner on Dec 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
fs.ts
261 lines (228 loc) · 8.25 KB
/
fs.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
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
import * as fs from 'graceful-fs'
import Promise = require('any-promise')
import thenify = require('thenify')
import stripBom = require('strip-bom')
import parse = require('parse-json')
import popsicle = require('popsicle')
import popsicleStatus = require('popsicle-status')
import popsicleRetry = require('popsicle-retry')
import detectIndent = require('detect-indent')
import sortKeys = require('sort-keys')
import mdp = require('mkdirp')
import uniq = require('array-uniq')
import lockfile = require('lockfile')
import rmrf = require('rimraf')
import popsicleProxy = require('popsicle-proxy-agent')
import promiseFinally from 'promise-finally'
import tch = require('touch')
import { join, dirname } from 'path'
import { parse as parseUrl } from 'url'
import template = require('string-template')
import { CONFIG_FILE, TYPINGS_DIR, DTS_MAIN_FILE, DTS_BROWSER_FILE, PRETTY_PROJECT_NAME, HOMEPAGE } from './config'
import { isHttp, EOL, detectEOL, normalizeEOL } from './path'
import { parseReferences, stringifyReferences } from './references'
import { ConfigJson } from '../interfaces'
import { CompiledOutput } from '../lib/compile'
import rc from './rc'
import store from './store'
import debug from './debug'
const pkg = require('../../package.json')
const registryURL = parseUrl(rc.registryURL)
export type Stats = fs.Stats
export const touch: (path: string, options?: tch.Options) => Promise<void> = thenify<string, tch.Options, void>(tch)
export const stat: (path: string) => Promise<Stats> = thenify(fs.stat)
export const readFile: (path: string, encoding: string) => Promise<string> = thenify<string, string, string>(fs.readFile)
export const writeFile: (path: string, contents: string | Buffer) => Promise<void> = thenify<string, string | Buffer, void>(fs.writeFile)
export const mkdirp: (path: string) => Promise<string> = thenify<string, string>(mdp)
export const unlink: (path: string) => Promise<void> = thenify<string, void>(fs.unlink)
export const lock: (path: string, options?: lockfile.Options) => Promise<void> = thenify<string, lockfile.Options, void>(lockfile.lock)
export const unlock: (path: string) => Promise<void> = thenify<string, void>(lockfile.unlock)
export const rimraf: (path: string) => Promise<void> = thenify<string, void>(rmrf)
/**
* Verify a path exists and is a file.
*/
export function isFile (path: string): Promise<boolean> {
return stat(path).then(stat => stat.isFile(), () => false)
}
/**
* Read JSON from a path.
*/
export function readJson (path: string, allowEmpty?: boolean): Promise<any> {
return readFile(path, 'utf8')
.then(stripBom)
.then(contents => parseJson(contents, path, allowEmpty))
}
/**
* Write JSON to a file.
*/
export function writeJson (path: string, json: any, indent?: string | number, eol?: string) {
return writeFile(path, stringifyJson(json, indent, eol))
}
/**
* Read a configuration file.
*/
export function readConfig (path: string): Promise<ConfigJson> {
return readJson(path, true).then(data => parseConfig(data, path))
}
/**
* Read a configuration file from anywhere (HTTP or local).
*/
export function readConfigFrom (path: string): Promise<ConfigJson> {
return readJsonFrom(path, true).then(data => parseConfig(data, path))
}
/**
* Parse a config object with helpful validation.
*/
export function parseConfig (config: ConfigJson, path: string): ConfigJson {
// TODO(blakeembrey): Validate config object.
return config
}
/**
* Read a file over HTTP, using a file cache and status check.
*/
export function readHttp (url: string): Promise<string> {
const { proxy, httpProxy, httpsProxy, noProxy, rejectUnauthorized, ca, key, cert, userAgent } = rc
return popsicle.get({
url,
headers: {
'User-Agent': template(userAgent, {
nodeVersion: process.version,
platform: process.platform,
arch: process.arch,
typingsVersion: pkg.version
})
},
options: {
ca,
key,
cert,
rejectUnauthorized
},
use: [
popsicle.plugins.headers(),
popsicle.plugins.unzip(),
popsicle.plugins.concatStream('string')
]
})
// Enable HTTP(s) proxies and environment variable support.
.use(popsicleProxy({ proxy, httpProxy, httpsProxy, noProxy }))
// Retry failed HTTP requests.
.use(popsicleRetry({ maxRetries: 3, retryDelay: 3000 }))
// Check responses are "200 OK".
.use(popsicleStatus(200))
// Enable tracking of repeat users on the registry.
.use(function (self) {
if (self.Url.host === registryURL.host) {
if (store.get('clientId')) {
self.before(function (req) {
req.set('Typings-Client-Id', store.get('clientId'))
})
} else {
self.after(function (res) {
store.set('clientId', res.get('Typings-Client-Id'))
})
}
}
})
// Return only the response body.
.then(response => {
debug('http response', response.toJSON())
return response.body
})
}
/**
* Read a file from anywhere (HTTP or local filesystem).
*/
export function readFileFrom (from: string): Promise<string> {
return isHttp(from) ? readHttp(from) : readFile(from, 'utf8')
}
/**
* Read JSON from anywhere.
*/
export function readJsonFrom (from: string, allowEmpty?: boolean): Promise<any> {
return readFileFrom(from)
.then(stripBom)
.then(contents => parseJson(contents, from, allowEmpty))
}
/**
* Stringify an object as JSON for the filesystem (appends EOL).
*/
export function stringifyJson (json: any, indent?: number | string, eol: string = EOL) {
return normalizeEOL(JSON.stringify(json, null, indent || 2), eol) + eol
}
/**
* Parse a string as JSON.
*/
export function parseJson (contents: string, path: string, allowEmpty: boolean) {
if (contents === '' && allowEmpty) {
return {}
}
return parse(contents, null, path)
}
/**
* Transform a file contents (read and write in a single operation).
*/
export function transformFile (path: string, transform: (contents: string) => string | Promise<string>): Promise<void> {
function handle (contents: string) {
return Promise.resolve(transform(contents))
.then(contents => writeFile(path, contents))
}
const lockfile = `${path}.lock`
const lockOptions = { wait: 250, retries: 25, stale: 60000 }
const result = lock(lockfile, lockOptions)
.then(() => {
return readFile(path, 'utf8')
})
.then(
(contents) => handle(contents),
() => handle(undefined)
)
return promiseFinally(result, () => unlock(lockfile))
}
/**
* Transform a JSON file in a single operation.
*/
export function transformJson <T> (path: string, transform: (json: T) => T, allowEmpty?: boolean) {
return transformFile(path, (contents) => {
const indent = contents ? detectIndent(contents).indent : undefined
const json = contents ? parseJson(contents, path, allowEmpty) : undefined
const eol = contents ? detectEOL(contents) : undefined
return Promise.resolve(transform(json))
.then(json => stringifyJson(json, indent, eol))
})
}
/**
* Transform a configuration file in a single operation.
*/
export function transformConfig (cwd: string, transform: (config: ConfigJson) => ConfigJson) {
const path = join(cwd, CONFIG_FILE)
return transformJson<ConfigJson>(path, (config = {}) => {
return Promise.resolve(transform(parseConfig(config, path)))
.then(config => {
if (config.dependencies) {
config.dependencies = sortKeys(config.dependencies)
}
if (config.peerDependencies) {
config.peerDependencies = sortKeys(config.peerDependencies)
}
if (config.devDependencies) {
config.devDependencies = sortKeys(config.devDependencies)
}
if (config.ambientDependencies) {
config.ambientDependencies = sortKeys(config.ambientDependencies)
}
if (config.ambientDevDependencies) {
config.ambientDevDependencies = sortKeys(config.ambientDevDependencies)
}
return config
})
}, true)
}
export function transformDtsFile (path: string, transform: (typings: string[]) => string[]) {
const cwd = dirname(path)
return transformFile(path, contents => {
const typings = parseReferences(contents, cwd)
return Promise.resolve(transform(typings))
.then(typings => stringifyReferences(uniq(typings).sort(), cwd))
})
}