codekingpro/portable-devtools
114k
1// take a path and a resolved value, and turn it into a resolution from
2// the given new path. This is used with converting a package.json's
3// relative file: path into one suitable for a lockfile, or between
4// lockfiles, and for converting hosted git repos to a consistent url type.
5const npa = require('npm-package-arg')
6const relpath = require('./relpath.js')
7const consistentResolve = (resolved, fromPath, toPath, relPaths = false) => {
8 if (!resolved) {
9 return null
10 }
11
12 try {
13 const hostedOpt = { noCommittish: false }
14 const {
15 fetchSpec,
16 saveSpec,
17 type,
18 hosted,
19 rawSpec,
20 raw,
21 } = npa(resolved, fromPath)
22 if (type === 'file' || type === 'directory') {
23 if (relPaths && toPath) {
24 return `file:${relpath(toPath, fetchSpec)}`
25 }
26 return `file:${fetchSpec}`
27 }
28 if (hosted) {
29 return `git+${hosted.auth ? hosted.https(hostedOpt) : hosted.sshurl(hostedOpt)}`
30 }
31 if (type === 'git') {
32 return saveSpec
33 }
34 if (rawSpec === '*') {
35 return raw
36 }
37 return rawSpec
38 } catch (_) {
39 // whatever we passed in was not acceptable to npa.
40 // leave it 100% untouched.
41 return resolved
42 }
43}
44module.exports = consistentResolve
45 