@preventive/deptree 1.0.0-alpha.1 → 1.0.0-alpha.11

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.
Files changed (89) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/bin/compare.js +132 -0
  3. package/bin/deptree.js +211 -0
  4. package/bin/npmrc.js +21 -0
  5. package/cargo.d.ts +223 -0
  6. package/cargo.js +6 -0
  7. package/npm.d.ts +325 -0
  8. package/npm.js +7 -0
  9. package/package.json +92 -11
  10. package/pnpm.d.ts +401 -81
  11. package/pnpm.js +4 -9
  12. package/soldeer.d.ts +235 -0
  13. package/soldeer.js +6 -0
  14. package/src/cargo/crate.js +183 -0
  15. package/src/cargo/inputs.js +81 -0
  16. package/src/cargo/members.js +90 -0
  17. package/src/cargo/registry.js +65 -0
  18. package/src/cargo/tree.js +125 -0
  19. package/src/cargo/workspace.js +177 -0
  20. package/src/concurrent.js +32 -0
  21. package/src/error.js +8 -10
  22. package/src/glob.js +55 -0
  23. package/src/hash.js +51 -16
  24. package/src/manifest.js +52 -0
  25. package/src/matcher.js +60 -10
  26. package/src/mount.js +124 -42
  27. package/src/npm/bins.js +54 -0
  28. package/src/npm/compat.js +97 -0
  29. package/src/npm/dev-engines.js +52 -0
  30. package/src/npm/graph.js +68 -0
  31. package/src/npm/inputs.js +75 -0
  32. package/src/npm/manifests.js +130 -0
  33. package/src/npm/package.js +96 -0
  34. package/src/npm/ratio.js +34 -0
  35. package/src/npm/settings.js +67 -0
  36. package/src/npm/tree.js +139 -0
  37. package/src/npm/versions.js +20 -0
  38. package/src/npmrc.js +24 -0
  39. package/src/patch.js +26 -45
  40. package/src/pnpm/bins.js +202 -322
  41. package/src/pnpm/checks.js +8 -35
  42. package/src/pnpm/commands.js +230 -0
  43. package/src/pnpm/filename.js +19 -16
  44. package/src/pnpm/frozen.js +29 -73
  45. package/src/pnpm/gitignore.js +138 -0
  46. package/src/pnpm/glob.js +65 -0
  47. package/src/pnpm/graph.js +26 -34
  48. package/src/pnpm/hoist.js +96 -59
  49. package/src/pnpm/hoisted.js +234 -0
  50. package/src/pnpm/hook.js +26 -31
  51. package/src/pnpm/inputs.js +177 -0
  52. package/src/pnpm/install.js +123 -124
  53. package/src/pnpm/local.js +95 -40
  54. package/src/pnpm/minimatch.js +319 -0
  55. package/src/pnpm/nm-hoist-graph.js +299 -0
  56. package/src/pnpm/nm-hoist.js +149 -0
  57. package/src/pnpm/npm-packlist.js +217 -0
  58. package/src/pnpm/overrides.js +11 -51
  59. package/src/pnpm/package.js +123 -0
  60. package/src/pnpm/packlist.js +176 -81
  61. package/src/pnpm/patches.js +18 -25
  62. package/src/pnpm/projects.js +132 -89
  63. package/src/pnpm/readers.js +122 -77
  64. package/src/pnpm/settings.js +74 -95
  65. package/src/pnpm/tree.js +216 -237
  66. package/src/pnpm/uptodate.js +16 -28
  67. package/src/pnpm/workspace.js +152 -126
  68. package/src/project.js +56 -0
  69. package/src/soldeer/config.js +63 -0
  70. package/src/soldeer/git.js +52 -0
  71. package/src/soldeer/inputs.js +30 -0
  72. package/src/soldeer/tree.js +83 -0
  73. package/src/soldeer/zip.js +121 -0
  74. package/src/tarball.js +123 -131
  75. package/src/yarn1/bins.js +28 -0
  76. package/src/yarn1/compat.js +67 -0
  77. package/src/yarn1/hoist.js +249 -0
  78. package/src/yarn1/inputs.js +83 -0
  79. package/src/yarn1/manifest.js +64 -0
  80. package/src/yarn1/package.js +206 -0
  81. package/src/yarn1/peers.js +51 -0
  82. package/src/yarn1/requests.js +74 -0
  83. package/src/yarn1/resolve.js +289 -0
  84. package/src/yarn1/settings.js +95 -0
  85. package/src/yarn1/tree.js +219 -0
  86. package/yarn1.d.ts +368 -0
  87. package/yarn1.js +7 -0
  88. package/src/pnpm/npmrc.js +0 -31
  89. /package/{LICENSE → LICENSE-MIT} +0 -0
