-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.ts
76 lines (71 loc) · 2.51 KB
/
index.ts
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
import * as fs from 'fs';
import { isAbsolute, resolve } from 'path';
import { readFileSync, existsSync, readdirSync, lstatSync, statSync, writeFileSync, appendFileSync, rmdirSync, mkdirSync } from 'fs';
import { removeSync } from 'fs-extra';
const symlinkOrCopySync = require('symlink-or-copy').sync;
const logger = require('heimdalljs-logger')('broccoli:outputWrapper');
const WHITELISTEDOPERATION = new Set([
'readFileSync',
'existsSync',
'lstatSync',
'readdirSync',
'statSync',
'writeFileSync',
'appendFileSync',
'rmdirSync',
'mkdirSync',
'unlinkSync',
'symlinkOrCopySync'
]);
function handleFs(target: any, propertyName: string, node: any, relativePath: string, ...fsArguments: Array<any>) {
let srcPath = '';
if (propertyName === 'symlinkOrCopySync') {
srcPath = relativePath;
relativePath = fsArguments[0];
}
if (isAbsolute(relativePath)) {
throw new Error(`Relative path is expected, path ${relativePath} is an absolute path.`);
}
let outputPath = resolve(node.outputPath + '/' + relativePath);
if (!outputPath.includes(node.outputPath)) {
throw new Error(`Traversing above the outputPath is not allowed. Relative path ${relativePath} traverses beyond ${node.outputPath}`);
}
if(WHITELISTEDOPERATION.has(propertyName)) {
logger.debug(`[operation:${propertyName}] at ${outputPath}`);
switch (propertyName) {
case 'symlinkOrCopySync':
return symlinkOrCopySync(srcPath, outputPath);
case 'rmdirSync':
if (fsArguments[0] && fsArguments[0].recursive) {
return removeSync(outputPath);
}
default:
return target[propertyName](outputPath, ...fsArguments);
}
} else {
throw new Error(`Operation ${propertyName} is not allowed to use. Allowed operations are ${Array.from(WHITELISTEDOPERATION).toString()}`);
}
}
function outputWrapper (node: any): outputWrapper.FSOutput {
return new Proxy(fs, {
get(target: any, propertyName: string): any {
return handleFs.bind(this, target, propertyName, node);
}
});
}
export = outputWrapper;
namespace outputWrapper {
export interface FSOutput {
readFileSync: typeof readFileSync,
existsSync: typeof existsSync,
lstatSync: typeof lstatSync,
readdirSync: typeof readdirSync,
statSync: typeof statSync,
writeFileSync: typeof writeFileSync,
appendFileSync: typeof appendFileSync,
rmdirSync: typeof rmdirSync,
mkdirSync: typeof mkdirSync,
unlinkSync: typeof fs.unlinkSync,
symlinkOrCopy: (srcPath: string, destPath: string) => void
}
}