forked from lerna/lerna
/
index.js
303 lines (250 loc) · 8.26 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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
"use strict";
const npa = require("npm-package-arg");
const path = require("path");
const loadJsonFile = require("load-json-file");
const writePkg = require("write-pkg");
// symbol used to "hide" internal state
const PKG = Symbol("pkg");
/* eslint-disable no-underscore-dangle */
// private fields
const _location = Symbol("location");
const _resolved = Symbol("resolved");
const _rootPath = Symbol("rootPath");
const _scripts = Symbol("scripts");
const _contents = Symbol("contents");
/**
* @param {import("npm-package-arg").Result} result
*/
function binSafeName({ name, scope }) {
return scope ? name.substring(scope.length + 1) : name;
}
// package.json files are not that complicated, so this is intentionally naïve
function shallowCopy(json) {
return Object.keys(json).reduce((obj, key) => {
const val = json[key];
/* istanbul ignore if */
if (Array.isArray(val)) {
obj[key] = val.slice();
} else if (val && typeof val === "object") {
obj[key] = Object.assign({}, val);
} else {
obj[key] = val;
}
return obj;
}, {});
}
/**
* @typedef {object} RawManifest The subset of package.json properties that Lerna uses
* @property {string} name
* @property {string} version
* @property {boolean} [private]
* @property {Record<string, string>|string} [bin]
* @property {Record<string, string>} [scripts]
* @property {Record<string, string>} [dependencies]
* @property {Record<string, string>} [devDependencies]
* @property {Record<string, string>} [optionalDependencies]
* @property {Record<string, string>} [peerDependencies]
* @property {Record<'directory' | 'registry' | 'tag', string>} [publishConfig]
*/
/**
* Lerna's internal representation of a local package, with
* many values resolved directly from the original JSON.
*/
class Package {
/**
* Create a Package instance from parameters, possibly reusing existing instance.
* @param {string|Package|RawManifest} ref A path to a package.json file, Package instance, or JSON object
* @param {string} [dir] If `ref` is a JSON object, this is the location of the manifest
* @returns {Package}
*/
static lazy(ref, dir = ".") {
if (typeof ref === "string") {
const location = path.resolve(path.basename(ref) === "package.json" ? path.dirname(ref) : ref);
const manifest = loadJsonFile.sync(path.join(location, "package.json"));
return new Package(manifest, location);
}
// don't use instanceof because it fails across nested module boundaries
if ("__isLernaPackage" in ref) {
return ref;
}
// assume ref is a json object
return new Package(ref, dir);
}
/**
* @param {RawManifest} pkg
* @param {string} location
* @param {string} [rootPath]
*/
constructor(pkg, location, rootPath = location) {
// npa will throw an error if the name is invalid
const resolved = npa.resolve(pkg.name, `file:${path.relative(rootPath, location)}`, rootPath);
this.name = pkg.name;
this[PKG] = pkg;
// omit raw pkg from default util.inspect() output, but preserve internal mutability
Object.defineProperty(this, PKG, { enumerable: false, writable: true });
this[_location] = location;
this[_resolved] = resolved;
this[_rootPath] = rootPath;
this[_scripts] = { ...pkg.scripts };
}
// readonly getters
get location() {
return this[_location];
}
get private() {
return Boolean(this[PKG].private);
}
get resolved() {
return this[_resolved];
}
get rootPath() {
return this[_rootPath];
}
get scripts() {
return this[_scripts];
}
get bin() {
const pkg = this[PKG];
return typeof pkg.bin === "string"
? {
[binSafeName(this.resolved)]: pkg.bin,
}
: Object.assign({}, pkg.bin);
}
get binLocation() {
return path.join(this.location, "node_modules", ".bin");
}
get manifestLocation() {
return path.join(this.location, "package.json");
}
get nodeModulesLocation() {
return path.join(this.location, "node_modules");
}
// eslint-disable-next-line class-methods-use-this
get __isLernaPackage() {
// safer than instanceof across module boundaries
return true;
}
// accessors
get version() {
return this[PKG].version;
}
set version(version) {
this[PKG].version = version;
}
get contents() {
// if modified with setter, use that value
if (this[_contents]) {
return this[_contents];
}
// if provided by pkg.publishConfig.directory value
if (this[PKG].publishConfig && this[PKG].publishConfig.directory) {
return path.join(this.location, this[PKG].publishConfig.directory);
}
// default to package root
return this.location;
}
set contents(subDirectory) {
this[_contents] = path.join(this.location, subDirectory);
}
// "live" collections
get dependencies() {
return this[PKG].dependencies;
}
get devDependencies() {
return this[PKG].devDependencies;
}
get optionalDependencies() {
return this[PKG].optionalDependencies;
}
get peerDependencies() {
return this[PKG].peerDependencies;
}
/**
* Map-like retrieval of arbitrary values
* @template {keyof RawManifest} K
* @param {K} key field name to retrieve value
* @returns {RawManifest[K]} value stored under key, if present
*/
get(key) {
return this[PKG][key];
}
/**
* Map-like storage of arbitrary values
* @template {keyof RawManifest} K
* @param {T} key field name to store value
* @param {RawManifest[K]} val value to store
* @returns {Package} instance for chaining
*/
set(key, val) {
this[PKG][key] = val;
return this;
}
/**
* Provide shallow copy for munging elsewhere
* @returns {Object}
*/
toJSON() {
return shallowCopy(this[PKG]);
}
/**
* Refresh internal state from disk (e.g., changed by external lifecycles)
*/
refresh() {
return loadJsonFile(this.manifestLocation).then((pkg) => {
this[PKG] = pkg;
return this;
});
}
/**
* Write manifest changes to disk
* @returns {Promise} resolves when write finished
*/
serialize() {
return writePkg(this.manifestLocation, this[PKG]).then(() => this);
}
/**
* Mutate local dependency spec according to type
* @param {Object} resolved npa metadata
* @param {String} depVersion semver
* @param {String} savePrefix npm_config_save_prefix
*/
updateLocalDependency(resolved, depVersion, savePrefix, options = { retainWorkspacePrefix: true }) {
const depName = resolved.name;
// first, try runtime dependencies
let depCollection = this.dependencies;
// try optionalDependencies if that didn't work
if (!depCollection || !depCollection[depName]) {
depCollection = this.optionalDependencies;
}
// fall back to devDependencies
if (!depCollection || !depCollection[depName]) {
depCollection = this.devDependencies;
}
if (resolved.workspaceSpec && options.retainWorkspacePrefix) {
// do nothing if there is a workspace alias since they don't specify a version number
if (!resolved.workspaceAlias) {
const workspacePrefix = resolved.workspaceSpec.match(/^(workspace:[*~^]?)/)[0];
depCollection[depName] = `${workspacePrefix}${depVersion}`;
}
} else if (resolved.registry || resolved.type === "directory") {
// a version (1.2.3) OR range (^1.2.3) OR directory (file:../foo-pkg)
depCollection[depName] = `${savePrefix}${depVersion}`;
} else if (resolved.gitCommittish) {
// a git url with matching committish (#v1.2.3 or #1.2.3)
const [tagPrefix] = /^\D*/.exec(resolved.gitCommittish);
// update committish
const { hosted } = resolved; // take that, lint!
hosted.committish = `${tagPrefix}${depVersion}`;
// always serialize the full url (identical to previous resolved.saveSpec)
depCollection[depName] = hosted.toString({ noGitPlus: false, noCommittish: false });
} else if (resolved.gitRange) {
// a git url with matching gitRange (#semver:^1.2.3)
const { hosted } = resolved; // take that, lint!
hosted.committish = `semver:${savePrefix}${depVersion}`;
// always serialize the full url (identical to previous resolved.saveSpec)
depCollection[depName] = hosted.toString({ noGitPlus: false, noCommittish: false });
}
}
}
module.exports.Package = Package;