package/soldeer.d.ts ADDED
@@ -0,0 +1,235 @@
1
+ // Hand-written against soldeer.js; a change to either belongs with the other.
2
+
3
+ import type { Client } from '@preventive/upstream/github.js'
4
+ import type { NodeType, Vfs } from '@preventive/vfs'
5
+
6
+ export { LockfileError, TomlError } from '@preventive/lockfile/soldeer.js'
7
+
8
+ // Where @preventive/upstream caches what it fetches, zips and GitHub's
9
+ // tarballs among them. Both are fetched through it, and that is the one
10
+ // place anything here touches a filesystem: from its cache, where one is
11
+ // set, which is where it writes each it fetches — setCacheDir() sets the
12
+ // default one, and setCacheDir(false) unsets it; unset, which it is until
13
+ // set, it has none, and writes nothing. Soldeer's own folders are never
14
+ // read. The project is read only through the view given as `project`, and
15
+ // the tree built in a Vfs.
16
+ export { setCacheDir } from '@preventive/upstream/npm.js'
17
+
18
+ // The machine Soldeer would install on: `soldeer` is the version that
19
+ // installs, on its own or as `forge soldeer`, and has to be 0.12.0, which
20
+ // extracts zips otherwise than 0.11 and older; `os` as Node names it —
21
+ // `linux`, `darwin`. Windows is refused: Soldeer names folders and reads
22
+ // paths in zips otherwise there.
23
+ export interface SoldeerHost {
24
+ soldeer: string
25
+ os: string
26
+ }
27
+
28
+ // A view of the project's root, by paths from `/`: a Vfs, or anything
29
+ // with its readdir, lstat, stat and readFile, such as one of a directory
30
+ // on disk, of which only soldeer.lock, foundry.toml and, where there is
31
+ // no foundry.toml, soldeer.toml are read there, as Soldeer reads them,
32
+ // each as UTF-8, and refused where it is not. Nothing is written to it.
33
+ export interface SoldeerProject {
34
+ readdir(path: string): string[]
35
+ lstat(path: string): { type: NodeType }
36
+ stat(path: string): { type: NodeType }
37
+ readFile(path: string): Uint8Array
38
+ }
39
+
40
+ // The files an install reads at the project's root: soldeer.lock, and
41
+ // foundry.toml and soldeer.toml, where they are.
42
+ //
43
+ // Of the two, the config is the one Soldeer reads: foundry.toml, where it
44
+ // has a [dependencies] table, written as one rather than inline; else
45
+ // soldeer.toml, where there is no foundry.toml. Where neither holds, which
46
+ // is so of a foundry.toml with no such table, whatever soldeer.toml there
47
+ // is, Soldeer asks which file to make its config, and that is refused. Of
48
+ // foundry.toml, what Soldeer fails on as it adds `dependencies` to the
49
+ // default profile's libs is refused: a profile or profile.default that is
50
+ // not a table, or written inline, and libs that are not an array. Of the
51
+ // config's [soldeer] settings, a value of a type Soldeer fails on is
52
+ // refused, and so is recursive_deps = true, which has Soldeer install what
53
+ // each dependency depends on too; the others change nothing beneath
54
+ // dependencies/, and any other key is passed over, as Soldeer passes it
55
+ // over. A config whose `dependencies` is inline, which Soldeer reads none
56
+ // from, is refused.
57
+ //
58
+ // The two ways the files come, one or the other: given, with `lockfile`
59
+ // and, where they are, `foundry` and `soldeer`; or read, with `project`
60
+ // and none of them.
61
+ //
62
+ // `vfs` is a Vfs to mount the tree into, at its root, which is taken to be
63
+ // the project's — it may be `project` too; without one, a new Vfs holds
64
+ // the tree alone. A Vfs that holds a `dependencies` at its root, or on
65
+ // macOS a name that is one there, is refused before anything is fetched,
66
+ // as Soldeer would keep or remove what is in it by what it holds. Nothing
67
+ // there is written over: each directory the tree has is one there or is
68
+ // made, and every file is written where nothing is. The tree is built, and
69
+ // held to every check below, before any of it is written, so a refusal
70
+ // leaves the Vfs as it was.
71
+ //
72
+ // `github` is the client from @preventive/upstream/github.js's createClient
73
+ // each git dependency is fetched through, with whatever token it was made
74
+ // with, or none. It is needed only where the lockfile has a git dependency,
75
+ // and there it is a TypeError to leave it out, before anything is fetched.
76
+ export type SoldeerTreeOptions = SoldeerTreeGiven | SoldeerTreeRead
77
+
78
+ export interface SoldeerTreeGiven {
79
+ lockfile: string
80
+ foundry?: string
81
+ soldeer?: string
82
+ project?: undefined
83
+ host: SoldeerHost
84
+ vfs?: Vfs
85
+ github?: Client
86
+ }
87
+
88
+ export interface SoldeerTreeRead {
89
+ lockfile?: undefined
90
+ foundry?: undefined
91
+ soldeer?: undefined
92
+ project: SoldeerProject
93
+ host: SoldeerHost
94
+ vfs?: Vfs
95
+ github?: Client
96
+ }
97
+
98
+ // What buildSoldeerTree counts, all of it plain numbers: `dependencies`
99
+ // those installed, each a zip or a tarball fetched; `files` and `bytes`
100
+ // what is written, and `links` the symlinks, which git dependencies alone
101
+ // have, as a zip's are written as files.
102
+ export interface SoldeerTreeStats {
103
+ dependencies: number
104
+ files: number
105
+ bytes: number
106
+ links: number
107
+ }
108
+
109
+ // A dependency in the tree, as an SBOM would list it: `path` is its
110
+ // folder, from the project's root, which is `/` of the Vfs —
111
+ // dependencies/<name>-<version>; `name` and `version` the lockfile's, as
112
+ // the registry has them, or for a git dependency, the config's. From the
113
+ // registry, `checksum` is the hex sha256 its zip is held to; from git,
114
+ // `git` is the repository's URL and `rev` the commit, as the lockfile has
115
+ // them, and `commit` that commit again, as the other trees name one.
116
+ export type SoldeerInstalled = SoldeerInstalledZip | SoldeerInstalledGit
117
+
118
+ export interface SoldeerInstalledZip {
119
+ path: string
120
+ name: string
121
+ version: string
122
+ checksum: string
123
+ }
124
+
125
+ export interface SoldeerInstalledGit {
126
+ path: string
127
+ name: string
128
+ version: string
129
+ git: string
130
+ rev: string
131
+ commit: string
132
+ }
133
+
134
+ // `vfs` is the one given, the tree mounted into it, or a new one.
135
+ // `installed` is each dependency, in the lockfile's order.
136
+ export interface SoldeerTree {
137
+ vfs: Vfs
138
+ stats: SoldeerTreeStats
139
+ installed: SoldeerInstalled[]
140
+ }
141
+
142
+ // The dependencies folder `soldeer install` makes from the lockfile, with
143
+ // host.soldeer, in a project with no dependencies folder yet: rooted at
144
+ // the project's root, it holds `dependencies/<name>-<version>` for each
145
+ // dependency, and nothing else of the project. What Soldeer writes beside
146
+ // it — the lockfile again, remappings, foundry.toml's libs — is not
147
+ // written, and where writing it fails after the install, as Soldeer may on
148
+ // a remappings.txt it does not read, that is not followed.
149
+ //
150
+ // Each registry dependency's zip is fetched from Soldeer's registry, as
151
+ // Soldeer 0.12 asks for it anew rather than taking the lockfile's URL,
152
+ // and held to the lockfile's checksum, its sha256. It is extracted as
153
+ // Soldeer extracts it, with the zip crate, into a folder of its own: no
154
+ // root folder taken off; of two entries of one name, the later alone,
155
+ // where the first was; anything under a `.git` passed over, as Windows
156
+ // reads the name — trailing dots and spaces dropped, ASCII letters in
157
+ // either case; each symlink written as a file holding its target. Each
158
+ // directory is 0o755; each file's mode is its Unix mode as the zip crate
159
+ // reads it — from the upper half of its external attributes, by whatever
160
+ // system made it, or none at all for Unix where that is 0, else for MS-DOS
161
+ // from its read-only bit — without the
162
+ // type, setuid, setgid, sticky and group and other write bits; or 0o644,
163
+ // where the zip crate reads none, or for a symlink, or for a file written
164
+ // again by a name the zip crate reads no mode of, the mode it had. Both
165
+ // are as a umask of 0o022 leaves them. The lockfile's integrity, which
166
+ // Soldeer records anew as it installs and does not check, is not checked.
167
+ //
168
+ // The lockfile is held to what the lockfile reader holds it to, with the
169
+ // config: each dependency has its entry, which Soldeer installs it from,
170
+ // and each entry a dependency. And to more than Soldeer holds it to: a zip
171
+ // is read with @preventive/archive/zip.js, which refuses what it does not
172
+ // read — a `..`, absolute or backslashed name, one starting with a drive
173
+ // letter, zip64, encryption, an entry inside one that is not a directory,
174
+ // two entries of one name that differ, a directory by its name or its
175
+ // attributes and not by the other, entries that come to more than 512
176
+ // MiB — where Soldeer would take some of it;
177
+ // and what the zip crate reads otherwise than the archive reader is
178
+ // refused: a name with a byte past ASCII that is not flagged UTF-8, which
179
+ // it reads as CP437, and an AES or a Unicode comment extra field. What
180
+ // Soldeer fails on is refused: a name with a `:` in it, an NTFS extra
181
+ // field or an extended timestamp the zip crate does not read. A folder
182
+ // Soldeer downloads another dependency's zip into, `<folder>.zip`, is
183
+ // refused. On macOS, two names in one directory that differ only in case
184
+ // or normalization are refused, as they would be one name there, and so
185
+ // is a folder that is one there with another dependency's zip.
186
+ //
187
+ // A git dependency Soldeer clones, `git clone` of the lockfile's `git`,
188
+ // then `git checkout` of its `rev`; here it is fetched from a GitHub
189
+ // repository alone, by `github`, as GitHub's tarball of the tree of that
190
+ // commit, which upstream holds to the tree GitHub names for the commit. It
191
+ // is written as a checkout with no git config and a umask of 0o022 writes
192
+ // it: each directory 0o755, each file 0o644, or 0o755 where git has it
193
+ // executable; each symlink a symlink to its target, as git has it; a
194
+ // submodule an empty directory, as Soldeer leaves it without
195
+ // recursive_deps; a file the tree's .gitattributes mark `eol=crlf` with
196
+ // CRLF, as upstream reads them. The .git a clone has is not written, so
197
+ // nothing of the repository's history is there; nor is what git config on
198
+ // the machine would change, `core.autocrlf` or a filter such as Git LFS's.
199
+ // Its folder is the config's name and version, which Soldeer's
200
+ // sanitize_filename has to leave as they are. The `git` is the
201
+ // repository's URL over https or ssh, as git takes it —
202
+ // `https://github.com/<owner>/<name>`,
203
+ // `ssh://git@github.com/<owner>/<name>` or
204
+ // `git@github.com:<owner>/<name>`, `.git` after or not; git's http and git
205
+ // protocols, which Soldeer has git refuse, are refused. GitHub's tarball
206
+ // is refused where upstream refuses it — a tree with files marked
207
+ // `export-ignore`, `ident` or `working-tree-encoding`, from a repo set to
208
+ // include Git LFS objects in archives — and where the tar reader of
209
+ // @preventive/archive/tar.js does, as for a symlink whose target climbs
210
+ // out of the tarball; so is a path with a `.git` in it, in any case, which
211
+ // git refuses to check out. That the repository's branches and tags still
212
+ // reach the commit, without which Soldeer's clone does not have it, is not
213
+ // checked: GitHub answers for any commit it has.
214
+ //
215
+ // Dependencies come from Soldeer's registry, each by a name and a version
216
+ // the registry takes, or from GitHub: one from another git host, from a
217
+ // URL the config gives, or one the registry keeps private, which it hands
218
+ // out to those signed in alone, is refused.
219
+ //
220
+ // Nothing is left to a guess: a lockfile the lockfile reader refuses, a
221
+ // config this does not read as Soldeer reads it, a dependency from
222
+ // anywhere but the registry or GitHub, a check above that fails — each is
223
+ // refused with a DeptreeError, a LockfileError or a TomlError that says
224
+ // where. A TypeError is thrown for options of the wrong type, and for a
225
+ // git dependency without `github`.
226
+ export function buildSoldeerTree(options: SoldeerTreeOptions): Promise<SoldeerTree>
227
+
228
+ // `where` is what a refusal is about — `foundry.toml: profile.default`,
229
+ // `dependencies["forge-std"]`, an entry of a zip — or undefined for the
230
+ // call as a whole; the message leads with it. `cause` is what a package
231
+ // beneath refused with, where one did.
232
+ export class DeptreeError extends Error {
233
+ constructor(detail: string, where?: string, options?: { cause?: unknown })
234
+ where: string | undefined
235
+ }
package/soldeer.js ADDED
@@ -0,0 +1,6 @@
1
+ // The dependencies folder built in memory from a soldeer.lock, as Soldeer
2
+ // 0.12 installs it; see soldeer.d.ts.
3
+ export { buildSoldeerTree } from './src/soldeer/tree.js'
4
+ export { DeptreeError } from './src/error.js'
5
+ export { setCacheDir } from '@preventive/upstream/npm.js'
6
+ export { LockfileError, TomlError } from '@preventive/lockfile/soldeer.js'
@@ -0,0 +1,183 @@
1
+ // A .crate as `cargo vendor` unpacks it into vendor/, cargo 1.94 to 1.99:
2
+ // registry/mod.rs's unpack, through vendor.rs's vendor_this; what the archive
3
+ // reader takes and cargo would read otherwise is refused. As a 0o022 umask
4
+ // leaves them, each directory is 0o755 unless its own entry gives a mode, and
5
+ // each file its mode within 0o777, both without group and other write bits.
6
+
7
+ import { crc32 } from '@exodus/bytes/crc.js'
8
+ import { utf8fromString, utf8toString } from '@exodus/bytes/utf8.js'
9
+ import { CompressionError, decompress } from '@preventive/archive/compression.js'
10
+ import { ArchiveError, unpack } from '@preventive/archive/tar.js'
11
+ import { compareNames } from '@preventive/vfs/path.js'
12
+ import { DeptreeError, quote } from '../error.js'
13
+ import { bytesSha256Hex } from '../hash.js'
14
+ import { own } from '../manifest.js'
15
+
16
+ // Cargo's bound on what a .crate unpacks to: 512 MiB, or twenty times the
17
+ // .crate where that is more.
18
+ const unpackLimit = (bytes) => Math.max(512 * 1024 * 1024, bytes.length * 20)
19
+ const [FTEXT, FEXTRA, FNAME, FCOMMENT] = [0x01, 0x04, 0x08, 0x10]
20
+
21
+ // Where the gzip member's deflate data starts, past its header: a header CRC
22
+ // or a reserved flag, which a reader may take or not, is refused.
23
+ function deflateStart(bytes, where) {
24
+ if (bytes.length < 18 || bytes[0] !== 0x1f || bytes[1] !== 0x8b || bytes[2] !== 0x08) throw new DeptreeError('the .crate is not gzipped', where)
25
+ const flags = bytes[3]
26
+ if (flags & ~(FTEXT | FEXTRA | FNAME | FCOMMENT)) throw new DeptreeError('a gzip header with a header CRC or a reserved flag is not supported', where)
27
+ let at = 10
28
+ if (flags & FEXTRA) at += 2 + (bytes[at] | (bytes[at + 1] << 8))
29
+ for (const flag of [FNAME, FCOMMENT]) {
30
+ if (!(flags & flag)) continue
31
+ const end = bytes.indexOf(0, at)
32
+ at = end === -1 ? bytes.length : end + 1
33
+ }
34
+ if (at > bytes.length - 8) throw new DeptreeError('the .crate\'s gzip header runs past its end', where)
35
+ return at
36
+ }
37
+
38
+ // flate2's GzDecoder, which cargo reads a .crate through, reads its first
39
+ // gzip member alone, where the platform's stream reads on into any after it;
40
+ // so the first has to be all of it. Its deflate data has to end where its
41
+ // eight-byte trailer starts, which deflate-raw holds it to, refusing what
42
+ // follows; and the trailer has to be the data's CRC-32 and length, as flate2
43
+ // checks them.
44
+ async function gunzip(bytes, where) {
45
+ const start = deflateStart(bytes, where)
46
+ const limit = unpackLimit(bytes)
47
+ let tar
48
+ try {
49
+ tar = await decompress(bytes.subarray(start, bytes.length - 8), 'deflate-raw', { limit })
50
+ } catch (error) {
51
+ if (!(error instanceof CompressionError)) throw error
52
+ throw new DeptreeError(error.limited ? `the .crate unpacks to more than ${limit} bytes, which cargo refuses` : 'the .crate is not one gzip member, which cargo reads the first of alone', where, { cause: error })
53
+ }
54
+ const trailer = new DataView(bytes.buffer, bytes.byteOffset + bytes.length - 8, 8)
55
+ if (trailer.getUint32(0, true) !== crc32(tar) || trailer.getUint32(4, true) !== tar.length >>> 0) throw new DeptreeError('the .crate\'s gzip trailer does not match its data', where)
56
+ return tar
57
+ }
58
+
59
+ function entriesOf(tar, where) {
60
+ try {
61
+ return unpack(tar)
62
+ } catch (error) {
63
+ if (error instanceof ArchiveError) throw new DeptreeError(`the .crate cannot be read: ${error.message}`, where, { cause: error })
64
+ throw error
65
+ }
66
+ }
67
+
68
+ // vendor_this: a `.git` anywhere on the way, a .gitattributes or .gitignore
69
+ // by name, .cargo-ok at the root; each is passed over before its type is
70
+ // looked at, unlike unpack's own .cargo-ok anywhere, after it.
71
+ const vendored = (segments, last) => !segments.includes('.git') && last !== '.gitattributes' && last !== '.gitignore' && segments.join('/') !== '.cargo-ok'
72
+
73
+ const modeOf = (entry) => entry.mode & 0o777 & ~0o022
74
+ const unsupported = (entry, why, here) => new DeptreeError(`mode ${entry.mode.toString(8)}, which keeps cargo from ${why} as any user but root, is not supported`, here)
75
+
76
+ // As any user but root, cargo reads back no file without its owner's read
77
+ // bit; lists nothing in a directory without its owner's read and search
78
+ // bits, leaving what is in it out of .cargo-checksum.json; and writes
79
+ // nothing into one without its write bit once its entry has set it, `after`.
80
+ // A directory nothing is in may have any mode. The package's always has
81
+ // something written into it last, its .cargo-checksum.json.
82
+ function fileMode(entry, here) {
83
+ const mode = modeOf(entry)
84
+ if (!(mode & 0o400)) throw unsupported(entry, 'reading it back to checksum it', here)
85
+ return mode
86
+ }
87
+ function dirMode({ entry, here, after }, content) {
88
+ const mode = modeOf(entry)
89
+ if (content && (mode & 0o500) !== 0o500) throw unsupported(entry, 'listing what is in it', here)
90
+ if (after && !(mode & 0o200)) throw unsupported(entry, 'writing into it what comes after it', here)
91
+ return mode
92
+ }
93
+
94
+ // The directory `<name>-<version>` every entry has to be in, as Rust's
95
+ // strip_prefix reads a path: by its components, so `./` or `/` before it
96
+ // is not it.
97
+ function segmentsOf(entry, prefix, here) {
98
+ const [first, ...rest] = entry.name.split('/')
99
+ if (entry.storedName.startsWith('/') || entry.storedName.startsWith('./') || first !== prefix) throw new DeptreeError(`not under ${quote(prefix)}, which cargo refuses`, here)
100
+ // tar 0.4.44, in cargo 1.94.0, takes the header's size over a pax one.
101
+ if (entry.pax.has('size')) throw new DeptreeError('a pax size, which cargo 1.94.0 reads otherwise, is not supported', here)
102
+ return rest
103
+ }
104
+
105
+ // `root` is the mode of the package's directory; `dirs` maps each directory
106
+ // under it to its mode, 0o755 where no entry of its own gives one.
107
+ function vendorEntries(entries, prefix, where) {
108
+ const dirs = new Map()
109
+ const files = new Map()
110
+ // Each directory an entry of its own gives a mode, the package's as ''.
111
+ const given = new Map()
112
+ for (const entry of entries) {
113
+ const here = `${where}: ${quote(entry.storedName)}`
114
+ const segments = segmentsOf(entry, prefix, here)
115
+ const last = segments.at(-1)
116
+ if (!vendored(segments, last)) continue
117
+ if (entry.type !== 'file' && entry.type !== 'directory') throw new DeptreeError(`a ${entry.type}, which cargo refuses`, here)
118
+ if (last === '.cargo-ok') continue
119
+ if (segments.length === 0 && entry.type !== 'directory') throw new DeptreeError('the package\'s directory is not a directory', here)
120
+ if (segments[0] === '.cargo-checksum.json') throw new DeptreeError('a .cargo-checksum.json of its own, which cargo vendor lists and then writes over, so that cargo cannot build from it', here)
121
+ // Each directory it is written into, the package's first.
122
+ let dir = ''
123
+ for (let i = 0; i < segments.length; i++) {
124
+ if (given.has(dir)) given.get(dir).after = true
125
+ if (i > 0 && !dirs.has(dir)) dirs.set(dir, 0o755)
126
+ dir = i === 0 ? segments[0] : `${dir}/${segments[i]}`
127
+ }
128
+ const path = segments.join('/')
129
+ if (entry.type === 'file') files.set(path, { data: entry.data, mode: fileMode(entry, here) })
130
+ else if (!given.has(path)) given.set(path, { entry, here, after: path === '' })
131
+ }
132
+ // A directory under the package's has something in it where an entry made it.
133
+ let root = 0o755
134
+ for (const [path, dir] of given) {
135
+ if (path === '') root = dirMode(dir, true)
136
+ else dirs.set(path, dirMode(dir, dirs.has(path)))
137
+ }
138
+ return { root, dirs, files }
139
+ }
140
+
141
+ const COMMENT = 'This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.'
142
+
143
+ // vendor.rs's, as serde_json writes it: compact, each map's keys in UTF-8
144
+ // byte order, `$comment` from cargo 1.97 on.
145
+ async function checksumFile(files, checksum, comment) {
146
+ const paths = [...files.keys()].sort(compareNames)
147
+ const sums = await Promise.all(paths.map((path) => bytesSha256Hex(files.get(path).data)))
148
+ const listed = paths.map((path, i) => `${JSON.stringify(path)}:"${sums[i]}"`).join(',')
149
+ return `{${comment ? `"$comment":${JSON.stringify(COMMENT)},` : ''}"files":{${listed}},"package":${JSON.stringify(checksum)}}`
150
+ }
151
+
152
+ // A full commit id, as git writes one: 40 lowercase hex digits, or 64 in a
153
+ // repository of SHA-256 objects.
154
+ const COMMIT = /^(?:[\da-f]{40}|[\da-f]{64})$/u
155
+
156
+ // The commit .cargo_vcs_info.json names, which `cargo package` writes where
157
+ // it packs from a git checkout: none where it found the checkout dirty, as
158
+ // the files are then not that commit's, nor where it names anything but a
159
+ // full id. Cargo reads none of it, so one that is not JSON names none, and
160
+ // is vendored all the same.
161
+ function vcsCommitOf(file) {
162
+ if (file === undefined) return undefined
163
+ try {
164
+ const git = own(JSON.parse(utf8toString(file.data)), 'git')
165
+ if (![undefined, false].includes(own(git, 'dirty'))) return undefined
166
+ const sha1 = own(git, 'sha1')
167
+ return typeof sha1 === 'string' && COMMIT.test(sha1) ? sha1 : undefined
168
+ } catch {
169
+ return undefined
170
+ }
171
+ }
172
+
173
+ // What vendor/<directory> holds of a package, `.cargo-checksum.json` among
174
+ // its files. getCrate has held the .crate to its checksum; it is held to it
175
+ // again where it is unpacked.
176
+ export async function vendorCrate(bytes, { name, version, checksum }, comment, where) {
177
+ if (await bytesSha256Hex(bytes) !== checksum) throw new DeptreeError(`its .crate's sha256 is not ${checksum}`, where)
178
+ const { root, dirs, files } = vendorEntries(entriesOf(await gunzip(bytes, where), where), `${name}-${version}`, where)
179
+ const commit = vcsCommitOf(files.get('.cargo_vcs_info.json'))
180
+ const text = await checksumFile(files, checksum, comment)
181
+ files.set('.cargo-checksum.json', { data: utf8fromString(text), mode: 0o644 })
182
+ return { root, dirs, files, checksumText: text, commit }
183
+ }
@@ -0,0 +1,81 @@
1
+ // What buildCargoTree takes, as text or read from the project's root. Texts
2
+ // given are laid out as the project they stand for, so that both are read
3
+ // one way.
4
+
5
+ import { Vfs } from '@preventive/vfs'
6
+ import { DeptreeError, quote } from '../error.js'
7
+ import { UNSAFE, isInside } from '../mount.js'
8
+ import { checkHostKeys, checkLeftOut, checkProject, checkTexts, readText, typeOf } from '../project.js'
9
+
10
+ // 1.94 to 1.99 vendor alike, but for the `$comment` 1.97 and later write.
11
+ const VERSION = /^1\.(9[4-9])\.(?:0|[1-9]\d*)$/u
12
+
13
+ export function checkHost(host) {
14
+ checkHostKeys(host, ['cargo', 'os'], 'cargo and os')
15
+ const minor = VERSION.exec(host.cargo)?.[1]
16
+ if (minor === undefined) throw new DeptreeError(`cargo ${quote(host.cargo)} is not supported: only cargo 1.94.0 to 1.99.x are`, 'host.cargo')
17
+ if (host.os === 'win32') throw new DeptreeError('Windows is not supported: cargo unpacks and names files otherwise there', 'host.os')
18
+ return { cargo: host.cargo, os: host.os, comment: Number(minor) >= 97 }
19
+ }
20
+
21
+ // A file cargo reads, by its path from the root, as text, or undefined where
22
+ // there is none: a link at it or on the way to it is refused, so that nothing
23
+ // is read from outside the project's view.
24
+ export function readUnlinked(project, file, what) {
25
+ const segments = file.split('/')
26
+ for (let i = 1; i <= segments.length; i++) {
27
+ const path = segments.slice(0, i).join('/')
28
+ const type = typeOf(project, `/${path}`, false)
29
+ if (type === undefined) return undefined
30
+ if (type === 'symlink') throw new DeptreeError(`a link where cargo reads ${what} is not supported`, quote(path))
31
+ }
32
+ return readText(project, `/${file}`, file)
33
+ }
34
+
35
+ // Cargo reads .cargo/config where it is, in .cargo/config.toml's stead.
36
+ function readConfig(project) {
37
+ for (const file of ['.cargo/config', '.cargo/config.toml']) {
38
+ const text = readUnlinked(project, file, 'its config')
39
+ if (text !== undefined) return { text, file }
40
+ }
41
+ return { text: undefined, file: '.cargo/config.toml' }
42
+ }
43
+
44
+ const MANIFESTS = 'manifests must map each directory, "." for the root, to the text of its Cargo.toml'
45
+
46
+ // `.` or a path below the root, as a Cargo.toml's directory is named.
47
+ function given(manifests) {
48
+ if (manifests === null || typeof manifests !== 'object') throw new TypeError(MANIFESTS)
49
+ const vfs = new Vfs()
50
+ const dirs = new Set()
51
+ for (const [dir, text] of manifests instanceof Map ? manifests : Object.entries(manifests)) {
52
+ if (typeof dir !== 'string' || typeof text !== 'string') throw new TypeError(MANIFESTS)
53
+ if (dir !== '.' && (!isInside(dir) || UNSAFE.test(dir))) throw new DeptreeError('not a directory below the root, as it is named here', `manifests[${quote(dir)}]`)
54
+ const path = dir === '.' ? '' : `/${dir}`
55
+ if (path !== '') vfs.mkdir(path, { recursive: true })
56
+ vfs.writeFile(`${path}/Cargo.toml`, text)
57
+ dirs.add(dir)
58
+ }
59
+ return { vfs, dirs }
60
+ }
61
+
62
+ const LOCKFILE = 'lockfile must be the Cargo.lock text, or left out where project is given'
63
+
64
+ // `project` the view manifests are read from, and `given` the directories
65
+ // of those given, which have to be those read.
66
+ export function inputsOf(options) {
67
+ const { lockfile, manifests, config, project } = options
68
+ if (lockfile === undefined) {
69
+ if (project === undefined) throw new TypeError(LOCKFILE)
70
+ checkProject(project)
71
+ checkLeftOut({ manifests, config }, 'all')
72
+ const lock = readUnlinked(project, 'Cargo.lock', 'its lockfile')
73
+ if (lock === undefined) throw new DeptreeError('the project has no Cargo.lock, without which cargo resolves every dependency anew')
74
+ return { lockfile: lock, config: readConfig(project), project, given: undefined }
75
+ }
76
+ if (typeof lockfile !== 'string') throw new TypeError(LOCKFILE)
77
+ if (project !== undefined) throw new TypeError('project must be left out where lockfile is given')
78
+ checkTexts({ config })
79
+ const { vfs, dirs } = given(manifests)
80
+ return { lockfile, config: { text: config, file: '.cargo/config.toml' }, project: vfs, given: dirs }
81
+ }
@@ -0,0 +1,90 @@
1
+ // workspace.members, exclude and default-members as cargo reads them: each
2
+ // glob from the root through the glob crate, `*` and `?` taking any name in
3
+ // a directory, one with a leading dot too; `**` and `[`, and a path that
4
+ // leads out of the root or depends on where it is, are refused.
5
+
6
+ import { compareNames, join } from '@preventive/vfs/path.js'
7
+ import { DeptreeError, quote } from '../error.js'
8
+ import { wildcard } from '../matcher.js'
9
+ import { UNSAFE, fold } from '../mount.js'
10
+ import { typeOf } from '../project.js'
11
+
12
+ const WILD = /[*?]/u
13
+ const at = (dir) => (dir === '.' ? '/' : `/${dir}`)
14
+
15
+ // A path's components as Rust's Path has them past a root: no empty or `.`.
16
+ export const parts = (path) => path.split('/').filter((segment) => segment !== '' && segment !== '.')
17
+
18
+ // Each entry of the three lists, before anything is read by it.
19
+ export function checkLists(workspace) {
20
+ for (const key of ['members', 'exclude', 'defaultMembers']) {
21
+ for (const [index, entry] of (workspace[key] ?? []).entries()) {
22
+ const where = `Cargo.toml: workspace.${key === 'defaultMembers' ? 'default-members' : key}[${index}]`
23
+ if (entry.startsWith('/') || UNSAFE.test(entry)) throw new DeptreeError(`${quote(entry)} is not a relative path within the project, which is all that is read`, where)
24
+ if (key !== 'exclude' && parts(entry).includes('..')) throw new DeptreeError(`${quote(entry)} leads out of the root, which is not read`, where)
25
+ if (key !== 'exclude' && /\*\*|\[/u.test(entry)) throw new DeptreeError(`${quote(entry)} has a \`**\` or a \`[\`, which is not supported`, where)
26
+ }
27
+ }
28
+ }
29
+
30
+ // is_excluded: under an `exclude` path and no `members` one, each taken as
31
+ // written, a glob's wildcards as names.
32
+ export function isExcluded(workspace, path) {
33
+ const under = (list) => list.some((entry) => {
34
+ const prefix = parts(entry)
35
+ return prefix.length <= path.length && prefix.every((segment, i) => segment === path[i])
36
+ })
37
+ return under(workspace.exclude) && !under(workspace.members)
38
+ }
39
+
40
+ // A name glob() checks for by a path, which on macOS takes it in any case.
41
+ function literal(names, segment, folded, dir, where) {
42
+ if (names.includes(segment)) return [segment]
43
+ const other = folded ? names.find((name) => fold(name) === fold(segment)) : undefined
44
+ if (other !== undefined) throw new DeptreeError(`${quote(join(dir, segment))} is ${quote(join(dir, other))} on macOS, which is not supported`, where)
45
+ return []
46
+ }
47
+
48
+ // Every path the glob takes, files among them, which glob() lists too. A
49
+ // link it reaches is refused, as glob() follows it.
50
+ function expand(project, glob, folded, where) {
51
+ let found = ['.']
52
+ for (const segment of parts(glob)) {
53
+ const matches = WILD.test(segment) ? wildcard(segment, { one: true }) : undefined
54
+ const next = []
55
+ for (const dir of found) {
56
+ if (typeOf(project, at(dir), false) !== 'directory') continue
57
+ const names = project.readdir(at(dir))
58
+ for (const name of matches === undefined ? literal(names, segment, folded, dir, where) : names.filter(matches)) {
59
+ const path = join(dir, name)
60
+ if (typeOf(project, at(path), false) === 'symlink') throw new DeptreeError('a link where cargo looks for members is not supported', quote(path))
61
+ next.push(path)
62
+ }
63
+ }
64
+ found = next
65
+ }
66
+ return found.sort(compareNames)
67
+ }
68
+
69
+ // members_paths: the directories each glob takes, where one that takes
70
+ // nothing at all fails as cargo goes to read it.
71
+ function pathsOf(project, globs, key, folded) {
72
+ return globs.flatMap((glob, index) => {
73
+ const where = `Cargo.toml: workspace.${key}[${index}]`
74
+ const found = expand(project, glob, folded, where)
75
+ if (found.length === 0) throw new DeptreeError(`${quote(glob)} takes nothing, which cargo fails on`, where)
76
+ return found.filter((dir) => typeOf(project, at(dir)) === 'directory')
77
+ })
78
+ }
79
+
80
+ export const explicitMembers = (project, workspace, folded) => pathsOf(project, workspace.members, 'members', folded)
81
+
82
+ // Cargo, run at the root, holds each default member to be a member, or a
83
+ // directory `members` takes, `listed`, that is excluded.
84
+ export function checkDefaultMembers(project, workspace, members, listed, folded) {
85
+ if (workspace.defaultMembers === undefined) return
86
+ for (const dir of pathsOf(project, workspace.defaultMembers, 'default-members', folded)) {
87
+ if (members.has(dir) || (listed.has(dir) && isExcluded(workspace, parts(dir)))) continue
88
+ throw new DeptreeError(`${quote(dir)} is no member, which cargo refuses`, 'Cargo.toml: workspace.default-members')
89
+ }
90
+ }
@@ -0,0 +1,65 @@
1
+ // The packages `cargo vendor` copies into vendor/, each from its .crate:
2
+ // every one of the lockfile's but a path package, which is in the project
3
+ // already. Each is fetched from crates.io and unpacked as cargo unpacks it.
4
+
5
+ import { parseVersion } from '@preventive/lockfile/rust-semver.js'
6
+ import { getCrate } from '@preventive/upstream/cargo.js'
7
+ import { eachConcurrently } from '../concurrent.js'
8
+ import { DeptreeError, quote } from '../error.js'
9
+ import { vendorCrate } from './crate.js'
10
+
11
+ // As Cargo.lock names crates.io, however cargo reaches its index.
12
+ const CRATES_IO = 'registry+https://github.com/rust-lang/crates.io-index'
13
+
14
+ export const about = (key) => `packages[${quote(key)}]`
15
+
16
+ const sign = (a, b) => (a === b ? 0 : a < b ? -1 : 1)
17
+
18
+ // The semver crate's order of two versions the lockfile reader has read, but
19
+ // for build metadata, which crates.io takes no two versions apart by: a
20
+ // pre-release before its release, its identifiers digits before others and
21
+ // digits by their value.
22
+ function compareVersions(a, b) {
23
+ const [x, y] = [parseVersion(a), parseVersion(b)]
24
+ for (const part of ['major', 'minor', 'patch']) if (x[part] !== y[part]) return sign(x[part], y[part])
25
+ if (x.pre === '' || y.pre === '') return sign(x.pre === '', y.pre === '')
26
+ const [ids1, ids2] = [x.pre.split('.'), y.pre.split('.')]
27
+ for (let i = 0; i < Math.min(ids1.length, ids2.length); i++) {
28
+ const [p, q] = [ids1[i], ids2[i]]
29
+ const [digits1, digits2] = [/^\d+$/u.test(p), /^\d+$/u.test(q)]
30
+ if (digits1 !== digits2) return digits1 ? -1 : 1
31
+ const order = (digits1 && sign(p.length, q.length)) || sign(p, q)
32
+ if (order !== 0) return order
33
+ }
34
+ return sign(ids1.length, ids2.length)
35
+ }
36
+
37
+ // vendor.rs: the greatest version of a name has a directory of the name
38
+ // alone, and any other `<name>-<version>`.
39
+ export function vendoredPackages(lock) {
40
+ const crates = []
41
+ for (const [key, pkg] of Object.entries(lock.packages)) {
42
+ if (pkg.source === undefined) continue
43
+ if (pkg.source.startsWith('git+')) throw new DeptreeError('a git dependency, which cargo vendor checks out with git, is not supported', about(key))
44
+ if (pkg.source !== CRATES_IO) throw new DeptreeError('a package from a registry other than crates.io is not supported', about(key))
45
+ crates.push({ key, name: pkg.name, version: pkg.version, checksum: pkg.checksum })
46
+ }
47
+ const greatest = new Map()
48
+ for (const { name, version } of crates) {
49
+ const other = greatest.get(name)
50
+ const order = other === undefined ? 1 : compareVersions(version, other)
51
+ if (order === 0) throw new DeptreeError(`${quote(version)} and ${quote(other)} differ only in build metadata, which cargo vendors one of`, about(`${name} ${version}`))
52
+ if (order > 0) greatest.set(name, version)
53
+ }
54
+ for (const crate of crates) crate.directory = crate.version === greatest.get(crate.name) ? crate.name : `${crate.name}-${crate.version}`
55
+ return crates
56
+ }
57
+
58
+ // A few at a time; what each holds, by its key.
59
+ export async function fetchCrates(crates, comment) {
60
+ const vendored = new Map()
61
+ await eachConcurrently(crates, async (crate) => {
62
+ vendored.set(crate.key, await vendorCrate(await getCrate(crate.name, crate.version, crate.checksum), crate, comment, about(crate.key)))
63
+ }, ({ key }) => about(key))
64
+ return vendored
65
+ }