UNPKG

1.46 kBPlain TextView Raw
1import concat from 'concat-stream';
2import stream from 'stream';
3import tar from 'tar-stream';
4import * as tsm from 'ts-morph';
5import { toForwardSlashes } from '../utils/to-forward-slashes';
6
7export function extractPackageTarball({
8 fileSystem,
9}: {
10 fileSystem: tsm.FileSystemHost;
11}): stream.Writable {
12 const extract = tar.extract();
13
14 extract.on('entry', (header, stream, next) => {
15 const { type, name } = header;
16 const filename = normalizeEntryFilename({ name });
17 if (!shouldExtractEntry({ type, filename })) {
18 // Drain this stream and go to next entry
19 stream.resume();
20 return next();
21 }
22
23 stream.pipe(
24 concat((data) => {
25 const contents = data.toString();
26 fileSystem.writeFileSync(filename, contents);
27 next();
28 })
29 );
30 });
31
32 return extract;
33}
34
35function shouldExtractEntry({
36 type,
37 filename,
38}: {
39 type: string | null | undefined;
40 filename: string;
41}): boolean {
42 if (type !== 'file') {
43 return false;
44 }
45
46 return filename.endsWith('.ts');
47}
48
49/**
50 * `normalizeEntryFilename` removes the root directory present in npm packages
51 * from the names of entries (for example, `package/src/index.ts` => `src/index.ts`).
52 */
53function normalizeEntryFilename({ name }: { name: string }): string {
54 return toForwardSlashes(name).split('/').slice(1).join('/');
55}