@exodus/stasis-core 1.0.0-beta.8 → 1.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/brotli.js CHANGED
@@ -1,14 +1,13 @@
1
- import { constants as zlibConstants } from 'node:zlib'
1
+ import { brotliCompressSync, brotliDecompressSync, constants as zlibConstants } from 'node:zlib'
2
2
 
3
+ import { Bundle } from './bundle.js'
3
4
  import { assert, isBrotliQuality, parseBrotliQuality } from './util.js'
4
5
 
5
- // Default brotli quality; 11 (max) costs far more for a marginal gain over 9.
6
- export const DEFAULT_BROTLI_QUALITY = 9
6
+ // Default brotli quality; the top levels (10, 11) cost far more time for a marginal size gain.
7
+ export const DEFAULT_BROTLI_QUALITY = 6
7
8
 
8
9
  export function brotliOptions(quality) {
9
- if (quality !== undefined) {
10
- assert(isBrotliQuality(quality), `brotli quality must be an integer 0..11, got ${quality}`)
11
- }
10
+ assert(quality === undefined || isBrotliQuality(quality), `brotli quality must be an integer 0..11, got ${quality}`)
12
11
  const raw = process.env.EXODUS_STASIS_BROTLI_QUALITY
13
12
  if (raw) {
14
13
  const n = parseBrotliQuality('EXODUS_STASIS_BROTLI_QUALITY', raw)
@@ -18,3 +17,18 @@ export function brotliOptions(quality) {
18
17
  }
19
18
  return { params: { [zlibConstants.BROTLI_PARAM_QUALITY]: quality ?? DEFAULT_BROTLI_QUALITY } }
20
19
  }
20
+
21
+ // zlib's brotli decoder ignores bytes after the stream, where DecompressionStream refuses them with this error.
22
+ export const trailingJunkError = () => Object.assign(
23
+ new TypeError('Trailing junk found after the end of the compressed stream'),
24
+ { code: 'ERR_TRAILING_JUNK_AFTER_STREAM_END' })
25
+
26
+ // The engine's bytesWritten counts the input it consumed, which stops where the stream does.
27
+ export function brotliDecompressStrict(bytes) {
28
+ const { buffer, engine } = brotliDecompressSync(bytes, { info: true })
29
+ if (engine.bytesWritten !== Buffer.byteLength(bytes)) throw trailingJunkError()
30
+ return buffer
31
+ }
32
+
33
+ export const compressBundleText = (text, quality) => brotliCompressSync(text, brotliOptions(quality))
34
+ export const parseBundleBytes = (bytes) => Bundle.parse(brotliDecompressStrict(bytes).toString('utf8'))
@@ -2,85 +2,152 @@ import { isUtf8 } from 'node:buffer'
2
2
  import { dirname, join, posix, relative, resolve } from 'node:path'
3
3
 
4
4
  import { isValidRepoField } from './bundle.js'
5
- import { posixPathEscapes } from './artifact-util.js'
5
+ import { isPackageString, isSubpackage, posixPathEscapes } from './artifact-util.js'
6
6
  import { diskHost } from './host.js'
7
- import { assertRealPathWithinBase, hasNodeModulesSegment, relativeEscapes, toPosix } from './util.js'
7
+ import { assertRealPathWithinBase, hasNodeModulesSegment, memoized, relativeEscapes, splitNodeModulesPath, toPosix } from './util.js'
8
8
 
9
- // Text as Node reads a package.json: UTF-8, past a byte order mark.
9
+ // As Node reads a package.json: UTF-8, past a byte order mark.
10
10
  const utf8 = new TextDecoder()
11
11
  export const packageJSONText = (bytes) => utf8.decode(bytes)
12
12
 
13
- export function packageType(file, host = diskHost) {
13
+ // `kept(path, read)` caches by the package.json's path (a scan reads the same one for each file under it).
14
+ export function packageType(file, host = diskHost, kept = (path, read) => read()) {
14
15
  const pkg = host.findPackageJSON(file)
15
16
  if (!pkg) return null
16
- try {
17
- const type = JSON.parse(packageJSONText(host.readFile(pkg))).type
17
+ return kept(pkg, () => {
18
+ const type = readJson(pkg, host)?.type
18
19
  return type === 'module' || type === 'commonjs' ? type : null
19
- } catch {
20
- return null
20
+ })
21
+ }
22
+
23
+ // By host package name, so any layout or alias matches. Add only a confirmed upstream layout, with its reason.
24
+ const VENDOR_DIRS = {
25
+ __proto__: null,
26
+ next: ['dist/compiled'], // the dependencies Next.js compiles in, ~140, each with a trimmed package.json
27
+ }
28
+ const VENDOR_DIR_LIST = Object.values(VENDOR_DIRS).flat()
29
+
30
+ const inAnyVendorDir = (rel) => VENDOR_DIR_LIST.some((dir) => rel.startsWith(`${dir}/`))
31
+
32
+ export const vendorDirOf = (name, rel) => VENDOR_DIRS[name]?.find((dir) => rel.startsWith(`${dir}/`))
33
+
34
+ const manifestIdentity = (pkg) => ({ name: pkg.name, ...(isPackageString(pkg.version) ? { version: pkg.version } : {}) })
35
+
36
+ // `below`: whether any package.json under `vendorDir` covers the file at all.
37
+ export function vendoredPackageOf(rel, vendorDir, read) {
38
+ let below = false
39
+ for (let dir = posix.dirname(rel); dir.startsWith(`${vendorDir}/`); dir = posix.dirname(dir)) {
40
+ const pkg = read(dir)
41
+ if (pkg === null) continue
42
+ below = true
43
+ if (pkg?.name === undefined) continue // a `{"type":"module"}` marker inside the vendored package
44
+ return isPackageString(pkg.name) ? { below, vendored: { dir, ...manifestIdentity(pkg) } } : { below }
21
45
  }
46
+ return { below }
22
47
  }
23
48
 
24
- // Nearest package.json (walking up) that identifies a bucket; pkgDir is relative to baseDir ("."
25
- // at the root). Inside node_modules both name and version are required; a workspace package
26
- // outside node_modules may omit version (the name alone claims the bucket, matching
27
- // State#locateModule), and a node_modules one's `ecosystem` (npm) and `repo`, where its `repository`
28
- // names a GitHub one (packageRepo). Null if none. A malformed one is walked past, or with `strict` throws
29
- // (its files would otherwise land in the parent package); `check`, `host`: see readPackageJson.
49
+ export function namedManifestOf(rel, read) {
50
+ for (let dir = posix.dirname(rel); dir !== '.'; dir = posix.dirname(dir)) {
51
+ const pkg = read(dir)
52
+ if (pkg?.name !== undefined) return { dir, pkg }
53
+ }
54
+ return undefined
55
+ }
56
+
57
+ // A nearer package.json than the package's own, which Node takes the file's `type` from and Metro its fields.
58
+ export function scopeManifestOf(rel, pkgDir, exists) {
59
+ if (pkgDir !== '.' && !rel.startsWith(`${pkgDir}/`)) return undefined
60
+ for (let dir = posix.dirname(rel); dir !== pkgDir && dir !== '.'; dir = posix.dirname(dir)) {
61
+ if (exists(`${dir}/package.json`)) return `${dir}/package.json`
62
+ }
63
+ return undefined
64
+ }
65
+
66
+ // In node_modules a bucket's package.json needs name and version; outside, a name alone, as State#locateModule.
67
+ // A malformed one is walked past, or with `strict` throws (its files would otherwise land in the parent's).
30
68
  export function findPackageMetadata(baseDir, fileRelPath, { strict = false, check, host = diskHost } = {}) {
69
+ const options = { strict, check, host }
70
+ const read = (rel) => readPackageJson(baseDir, rel, options)
71
+ const nm = splitNodeModulesPath(toPosix(fileRelPath))
72
+ // A file in a vendored package is its host's, as State#locateModule has it.
73
+ if (nm !== null && inAnyVendorDir(nm.rel)) {
74
+ const pkg = read(`${nm.dir}/package.json`)
75
+ const vendorDir = pkg?.name && pkg.version ? vendorDirOf(pkg.name, nm.rel) : undefined
76
+ const { below, vendored } = vendorDir === undefined ? {} : vendoredPackageOf(nm.rel, vendorDir, (sub) => read(`${nm.dir}/${sub}/package.json`))
77
+ if (below) {
78
+ const repo = packageRepo(pkg)
79
+ const { dir: sub, ...identity } = vendored ?? {}
80
+ return { pkgDir: nm.dir, name: pkg.name, version: pkg.version, ecosystem: 'npm', ...(repo === undefined ? {} : { repo }), ...(vendored === undefined ? {} : { vendored: { [sub]: identity } }) }
81
+ }
82
+ }
83
+ // A file in a subpackage is its host's too: the nearest package.json with a name is walked past.
84
+ let subpackages
85
+ let nearest = true
31
86
  for (let dir = dirname(fileRelPath); ; dir = dirname(dir)) {
32
- const pkg = readPackageJson(baseDir, toPosix(join(dir, 'package.json')), { strict, check, host })
33
- const inNodeModules = hasNodeModulesSegment(toPosix(dir))
34
- if (pkg?.name && (pkg.version || !inNodeModules)) {
87
+ const pkg = read(toPosix(join(dir, 'package.json')))
88
+ const posixDir = toPosix(dir)
89
+ const inNodeModules = hasNodeModulesSegment(posixDir)
90
+ const sub = pkg?.name && nm !== null ? hostSubpackageDir(read, nm.dir, posixDir, pkg.name) : undefined
91
+ if (sub !== undefined) {
92
+ if (nearest) subpackages = { [sub]: manifestIdentity(pkg) }
93
+ } else if (pkg?.name && (pkg.version || !inNodeModules)) {
35
94
  const repo = inNodeModules ? packageRepo(pkg) : undefined
95
+ const own = posixDir === nm?.dir ? subpackages : undefined // the subpackage's package, not one above it
36
96
  // `?? undefined` folds a literal `"version": null` into the one absent-version spelling.
37
- return { pkgDir: dir, name: pkg.name, version: pkg.version ?? undefined, ...(inNodeModules ? { ecosystem: 'npm' } : {}), ...(repo === undefined ? {} : { repo }) }
97
+ return { pkgDir: dir, name: pkg.name, version: pkg.version ?? undefined, ...(inNodeModules ? { ecosystem: 'npm' } : {}), ...(repo === undefined ? {} : { repo }), ...(own === undefined ? {} : { subpackages: own }) }
38
98
  }
39
- if (dir === '.' || dir === '/' || dir === '' || dirname(dir) === dir) return null
99
+ if (pkg?.name) nearest = false
100
+ if (dirname(dir) === dir) return null // '.' and a filesystem root are their own dirname
40
101
  }
41
102
  }
42
103
 
43
- // The error codes that mean nothing is at a path.
104
+ // Once per directory, the only thing findPackageMetadata's answer depends on.
105
+ export const packageLookup = (baseDir, options) => memoized((path) => findPackageMetadata(baseDir, path, options), (path) => posix.dirname(path))
106
+
107
+ function hostSubpackageDir(read, pkgDir, dir, manifestName) {
108
+ if (!dir.startsWith(`${pkgDir}/`)) return undefined
109
+ const sub = dir.slice(pkgDir.length + 1)
110
+ if (typeof manifestName !== 'string' || !manifestName.endsWith(`/${sub}`)) return undefined
111
+ return isSubpackage(manifestName, read(`${pkgDir}/package.json`)?.name, sub) ? sub : undefined
112
+ }
113
+
44
114
  export const NO_ENTRY = new Set(['ENOENT', 'ENOTDIR'])
45
115
 
46
- // Why `file` can't be read, where `host.stat` gave null, or null when nothing is there (a missing
47
- // path, one through a file, a link to nothing). host.stat answers null for any failure, as Node's
48
- // module lookup does; real stat tells them apart: a link loop, a directory that may not be searched
49
- // or a name too long is something there that can't be read, and a read meets the same error.
50
- function readFailure(host, file) {
116
+ // A link is not followed, a broken one counted too (`host.readlink` throws when nothing is there).
117
+ export function lexists(p, host) {
51
118
  try {
52
- host.readFile(file)
119
+ host.readlink(p)
120
+ return true
53
121
  } catch (err) {
54
- return NO_ENTRY.has(err.code) ? null : err
122
+ if (NO_ENTRY.has(err.code)) return false
123
+ throw err
55
124
  }
56
- return new Error(`${file} could be read but not stat'ed`)
57
125
  }
58
126
 
59
- // host.stat as real stat answers: null only when nothing is there (readFailure); anything else that
60
- // can't be stat'ed throws, naming the file `label`.
61
- export function statStrict(host, file, label) {
127
+ // host.stat answers null for any failure, as Node's module lookup does; this, only when nothing is there. Something
128
+ // there that can't be read (a link loop, an unsearchable directory, a too-long name) throws `fail(cause)`.
129
+ function statOrFail(host, file, fail) {
62
130
  const stat = host.stat(file)
63
131
  if (stat !== null) return stat
64
- const failure = readFailure(host, file)
65
- if (failure === null) return null
66
- throw new Error(`${label}: can't be read (${failure.code ?? failure.message})`, { cause: failure })
132
+ try {
133
+ host.readFile(file)
134
+ } catch (err) {
135
+ if (NO_ENTRY.has(err.code)) return null
136
+ throw fail(err)
137
+ }
138
+ throw fail(new Error(`${file} could be read but not stat'ed`))
67
139
  }
68
140
 
69
- // host.stat for a package.json, as Node's lookups read one: null when nothing is there, and one that
70
- // can't be read (a link loop, a directory that may not be searched) throws ERR_INVALID_PACKAGE_CONFIG,
71
- // as Node refuses it.
72
- export function packageJSONStat(host, file) {
73
- const stat = host.stat(file)
74
- if (stat !== null) return stat
75
- const cause = readFailure(host, file)
76
- if (cause === null) return null
77
- throw Object.assign(new Error(`Cannot read package config ${file}: ${cause.code ?? cause.message}.`, { cause }), { code: 'ERR_INVALID_PACKAGE_CONFIG' })
78
- }
141
+ export const statStrict = (host, file, label) =>
142
+ statOrFail(host, file, (cause) => new Error(`${label}: can't be read (${cause.code ?? cause.message})`, { cause }))
143
+
144
+ export const invalidPackageConfig = (path, cause) =>
145
+ Object.assign(new Error(`Invalid package config ${path}.`, cause === undefined ? {} : { cause }), { code: 'ERR_INVALID_PACKAGE_CONFIG' })
79
146
 
80
- // `file`'s bytes, read through `host`, or null when there's no file (a directory counts as none).
81
- // It's read only when it's a regular file: a FIFO, a socket, a device or a link to one
82
- // (`/dev/stdin`) throws, naming it `label`, rather than stalling or reading the process's input, and
83
- // so does one there that can't be read (statStrict).
147
+ export const packageJSONStat = (host, file) => statOrFail(host, file, (cause) =>
148
+ Object.assign(new Error(`Cannot read package config ${file}: ${cause.code ?? cause.message}.`, { cause }), { code: 'ERR_INVALID_PACKAGE_CONFIG' }))
149
+
150
+ // A FIFO, a socket, a device or a link to one (`/dev/stdin`) throws rather than stalling or reading the process's input.
84
151
  export function readRegularFileOrNull(file, label, host = diskHost) {
85
152
  const stat = statStrict(host, file, label)
86
153
  if (stat === null || stat.isDirectory()) return null
@@ -88,24 +155,17 @@ export function readRegularFileOrNull(file, label, host = diskHost) {
88
155
  return host.readFile(file)
89
156
  }
90
157
 
91
- // The package.json at `rel` (under `baseDir`), parsed (a leading byte-order mark skipped, as npm
92
- // and Node skip it), read through `host`; null when there's none (a directory counts as none), or
93
- // when it doesn't parse, isn't a regular file or can't be read -- unless `strict`, then that throws
94
- // (only nothing there is no package.json, as Node reads one: statStrict), saying where
95
- // with the parser's line and column but never its message, which quotes the text (a file that isn't
96
- // JSON may be anything, a secret included). `check(rel)`, when given, sees the path before it is
97
- // read, and may throw to refuse it.
158
+ // Parsed past a BOM, as npm and Node; null when there's none or it can't be read, isn't a regular file or doesn't
159
+ // parse -- unless `strict`: then only nothing there is null. `check(rel)` sees the path before it is read.
98
160
  export function readPackageJson(baseDir, rel, { strict = false, check, host = diskHost } = {}) {
99
161
  const file = join(baseDir, rel)
100
162
  const stat = strict ? statStrict(host, file, rel) : host.stat(file)
101
163
  if (stat === null || stat.isDirectory()) return null
102
164
  check?.(rel)
103
165
  try {
104
- // A FIFO, a socket or a device (or a link to one) is never read: it could stall the bundle.
105
166
  if (!stat.isFile()) throw new Error(`${rel}: not a regular file`)
106
167
  const bytes = host.readFile(file)
107
- // Strict, it's read as the file's own text or not at all; lenient lookups decode it as they always
108
- // have (a stray byte as U+FFFD).
168
+ // Lenient lookups decode it as they always have (a stray byte as U+FFFD).
109
169
  if (strict && !isUtf8(bytes)) throw new Error(`${rel}: not valid UTF-8`)
110
170
  return parseJson(packageJSONText(bytes), rel)
111
171
  } catch (err) {
@@ -114,8 +174,7 @@ export function readPackageJson(baseDir, rel, { strict = false, check, host = di
114
174
  }
115
175
  }
116
176
 
117
- // JSON.parse, throwing where the text breaks (the parser's line and column) but never the parser's
118
- // message, which quotes the text.
177
+ // Never the parser's message, which quotes the text (a file that isn't JSON may be anything, a secret included).
119
178
  function parseJson(text, rel) {
120
179
  try {
121
180
  return JSON.parse(text)
@@ -135,8 +194,7 @@ export function normalizeEntries(entries, cwd) {
135
194
  })
136
195
  }
137
196
 
138
- // Bytes of a bundled module's `package.json`, or null to skip when it's absent; one that can't be
139
- // read (statStrict) or isn't UTF-8 aborts (never silently skipped).
197
+ // One that can't be read or isn't UTF-8 aborts, never silently skipped.
140
198
  export function readModuleManifest({ baseDir, realBase, rel, host = diskHost } = {}) {
141
199
  const absolute = join(baseDir, rel)
142
200
  if (statStrict(host, absolute, rel) === null) return null
@@ -155,30 +213,24 @@ export function readJson(file, host = diskHost) {
155
213
  }
156
214
  }
157
215
 
158
- // `owner/name` from a package.json `repository` (GitHub URL or shorthand), else null. A `#committish`
159
- // npm lets it name is no part of the repo; a URL's userinfo holds only what RFC 3986 allows there, so
160
- // a `?` or `\` ending the authority early (`https://evil.example?@github.com/a/b`) isn't GitHub's. An
161
- // scp-like `git@github.com:owner/name` is taken behind an `ssh://` too (`git+ssh://git@github.com:o/n`),
162
- // as package.json files spell it.
216
+ // Userinfo holds only what RFC 3986 allows: a `?` or `\` ending the authority early isn't GitHub's
217
+ // (`https://evil.example?@github.com/a/b`). scp-like `git@github.com:o/n` is taken behind `ssh://` too.
163
218
  export function parseGithubRepository(url) {
164
219
  if (typeof url !== 'string') return null
165
- const match = /^(?:github:|(?:git\+)?(?:(?:https?|ssh|git):\/\/(?:[\w.~%!$&'()*+,;=:-]*@)?github\.com(?::\d+)?\/|ssh:\/\/(?:[\w.~%!$&'()*+,;=-]*@)?github\.com:|(?:[^@/:]+@)?github\.com:))?([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/iu.exec(url.trim().replace(/#.*$/su, ''))
166
- // Must also pass the bundle format's `github` check.
220
+ const match = /^(?:github:|(?:git\+)?(?:(?:https?|ssh|git):\/\/(?:[\w.~%!$&'()*+,;=:-]*@)?(?:www\.)?github\.com(?::\d+)?\/|ssh:\/\/(?:[\w.~%!$&'()*+,;=-]*@)?(?:www\.)?github\.com:|(?:[^@/:]+@)?(?:www\.)?github\.com:))?([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/iu.exec(url.trim().replace(/#.*$/su, ''))
167
221
  const github = match && `${match[1]}/${match[2]}`
168
222
  return github && isValidRepoField('github', github) ? github : null
169
223
  }
170
224
 
171
- // Best-effort `origin` url: literal match of git's own `.git/config` layout, no parsing.
225
+ // A literal match of git's own `.git/config` layout, no parsing.
172
226
  const GIT_ORIGIN_URL = '[remote "origin"]\n\turl = '
173
227
  export function gitOriginUrl(text) {
174
228
  const at = text?.indexOf(GIT_ORIGIN_URL) ?? -1
175
229
  if (at === -1) return null
176
- const start = at + GIT_ORIGIN_URL.length
177
- const end = text.indexOf('\n', start)
178
- return text.slice(start, end === -1 ? undefined : end).trim() || null
230
+ return text.slice(at + GIT_ORIGIN_URL.length).split('\n', 1)[0].trim() || null
179
231
  }
180
232
 
181
- // The text of `file`, or null. Read through `host` (never the --fs-patched fs), it is never captured.
233
+ // Read through `host` (never the --fs-patched fs), it is never captured.
182
234
  export const readText = (host, file) => {
183
235
  try {
184
236
  return host.readFile(file).toString('utf8')
@@ -187,7 +239,7 @@ export const readText = (host, file) => {
187
239
  }
188
240
  }
189
241
 
190
- // Dir of a `https://github.com/<github>/tree/<branch>/<dir>` homepage (one-segment branch).
242
+ // The branch is taken as one segment: one holding a `/` reads as part of the dir.
191
243
  export function githubHomepageDirectory(homepage, github) {
192
244
  if (typeof homepage !== 'string') return undefined
193
245
  const match = /^https?:\/\/(?:www\.)?github\.com\/([^/]+\/[^/]+)\/tree\/[^/#?]+\/([^#?]+)/iu.exec(homepage.trim())
@@ -199,17 +251,12 @@ export function githubHomepageDirectory(homepage, github) {
199
251
  }
200
252
  }
201
253
 
202
- // `{ directory }` where it is a valid one, else `{}`.
203
254
  const repoLocation = (directory) => (isValidRepoField('directory', directory) ? { directory } : {})
204
255
 
205
- // Whether a declared path is the repository's root: nothing but empty and `.` parts (`./`, `/.`).
206
256
  const isRootPath = (path) => path.replaceAll('\\', '/').split('/').every((part) => part === '' || part === '.')
207
257
 
208
- // A package.json's declared `base` (its `repository.directory`) joined with `rel` as a `repoLocation`;
209
- // `{}` where none is declared (unknown, not the root), or where `base` has a `..` part, whatever it
210
- // would come to (`a/..` is no claim on the root). Its empty and `.` parts are dropped, and one that
211
- // comes to the root (`''`, `.`, `./`, `/`, `/.`) is the root, `''`. Windows users write `base` with
212
- // `\`: metadata, not a name on disk, so its `\` is taken for a separator.
258
+ // `{}` where none is declared (unknown, not the root) or `base` has a `..` part (`a/..` is no claim on the root).
259
+ // Its `\` is a separator: Windows users write it so, and it is metadata, not a name on disk.
213
260
  const declaredLocation = (base, rel) => {
214
261
  if (typeof base !== 'string') return {}
215
262
  const path = base.replaceAll('\\', '/')
@@ -218,7 +265,6 @@ const declaredLocation = (base, rel) => {
218
265
  return repoLocation(directory === '.' ? '' : directory)
219
266
  }
220
267
 
221
- // Git and common dirs, following a worktree/submodule `.git` file.
222
268
  function gitDirs(dotGit, host) {
223
269
  const pointer = readText(host, dotGit) // null for a `.git` directory (EISDIR)
224
270
  const gitDir = pointer?.startsWith('gitdir: ') ? resolve(dirname(dotGit), pointer.slice('gitdir: '.length).trim()) : dotGit
@@ -226,7 +272,6 @@ function gitDirs(dotGit, host) {
226
272
  return { gitDir, commonDir: common ? resolve(gitDir, common) : gitDir }
227
273
  }
228
274
 
229
- // HEAD's commit: detached sha, loose ref, or packed-refs; undefined unless a valid sha.
230
275
  function gitHeadCommit({ gitDir, commonDir }, host) {
231
276
  const head = readText(host, join(gitDir, 'HEAD'))?.trim()
232
277
  if (!head) return undefined
@@ -240,22 +285,23 @@ function gitHeadCommit({ gitDir, commonDir }, host) {
240
285
  return isValidRepoField('commit', commit) ? commit : undefined
241
286
  }
242
287
 
243
- // A parsed package.json's `repository` url (the string shorthand, or its `url`), or undefined.
288
+ // Read through `host`, under `.git` alone; git never runs.
289
+ export function checkoutCommit(dir, host = diskHost) {
290
+ const dotGit = join(dir, '.git')
291
+ return host.stat(dotGit) === null ? undefined : gitHeadCommit(gitDirs(dotGit, host), host)
292
+ }
293
+
244
294
  function repositoryUrl(json) {
245
295
  const repository = json?.repository
246
296
  const url = typeof repository === 'string' ? repository : repository?.url
247
297
  return typeof url === 'string' ? url : undefined
248
298
  }
249
299
 
250
- // The `repo` a parsed package.json's `repository` names for `rel`, a directory below it ('' for its
251
- // own): `github` from its GitHub URL or shorthand, and `directory` from `repository.directory` joined
252
- // with `rel` (declaredLocation); undefined where it names no GitHub repository.
253
- export function packageRepo(json, rel = '') {
300
+ function declaredRepo(json, rel) {
254
301
  const github = parseGithubRepository(repositoryUrl(json))
255
302
  if (!github) return undefined
256
303
  let base = json.repository.directory
257
- // Often unset; fall back to a GitHub tree `homepage`, which places a package below the root, never
258
- // at it: only `repository.directory` declares the root (`/tree/main/.` declares nothing).
304
+ // Often unset; a GitHub tree `homepage` places a package below the root, never at it (`/tree/main/.` declares nothing).
259
305
  if (typeof base !== 'string') {
260
306
  base = githubHomepageDirectory(json.homepage, github)
261
307
  if (base !== undefined && isRootPath(base)) base = undefined
@@ -263,8 +309,13 @@ export function packageRepo(json, rel = '') {
263
309
  return { github, ...declaredLocation(base, rel) }
264
310
  }
265
311
 
266
- // Bundle `repo` for `dir`: git origin/HEAD at the work tree root, with `dir`'s place in it (`''` at
267
- // the root), else nearest package.json `repository` (packageRepo).
312
+ // lerna writes `gitHead` into package.json too (npm publish only into the registry's document), and npm keeps it.
313
+ export function packageRepo(json) {
314
+ const repo = declaredRepo(json, '')
315
+ return repo !== undefined && isValidRepoField('commit', json.gitHead) ? { ...repo, commit: json.gitHead } : repo
316
+ }
317
+
318
+ // Its commit is git's HEAD alone, never a package.json's `gitHead`: a project's own files likely changed since.
268
319
  export function detectRepo(dir, host = diskHost) {
269
320
  const start = resolve(dir)
270
321
  let pkg = null // null: no package.json `repository` seen yet; undefined: one seen, not GitHub
@@ -272,17 +323,16 @@ export function detectRepo(dir, host = diskHost) {
272
323
  const rel = toPosix(relative(cursor, start))
273
324
  if (pkg === null) {
274
325
  const json = readJson(join(cursor, 'package.json'), host)
275
- if (repositoryUrl(json) !== undefined) pkg = packageRepo(json, rel)
326
+ if (repositoryUrl(json) !== undefined) pkg = declaredRepo(json, rel)
276
327
  }
277
328
  const dotGit = join(cursor, '.git')
278
329
  if (host.stat(dotGit) !== null) {
279
330
  const dirs = gitDirs(dotGit, host)
280
331
  const github = parseGithubRepository(gitOriginUrl(readText(host, join(dirs.commonDir, 'config'))))
281
- if (github) return stripUndefined({ github, ...repoLocation(rel), commit: gitHeadCommit(dirs, host) })
282
- return pkg ?? undefined
332
+ if (!github) return pkg ?? undefined
333
+ const commit = gitHeadCommit(dirs, host)
334
+ return { github, ...repoLocation(rel), ...(commit === undefined ? {} : { commit }) }
283
335
  }
284
336
  if (dirname(cursor) === cursor) return pkg ?? undefined
285
337
  }
286
338
  }
287
-
288
- const stripUndefined = (obj) => Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined))