/
index.js
279 lines (243 loc) · 6.2 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
const { readFile, writeFile } = require('fs/promises')
const { resolve } = require('path')
const updateDeps = require('./update-dependencies.js')
const updateScripts = require('./update-scripts.js')
const updateWorkspaces = require('./update-workspaces.js')
const normalize = require('./normalize.js')
const parseJSON = require('json-parse-even-better-errors')
// a list of handy specialized helper functions that take
// care of special cases that are handled by the npm cli
const knownSteps = new Set([
updateDeps,
updateScripts,
updateWorkspaces,
])
// list of all keys that are handled by "knownSteps" helpers
const knownKeys = new Set([
...updateDeps.knownKeys,
'scripts',
'workspaces',
])
class PackageJson {
static normalizeSteps = Object.freeze([
'_id',
'_attributes',
'bundledDependencies',
'bundleDependencies',
'optionalDedupe',
'scripts',
'funding',
'bin',
])
// npm pkg fix
static fixSteps = Object.freeze([
'binRefs',
'bundleDependencies',
'bundleDependenciesFalse',
'fixNameField',
'fixVersionField',
'fixRepositoryField',
'fixBinField',
'fixDependencies',
'fixScriptsField',
'devDependencies',
'scriptpath',
])
static prepareSteps = Object.freeze([
'_id',
'_attributes',
'bundledDependencies',
'bundleDependencies',
'bundleDependenciesDeleteFalse',
'gypfile',
'serverjs',
'scriptpath',
'authors',
'readme',
'mans',
'binDir',
'gitHead',
'fillTypes',
'normalizeData',
'binRefs',
])
// create a new empty package.json, so we can save at the given path even
// though we didn't start from a parsed file
static async create (path, opts = {}) {
const p = new PackageJson()
await p.create(path)
if (opts.data) {
return p.update(opts.data)
}
return p
}
// Loads a package.json at given path and JSON parses
static async load (path, opts = {}) {
const p = new PackageJson()
// Avoid try/catch if we aren't going to create
if (!opts.create) {
return p.load(path)
}
try {
return await p.load(path)
} catch (err) {
if (!err.message.startsWith('Could not read package.json')) {
throw err
}
return await p.create(path)
}
}
// npm pkg fix
static async fix (path, opts) {
const p = new PackageJson()
await p.load(path, true)
return p.fix(opts)
}
// read-package-json compatible behavior
static async prepare (path, opts) {
const p = new PackageJson()
await p.load(path, true)
return p.prepare(opts)
}
// read-package-json-fast compatible behavior
static async normalize (path, opts) {
const p = new PackageJson()
await p.load(path)
return p.normalize(opts)
}
#path
#manifest
#readFileContent = ''
#canSave = true
// Load content from given path
async load (path, parseIndex) {
this.#path = path
let parseErr
try {
this.#readFileContent = await readFile(this.filename, 'utf8')
} catch (err) {
err.message = `Could not read package.json: ${err}`
if (!parseIndex) {
throw err
}
parseErr = err
}
if (parseErr) {
const indexFile = resolve(this.path, 'index.js')
let indexFileContent
try {
indexFileContent = await readFile(indexFile, 'utf8')
} catch (err) {
throw parseErr
}
try {
this.fromComment(indexFileContent)
} catch (err) {
throw parseErr
}
// This wasn't a package.json so prevent saving
this.#canSave = false
return this
}
return this.fromJSON(this.#readFileContent)
}
// Load data from a JSON string/buffer
fromJSON (data) {
try {
this.#manifest = parseJSON(data)
} catch (err) {
err.message = `Invalid package.json: ${err}`
throw err
}
return this
}
// Load data from a comment
// /**package { "name": "foo", "version": "1.2.3", ... } **/
fromComment (data) {
data = data.split(/^\/\*\*package(?:\s|$)/m)
if (data.length < 2) {
throw new Error('File has no package in comments')
}
data = data[1]
data = data.split(/\*\*\/$/m)
if (data.length < 2) {
throw new Error('File has no package in comments')
}
data = data[0]
data = data.replace(/^\s*\*/mg, '')
this.#manifest = parseJSON(data)
return this
}
get content () {
return this.#manifest
}
get path () {
return this.#path
}
get filename () {
if (this.path) {
return resolve(this.path, 'package.json')
}
return undefined
}
create (path) {
this.#path = path
this.#manifest = {}
return this
}
// This should be the ONLY way to set content in the manifest
update (content) {
if (!this.content) {
throw new Error('Can not update without content. Please `load` or `create`')
}
for (const step of knownSteps) {
this.#manifest = step({ content, originalContent: this.content })
}
// unknown properties will just be overwitten
for (const [key, value] of Object.entries(content)) {
if (!knownKeys.has(key)) {
this.content[key] = value
}
}
return this
}
async save () {
if (!this.#canSave) {
throw new Error('No package.json to save to')
}
const {
[Symbol.for('indent')]: indent,
[Symbol.for('newline')]: newline,
} = this.content
const format = indent === undefined ? ' ' : indent
const eol = newline === undefined ? '\n' : newline
const fileContent = `${
JSON.stringify(this.content, null, format)
}\n`
.replace(/\n/g, eol)
if (fileContent.trim() !== this.#readFileContent.trim()) {
return await writeFile(this.filename, fileContent)
}
}
async normalize (opts = {}) {
if (!opts.steps) {
opts.steps = this.constructor.normalizeSteps
}
await normalize(this, opts)
return this
}
async prepare (opts = {}) {
if (!opts.steps) {
opts.steps = this.constructor.prepareSteps
}
await normalize(this, opts)
return this
}
async fix (opts = {}) {
// This one is not overridable
opts.steps = this.constructor.fixSteps
await normalize(this, opts)
return this
}
}
module.exports = PackageJson