-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathindex.js
142 lines (116 loc) · 3.92 KB
/
index.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
const fs = require('fs');
const path = require('path');
const loaderUtils = require('loader-utils');
const LineDiff = require('line-diff');
const bannerMessage =
'// This file is automatically generated.\n// Please do not change this file!';
const cssModuleExport = 'export const cssExports: CssExports;\nexport default cssExports;\n';
const getNoDeclarationFileError = ({ filename }) =>
new Error(
`Generated type declaration does not exist. Run webpack and commit the type declaration for '${filename}'`
);
const getTypeMismatchError = ({ filename, expected, actual }) => {
const diff = new LineDiff(enforceLFLineSeparators(actual), expected).toString();
return new Error(
`Generated type declaration file is outdated. Run webpack and commit the updated type declaration for '${filename}'\n\n${diff}`
);
};
const cssModuleToInterface = (cssModuleKeys) => {
const interfaceFields = cssModuleKeys
.sort()
.map(key => ` '${key}': string;`)
.join('\n');
return `interface CssExports {\n${interfaceFields}\n}`;
};
const filenameToTypingsFilename = filename => {
const dirName = path.dirname(filename);
const baseName = path.basename(filename);
return path.join(dirName, `${baseName}.d.ts`);
};
const enforceLFLineSeparators = text => {
if (text) {
// replace all CRLFs (Windows) by LFs (Unix)
return text.replace(/\r\n/g, "\n");
} else {
return text;
}
};
const compareText = (contentA, contentB) => {
return enforceLFLineSeparators(contentA) === enforceLFLineSeparators(contentB);
};
const validModes = ['emit', 'verify'];
const isFileNotFound = err => err && err.code === 'ENOENT';
const makeDoneHandlers = (callback, content, rest) => ({
failed: e => callback(e),
success: () => callback(null, content, ...rest)
});
const makeFileHandlers = filename => ({
read: handler => fs.readFile(filename, { encoding: 'utf-8' }, handler),
write: (content, handler) =>
fs.writeFile(filename, content, { encoding: 'utf-8' }, handler)
});
const extractLocalExports = (content) => {
let localExports = content.split('exports.locals')[1];
if (!localExports) {
localExports = content.split('___CSS_LOADER_EXPORT___.locals')[1];
}
return localExports;
}
module.exports = function(content, ...rest) {
const { failed, success } = makeDoneHandlers(this.async(), content, rest);
const filename = this.resourcePath;
const { mode = 'emit' } = loaderUtils.getOptions(this) || {};
if (!validModes.includes(mode)) {
return failed(new Error(`Invalid mode option: ${mode}`));
}
const cssModuleInterfaceFilename = filenameToTypingsFilename(filename);
const { read, write } = makeFileHandlers(cssModuleInterfaceFilename);
const keyRegex = /"([^\\"]+)":/g;
let match;
const cssModuleKeys = [];
const localExports = extractLocalExports(content);
while ((match = keyRegex.exec(localExports))) {
if (cssModuleKeys.indexOf(match[1]) < 0) {
cssModuleKeys.push(match[1]);
}
}
const cssModuleDefinition = `${bannerMessage}\n${cssModuleToInterface(cssModuleKeys)}\n${cssModuleExport}`;
if (mode === 'verify') {
read((err, fileContents) => {
if (isFileNotFound(err)) {
return failed(
getNoDeclarationFileError({
filename: cssModuleInterfaceFilename
})
);
}
if (err) {
return failed(err);
}
if (!compareText(cssModuleDefinition, fileContents)) {
return failed(
getTypeMismatchError({
filename: cssModuleInterfaceFilename,
expected: cssModuleDefinition,
actual: fileContents
})
);
}
return success();
});
} else {
read((_, fileContents) => {
if (!compareText(cssModuleDefinition, fileContents)) {
write(cssModuleDefinition, err => {
if (err) {
failed(err);
} else {
success();
}
});
} else {
success();
}
});
}
};