/
postcss-server.js
151 lines (123 loc) · 3.88 KB
/
postcss-server.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
/* @flow */
import net from 'net';
import fs from 'fs';
import path from 'path';
import util from 'util';
import crypto from 'crypto';
import makeDebug from 'debug';
import postcss from 'postcss';
import loadConfig from 'postcss-load-config';
import type { Socket, Server } from 'net';
const debug = makeDebug('babel-plugin-transform-postcss');
const streams = { stderr: process.stderr }; // overwritable by tests
const md5 = (data: string) => (
crypto.createHash('md5').update(data).digest('hex')
);
const error = (...args: any) => {
let prefix = 'babel-plugin-transform-postcss: ';
const message = util.format(...args);
if (streams.stderr.isTTY) {
prefix = `\x1b[31m${prefix}\x1b[0m`;
}
streams.stderr.write(`${prefix}${message}\n`);
};
const main = async function main(
socketPath: string,
tmpPath: string,
): Promise<Server> {
try { fs.mkdirSync(tmpPath); } // eslint-disable-line no-sync
catch (err) {
if (err.code !== 'EEXIST') {
throw err;
}
}
const options = { allowHalfOpen: true };
const server = net.createServer(options, (connection: Socket) => {
let data: string = '';
connection.on('data', (chunk: Buffer) => {
data += chunk.toString('utf8');
});
connection.on('end', async(): Promise<void> => {
try {
let tokens, cache;
const { cssFile } = JSON.parse(data);
const cachePath =
`${path.join(tmpPath, cssFile.replace(/[^a-z]/ig, ''))}.cache`;
const source = // eslint-disable-next-line no-sync
fs.readFileSync(cssFile, 'utf8');
const hash = md5(source);
// eslint-disable-next-line no-sync
try { cache = JSON.parse(fs.readFileSync(cachePath, 'utf8')); }
catch (err) {
if (err.code !== 'ENOENT') {
throw err;
}
}
if (cache && cache.hash === hash) {
connection.end(JSON.stringify(cache.tokens));
return;
}
const extractModules = (_, resultTokens: any) => {
tokens = resultTokens;
};
const { plugins, options: postcssOpts } =
await loadConfig({ extractModules }, path.dirname(cssFile));
const runner = postcss(plugins);
await runner.process(source, Object.assign({
from: cssFile,
to: cssFile, // eslint-disable-line id-length
}, postcssOpts));
cache = {
hash,
tokens,
};
// eslint-disable-next-line no-sync
fs.writeFileSync(cachePath, JSON.stringify(cache));
connection.end(JSON.stringify(tokens));
}
catch (err) {
error(err.stack);
connection.end();
}
});
});
if (fs.existsSync(socketPath)) { // eslint-disable-line no-sync
error(`Server already running on socket ${socketPath}`);
process.exit(1);
return server; // tests can make it past process.exit
}
await new Promise((resolve: () => void, reject: (Error) => void) => {
server.on('error', (err: Error) => reject(err));
server.on('listening', () => {
const handler = () => {
fs.unlinkSync(socketPath); // eslint-disable-line no-sync
};
server.on('close', () => {
process.removeListener('exit', handler);
process.removeListener('SIGINT', handler);
process.removeListener('SIGTERM', handler);
});
process.on('exit', handler);
process.on('SIGINT', handler);
process.on('SIGTERM', handler);
resolve();
});
server.listen(socketPath, () => {
debug(
`babel-plugin-transform-postcss server running on socket ${socketPath}`
);
});
});
return server;
};
/* istanbul ignore if */
if ((require: any).main === module) {
(async(): Promise<void> => {
try { await main(...process.argv.slice(2)); }
catch (err) { process.stderr.write(`${err.stack}\n`); process.exit(1); }
})();
}
export {
main,
streams as _streams,
};