-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.ts
More file actions
264 lines (227 loc) · 7.56 KB
/
index.ts
File metadata and controls
264 lines (227 loc) · 7.56 KB
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
import { execSync } from 'node:child_process';
import { Spec } from '@vltpkg/spec';
import { manifest as getManifest } from '@vltpkg/package-info';
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { homedir } from 'node:os';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const pkg = JSON.parse(readFileSync(join(__dirname, 'package.json'), 'utf8'));
interface PackageManifest {
name: string
version: string
repository?: {
url: string
type?: string
directory?: string
}
gitHead?: string
dist: {
tarball: string
integrity: string
attestations?: {
url: string
}
}
}
interface PackedResult {
integrity?: string
[key: string]: any
}
interface Strategy {
getVersion: () => string
install: (dir: string) => string
pack: (dir: string) => {
command: string
parseResult: (output: string) => PackedResult
}
}
export interface ReproduceOptions {
cache?: Record<string, any>
cacheDir?: string
cacheFile?: string
strategy?: 'npm'
force?: boolean
}
export interface ReproduceResult {
reproduceVersion: string
timestamp: Date
os: string
arch: string
strategy: string
reproduced: boolean
attested: boolean
package: {
name: string
version: string
spec: string
location: string
integrity: string
}
source: {
spec: string
location: string
integrity: string
}
diff?: string
}
// Parse a URL to get the name and version of the package
function parseURL(url: string): { name: string; version: string } {
// Split the URL by "/"
const parts = url.split('/');
// Find the tarball filename (last part of the URL)
const tarball = parts[parts.length - 1];
// Ensure it ends with `.tgz`
if (!tarball.endsWith('.tgz')) {
throw new Error('Invalid npm tarball URL');
}
// Remove the `.tgz` extension
const baseName = tarball.slice(0, -4);
// Find the last `-` to split the name and version
const lastDashIndex = baseName.lastIndexOf('-');
if (lastDashIndex === -1) {
throw new Error('Invalid tarball filename structure');
}
const namePart = baseName.slice(0, lastDashIndex);
const version = baseName.slice(lastDashIndex + 1);
// Determine if it's a scoped package
let name = namePart;
const scopeIndex = parts.indexOf('-');
if (scopeIndex > 0 && parts[scopeIndex - 1].startsWith('@')) {
name = `${parts[scopeIndex - 1]}/${namePart}`;
}
return { name, version };
}
// Get OS-specific cache directory
function getDefaultCacheDir(): string {
switch (process.platform) {
case 'darwin':
return join(homedir(), 'Library', 'Caches', 'reproduce');
case 'win32':
return join(homedir(), 'AppData', 'Local', 'reproduce', 'Cache');
default: // Linux and others follow XDG spec
return join(process.env.XDG_CACHE_HOME || join(homedir(), '.cache'), 'reproduce');
}
}
const DEFAULT_CACHE_DIR = getDefaultCacheDir();
const DEFAULT_CACHE_FILE = 'cache.json';
const EXEC_OPTIONS = { stdio: [] };
const STRATEGIES: Record<string, Strategy> = {
npm: {
getVersion: () => execSync('npm --version', EXEC_OPTIONS).toString().trim(),
install: (dir: string) => `cd ${dir} && npm install --no-audit --no-fund --silent >/dev/null`,
pack: (dir: string) => ({
command: `
cd ${dir} &&
npm pack --dry-run --json`,
parseResult: (output: string) => JSON.parse(output)[0]
})
}
};
export async function reproduce(spec: string, opts: ReproduceOptions = {}): Promise<ReproduceResult | false> {
opts = {
cache: {},
cacheDir: DEFAULT_CACHE_DIR,
cacheFile: DEFAULT_CACHE_FILE,
strategy: 'npm',
...opts
};
if (!opts.strategy || !STRATEGIES[opts.strategy]) {
throw new Error(`Invalid strategy: ${opts.strategy}`);
}
let skipSetup = false;
const cacheFilePath = join(opts.cacheDir!, opts.cacheFile!);
if (!existsSync(cacheFilePath)) {
mkdirSync(opts.cacheDir!, { recursive: true });
writeFileSync(cacheFilePath, JSON.stringify(opts.cache));
}
opts.cache = Object.keys(opts.cache!).length > 0 ? opts.cache : JSON.parse(readFileSync(cacheFilePath, 'utf8'));
try {
const info = new Spec(spec);
if (!spec || !info || info.type != 'registry' || info.registry != 'https://registry.npmjs.org/') {
return false;
}
// Make cache spec-based by using the full spec as the key
if (!opts.force && opts.cache && opts.cache.hasOwnProperty(spec)) {
// If the package name was never set, parse the URL and set it & version (useful for old caches)
const cacheEntry = opts.cache[spec];
if (cacheEntry?.package && !cacheEntry.package.name) {
const { name, version } = parseURL(cacheEntry.package.location);
cacheEntry.package.name = name;
cacheEntry.package.version = version;
}
return cacheEntry;
}
const manifest = await getManifest(spec) as unknown as PackageManifest;
if (!manifest || !manifest?.repository?.url) {
return false;
}
const repo = manifest.repository!;
const url = repo.url;
const parsed = new URL(url);
const location = parsed.pathname.replace('.git', '').split('/').slice(1, 3).join('/');
const path = repo.directory ? `::path:${repo.directory}` : '';
const explicitRef = url.indexOf('#') > 0 ? url.substring(0, url.indexOf('#')) : '';
const implicitRef = manifest.gitHead || 'HEAD';
const ref = explicitRef || implicitRef || '';
const host = parsed.host;
if (host !== 'github.com') {
return false;
}
const source = `github:${location}#${ref}${path}`;
const sourceSpec = new Spec(`${manifest.name}@${source}`);
let packed: PackedResult = {};
const strategy = STRATEGIES[opts.strategy!];
const cacheDir = join(opts.cacheDir!, sourceSpec.name);
try {
// Skip setup if the package is already cached or if the git repository is already cloned
if (!opts.force && (opts.cache!.hasOwnProperty(sourceSpec.toString()) || existsSync(cacheDir))) {
skipSetup = true;
}
// Clone and install
if (!skipSetup) {
execSync(`
rm -rf ${cacheDir} &&
git clone https://github.com/${location}.git ${cacheDir} --depth 1 >/dev/null &&
cd ${cacheDir} &&
git checkout ${ref} >/dev/null
`, EXEC_OPTIONS);
// Install dependencies
execSync(strategy.install(cacheDir), EXEC_OPTIONS);
}
// Pack and get integrity
const packCommand = strategy.pack(cacheDir);
const packResult = execSync(packCommand.command, EXEC_OPTIONS);
packed = packCommand.parseResult(packResult.toString());
} catch (e) {
// swallow reproducibility errors
}
const check: ReproduceResult = opts.cache![spec] = {
reproduceVersion: pkg.version,
timestamp: new Date(),
os: process.platform,
arch: process.arch,
strategy: `${opts.strategy}:${strategy.getVersion()}`,
reproduced: packed?.integrity ? manifest.dist.integrity === packed.integrity : false,
attested: !!manifest.dist?.attestations?.url,
package: {
spec,
name: manifest.name,
version: manifest.version,
location: manifest.dist.tarball,
integrity: manifest.dist.integrity,
},
source: {
spec: source,
location: repo.url,
integrity: packed?.integrity || 'null',
}
};
// Persist cache
writeFileSync(cacheFilePath, JSON.stringify(opts.cache, null, 2));
return check;
} catch (e) {
return opts.cache![spec] = false;
}
}