-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathsubsetLocalFont.js
82 lines (67 loc) · 2.14 KB
/
subsetLocalFont.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
// https://github.com/googlefonts/tools/blob/master/experimental/make_kit.py
// https://github.com/filamentgroup/glyphhanger/blob/master/index.js
// Installation:
// pip install fonttools brotli zopfli
const childProcess = require('child_process');
try {
childProcess.execSync('pyftsubset --help', { stdio: 'ignore' });
} catch (err) {
throw new Error(
'Subsetting tool not available. How to install: `pip install fonttools brotli zopfli`'
);
}
const Promise = require('bluebird');
const fs = require('fs');
const getTemporaryFilePath = require('gettemporaryfilepath');
const allowedFormats = ['truetype', 'woff', 'woff2'];
const readFile = Promise.promisify(fs.readFile);
const writeFile = Promise.promisify(fs.writeFile);
const execFile = Promise.promisify(childProcess.execFile);
function subsetLocalFont(inputBuffer, format, text, ignoreMissingUnicodes) {
if (!allowedFormats.includes(format)) {
throw new Error(
`Invalid output format: \`${format}\`. Allowed formats: ${allowedFormats
.map((t) => `\`${t}\``)
.join(', ')}`
);
}
text = text || '*';
const tempInputFileName = getTemporaryFilePath({
prefix: 'input-',
suffix: `.${format}`,
});
const tempOutputFileName = getTemporaryFilePath({
prefix: 'output-',
suffix: `.${format}`,
});
const args = [
tempInputFileName,
`--output-file=${tempOutputFileName}`,
'--obfuscate_names',
`--text="${text.replace('"', '\\"')}"`,
];
if (format === 'woff') {
args.push('--with-zopfli');
}
if (format !== 'truetype') {
args.push(`--flavor=${format}`);
}
return writeFile(tempInputFileName, inputBuffer)
.then((result) => execFile('pyftsubset', args))
.catch((err) => {
if (
err.message.includes(
'fontTools.ttLib.TTLibError: Not a TrueType or OpenType font (not enough data)'
)
) {
throw new Error('Not a TrueType or OpenType font');
}
throw err;
})
.then(() => readFile(tempOutputFileName))
.finally(() => {
fs.unlink(tempInputFileName, () => {});
fs.unlink(tempOutputFileName, () => {});
});
}
module.exports = subsetLocalFont;