/
tarball-fetcher.js
200 lines (169 loc) · 5.89 KB
/
tarball-fetcher.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
/* @flow */
import {SecurityError, MessageError} from '../errors.js';
import type {FetchedOverride} from '../types.js';
import {UnpackStream} from '../util/stream.js';
import * as constants from '../constants.js';
import * as crypto from '../util/crypto.js';
import BaseFetcher from './base-fetcher.js';
import * as fsUtil from '../util/fs.js';
const invariant = require('invariant');
const path = require('path');
const tar = require('tar');
const url = require('url');
const fs = require('fs');
export default class TarballFetcher extends BaseFetcher {
async getResolvedFromCached(hash: string): Promise<?string> {
const mirrorPath = this.getMirrorPath();
if (mirrorPath == null) {
// no mirror
return null;
}
const tarballLoc = path.join(this.dest, constants.TARBALL_FILENAME);
if (!(await fsUtil.exists(tarballLoc))) {
// no tarball located in the cache
return null;
}
// copy the file over
if (!await fsUtil.exists(mirrorPath)) {
await fsUtil.copy(tarballLoc, mirrorPath, this.reporter);
}
const relativeMirrorPath = this.getRelativeMirrorPath(mirrorPath);
invariant(relativeMirrorPath != null, 'Missing offline mirror path');
return `${relativeMirrorPath}#${hash}`;
}
getMirrorPath(): ?string {
const {pathname} = url.parse(this.reference);
if (pathname == null) {
return this.config.getOfflineMirrorPath();
}
let packageFilename = path.basename(pathname);
// handle scoped packages
const pathParts = pathname.slice(1).split('/');
if (pathParts[0][0] === '@') {
// scoped npm package
packageFilename = `${pathParts[0]}-${packageFilename}`;
}
return this.config.getOfflineMirrorPath(packageFilename);
}
getRelativeMirrorPath(mirrorPath: string): ?string {
const offlineMirrorPath = this.config.getOfflineMirrorPath();
if (offlineMirrorPath == null) {
return null;
}
return path.relative(offlineMirrorPath, mirrorPath);
}
createExtractor(
mirrorPath: ?string,
resolve: (fetched: FetchedOverride) => void,
reject: (error: Error) => void,
): {
validateStream: crypto.HashStream,
extractorStream: UnpackStream,
} {
const validateStream = new crypto.HashStream();
const extractorStream = new UnpackStream();
const untarStream = tar.Extract({path: this.dest, strip: 1});
extractorStream
.pipe(untarStream)
.on('error', reject)
.on('end', () => {
const expectHash = this.hash;
const actualHash = validateStream.getHash();
if (!expectHash || expectHash === actualHash) {
resolve({
hash: actualHash,
resolved: mirrorPath ? `${mirrorPath}#${actualHash}` : null,
});
} else {
reject(new SecurityError(
this.config.reporter.lang('fetchBadHash', expectHash, actualHash),
));
}
});
return {validateStream, extractorStream};
}
async fetchFromLocal(pathname: ?string): Promise<FetchedOverride> {
const {reference: ref, config} = this;
const {reporter} = config;
// path to the local tarball
let localTarball;
let isOfflineTarball = false;
const relativeFileLoc = pathname ? path.join(config.cwd, pathname) : null;
if (relativeFileLoc && await fsUtil.exists(relativeFileLoc)) {
// this is a reference to a file relative to the cwd
localTarball = relativeFileLoc;
} else {
// generate a offline cache location
const offlineMirrorPath = config.getOfflineMirrorPath() || '';
localTarball = path.resolve(offlineMirrorPath, ref);
isOfflineTarball = true;
}
if (!(await fsUtil.exists(localTarball))) {
throw new MessageError(reporter.lang('tarballNotInNetworkOrCache', ref, localTarball));
}
return new Promise((resolve, reject) => {
const {validateStream, extractorStream} = this.createExtractor(null, resolve, reject);
const cachedStream = fs.createReadStream(localTarball);
cachedStream
.pipe(validateStream)
.pipe(extractorStream)
.on('error', function(err) {
let msg = 'errorDecompressingTarball';
if (isOfflineTarball) {
msg = 'fetchErrorCorrupt';
}
reject(new MessageError(reporter.lang(msg, err.message, localTarball)));
});
});
}
fetchFromExternal(): Promise<FetchedOverride> {
const {reference: ref} = this;
const registry = this.config.registries[this.registry];
return registry.request(ref, {
headers: {
'Accept-Encoding': 'gzip',
'Accept': 'application/octet-stream',
},
buffer: true,
process: (req, resolve, reject) => {
// should we save this to the offline cache?
const mirrorPath = this.getMirrorPath();
const tarballStorePath = path.join(this.dest, constants.TARBALL_FILENAME);
const overwriteResolved = mirrorPath
? this.getRelativeMirrorPath(mirrorPath)
: null;
//
const {
validateStream,
extractorStream,
} = this.createExtractor(overwriteResolved, resolve, reject);
//
req.pipe(validateStream);
validateStream
.pipe(fs.createWriteStream(tarballStorePath))
.on('error', reject);
validateStream
.pipe(extractorStream)
.on('error', reject);
if (mirrorPath) {
validateStream
.pipe(fs.createWriteStream(mirrorPath))
.on('error', reject);
}
},
});
}
_fetch(): Promise<FetchedOverride> {
const {protocol, pathname} = url.parse(this.reference);
if (protocol === null && typeof pathname === 'string') {
return this.fetchFromLocal(pathname);
} else {
return this.fetchFromExternal();
}
}
}
export class LocalTarballFetcher extends TarballFetcher {
_fetch(): Promise<FetchedOverride> {
return this.fetchFromLocal(this.reference);
}
}