Debian Codegraph @

components/bin/build

raw
1 #! /usr/bin/env node
2
3 /*************************************************************
4 *
5 * Copyright (c) 2018 The MathJax Consortium
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 */
19
20 /**
21 * @fileoverview Builds the lib directory for a component
22 *
23 * @author [email protected] (Davide Cervone)
24 */
25
26
27 const fs = require('fs');
28 const path = require('path');
29
30 /**
31 * The amount of space for each level of indentation
32 */
33 const INDENT = ' ';
34
35 /**
36 * The pattern to use when looking for explort commands to process
37 */
38 const EXPORTPATTERN = /(^export(?:\s+default)?(?:\s+abstract)?\s+[^ {*}]+\s+[a-zA-Z0-9_.$]+)/m;
39
40 const EXPORT_IGNORE = ['type', 'interface'];
41 const EXPORT_PROCESS = ['let', 'const', 'var', 'function', 'class', 'namespace'];
42
43 /**
44 * The relative path to the MathJax directory
45 */
46 const mjPath = path.relative(process.cwd(), path.resolve(__dirname, '..', '..', 'js'));
47 const mjGlobal = path.join('..', mjPath, 'components', 'global.js');
48
49 /**
50 * Read the configuration for the component
51 */
52 const config = JSON.parse(fs.readFileSync(process.argv[2] || 'build.json'));
53
54 function getType() {
55 const component = config.component || 'part';
56 if (component.match(/\/(svg|chtml|common)\/fonts\//)) return RegExp.$1 + '-font';
57 if (component.match(/\/(mathml|tex)\/.+\//)) return RegExp.$1 + '-extension';
58 if (component.match(/^(.+)\//)) return RegExp.$1;
59 return component;
60 }
61
62 /**
63 * Extract the configuration values
64 */
65 const COMPONENT = path.basename(config.component || 'part'); // name of the component
66 const ID = config.id || config.component || 'part'; // the ID of the component
67 const TARGETS = config.targets || []; // the files to include in the component
68 const EXCLUDE = new Map((config.exclude || []).map(name => [name, true])); // files to exclude from the component
69 const EXCLUDESUBDIRS = config.excludeSubdirs === 'true'; // exclude subdirectories or not
70 const JS = config.js || config.mathjax || mjPath; // path to the compiled .js files
71 const LIB = config.lib || './lib'; // path to the lib directory to create
72 const TS = config.ts || JS.replace(/js$/, 'ts'); // path to the .ts files
73 const GLOBAL = config.global || mjGlobal; // path to the global.js file
74 const VERSION = config.version || mjGlobal.replace(/global/, 'version'); // path to the version.js file
75 const TYPE = config.type || getType(); // the module type
76
77 /**
78 * The list of files that need to be added to the lib directory
79 */
80 let PACKAGE = [];
81
82 /**
83 * Process an array of files/directories to be included in the component
84 *
85 * @param {string} base The root directory for the .ts files
86 * @param {string} dir The relative path within the root for the files to process
87 * @param {string[]} list An array of file/directory names to process
88 * @param {boolean} top True if this is the initial list of files
89 */
90 function processList(base, dir, list, top = true) {
91 for (const item of list) {
92 const file = path.join(dir, item);
93 if (!EXCLUDE.has(file)) {
94 const stat = fs.statSync(path.resolve(base, file));
95 if (stat.isDirectory()) {
96 if (top || !EXCLUDESUBDIRS) {
97 processDir(base, file);
98 }
99 } else if (file.match(/\.ts$/)) {
100 processFile(base, file);
101 }
102 }
103 }
104 }
105
106 /**
107 * Process the contents of the directory
108 *
109 * @param {string} base The root directory for the .ts files
110 * @param {string} dir The relative path within the root for the directory to process
111 */
112 function processDir(base, dir) {
113 const root = path.resolve(base, dir);
114 processList(base, dir, fs.readdirSync(root), false);
115 }
116
117 /**
118 * Process the contents of a .ts file
119 *
120 * Look for export commands within the file, and determine the objects
121 * that they reference, then produce the library file that defines
122 * them, and add the file to the package list.
123 *
124 * @param {string} base The root directory for the .ts files
125 * @param {string} name The path of the file relative to the base
126 */
127 function processFile(base, name) {
128 console.info(' ' + name);
129 const file = fs.readFileSync(path.resolve(base, name)).toString();
130 const parts = file.split(EXPORTPATTERN);
131 const objects = processParts(parts);
132 const lines = processLines(name, objects);
133 makeFile(name, lines);
134 if (objects.length) {
135 PACKAGE.push(name);
136 }
137 }
138
139 /**
140 * Process the export lines to record the ones that need to be added to the
141 * library file.
142 *
143 * @param {string[]} parts The file broken into export lines and the text between them
144 * @return {string[]} An array of names of exported objects
145 */
146 function processParts(parts) {
147 const objects = [];
148 for (let i = 1; i < parts.length; i += 2) {
149 const words = parts[i].split(/\s+/);
150 const type = words[words.length - 2];
151 const name = words[words.length - 1];
152
153 if (words[1] === 'default' || type === 'default') {
154 objects.push('default');
155 } else if (EXPORT_PROCESS.indexOf(type) >= 0) {
156 objects.push(name);
157 } else if (EXPORT_IGNORE.indexOf(type) < 0) {
158 console.info(" Can't process '" + parts[i] + "'");
159 }
160 }
161 return objects;
162 }
163
164 /**
165 * Create the lines of the lib file using the object names from the file.
166 *
167 * @param {string} name The path of the file relative to the root .ts directory
168 * @param {string[]} objects Array of names of the object exported by the file
169 * @return {string[]} Array of lines for the contents of the library file
170 */
171 function processLines(file, objects) {
172 if (objects.length === 0) return [];
173 const dir = path.dirname(file).replace(/^\.$/, '');
174 const dots = dir.replace(/[^\/]+/g, '..') || '.';
175 const relative = path.join(dots, '..', JS, dir, path.basename(file)).replace(/\.ts$/, '.js');
176 const name = path.parse(file).name;
177 const lines = [
178 '"use strict";',
179 `Object.defineProperty(exports, '__esModule', {value: true});`
180 ];
181 let source = ((dir.replace(/\//g, '.') + '.' + name).replace(/^\./, '')
182 + (exists(path.resolve(JS, file.replace(/\.ts$/, ''))) ? '_ts' : ''))
183 .replace(/\.[^.]*/g, (x) => (x.substr(1).match(/[^a-zA-Z_]/) ? '[\'' + x.substr(1) + '\']' : x));
184 for (const id of objects) {
185 lines.push(`exports.${id} = MathJax._.${source}.${id};`);
186 }
187 return lines;
188 }
189
190 /**
191 * @param {string} file Path to a file
192 * @return {boolean} True if the file exists, false if not
193 */
194 function exists(file) {
195 if (!fs.existsSync(file)) return false;
196 //
197 // For case-insensitive file systems (like Mac OS),
198 // check that the file names match exactly
199 //
200 const [dir, name] = [path.dirname(file), path.basename(file)];
201 return fs.readdirSync(dir).indexOf(name) >= 0;
202 }
203
204 /**
205 * Recursively make any needed directories
206 *
207 * @param {string} dir The directory relative to the library directory
208 */
209 function makeDir(dir) {
210 const fulldir = path.resolve(LIB, dir);
211 if (fs.existsSync(fulldir)) return;
212 makeDir(path.dirname(fulldir));
213 fs.mkdirSync(fulldir);
214 }
215
216 /**
217 * Make a file in the library directory from the given lines of javascript
218 *
219 * @param {string} file The name of the file relative to the root .ts directory
220 * @param {string[]} lines The contents of the file to create
221 */
222 function makeFile(file, lines) {
223 if (!lines.length) return;
224 const [dir, name] = [path.dirname(file), path.basename(file)];
225 makeDir(dir);
226 fs.writeFileSync(path.resolve(LIB, dir, name.replace(/\.ts$/, '.js')), lines.join('\n') + '\n');
227 }
228
229 /**
230 * Make the library file that adds all the exported objects into the MathJax global object
231 */
232 function processGlobal() {
233 console.info(' ' + COMPONENT + '.ts');
234 const lines = [
235 `import {combineWithMathJax} from '${GLOBAL}';`,
236 `import {VERSION} from '${VERSION}';`,
237 '',
238 ];
239 const packages = [];
240 PACKAGE = PACKAGE.sort(sortDir);
241 while (PACKAGE.length) {
242 const dir = path.dirname(PACKAGE[0]).split(path.sep)[0];
243 packages.push(processPackage(lines, INDENT, dir));
244 }
245 const name = (ID.match(/[^a-zA-Z0-9_]/) ? `"${ID}"` : ID);
246 lines.push(
247 '',
248 'if (MathJax.loader) {',
249 INDENT + `MathJax.loader.checkVersion('${ID}', VERSION, '${TYPE}');`,
250 '}',
251 '',
252 `combineWithMathJax({_: {`,
253 INDENT + packages.join(',\n' + INDENT),
254 '}});'
255 );
256 fs.writeFileSync(path.join(LIB, COMPONENT + '.js'), lines.join('\n') + '\n');
257 }
258
259 /**
260 * Sort file paths alphabetically
261 */
262 function sortDir(a, b) {
263 const A = a.replace(/\//g, '|'); // Replace directory separator by one that is after the alphnumerics
264 const B = b.replace(/\//g, '|');
265 return (A === B ? 0 : A < B ? -1 : 1);
266 }
267
268 let importCount = 0;
269 /**
270 * Recursively process packages, collecting them into groups by subdirectory, properly indented
271 *
272 * @param {string[]} lines The array where lines of code defining the packages are to be stored
273 * @param {string} space The current level of indentation
274 * @param {string} dir The subdirectory currently being processed
275 * @return {string} The string to use to load all the objects from the given directory
276 */
277 function processPackage(lines, space, dir) {
278 const packages = [];
279 //
280 // Loop through the lines that are in the current directory
281 //
282 while (PACKAGE.length && (PACKAGE[0].substr(0, dir.length) === dir || dir === '.')) {
283 //
284 // If the current package is in this directory (not a subdirectory)
285 // Get the location of transpiled mathjax file
286 // Get the name to use for the data from that file
287 // Create an entry for the file in the MathJax global that loads the reuired component
288 // Otherwise (its in a subdirectory)
289 // Get the subdirectory name
290 // Process the subdirectory using an additional indentation
291 //
292 if (path.dirname(PACKAGE[0]) === dir) {
293 const file = PACKAGE.shift();
294 const name = path.basename(file);
295 const relativefile = path.join('..', JS, dir, name).replace(/\.ts$/, '.js');
296 const component = 'module' + (++importCount);
297 lines.push(`import * as ${component} from '${relativefile}';`);
298 let property = name.replace(/\.ts$/, '');
299 if (property !== name && exists(path.resolve(JS, file.replace(/\.ts$/, '')))) {
300 property += '_ts';
301 }
302 if (property.match(/[^a-zA-Z0-9_]/)) {
303 property = `"${property}"`;
304 }
305 packages.push(`${property}: ${component}`);
306 } else {
307 let subdir = path.dirname(PACKAGE[0]);
308 while (path.dirname(subdir) !== dir && subdir !== '.') {
309 subdir = path.dirname(subdir);
310 }
311 packages.push(processPackage(lines, space + (dir === '.' ? '' : INDENT), subdir));
312 }
313 }
314 //
315 // Create the string defining the object that loads all the needed files into the proper places
316 //
317 if (dir === '.') return packages.join(',\n ');
318 return path.basename(dir) + ': {\n' + INDENT + space + packages.join(',\n' + INDENT + space) + '\n' + space + '}';
319 }
320
321 /**
322 * @param {string} dir The path to the directory tree to be removed (recursively)
323 */
324 function rmDir(dir) {
325 if (!dir) return;
326 if (fs.existsSync(dir)) {
327 for (const name of fs.readdirSync(dir)) {
328 const file = path.join(dir, name);
329 if (fs.lstatSync(file).isDirectory()) {
330 rmDir(file);
331 } else {
332 fs.unlinkSync(file);
333 }
334 }
335 fs.rmdirSync(dir);
336 }
337 }
338
339 //
340 // Remove the existing lib directory contents, if any.
341 // Load all the target files from the MathJax .ts directory.
342 // Create the file that loads all the target objects into the MathJax global object.
343 //
344 rmDir(LIB);
345 console.info("Processing:");
346 processList(TS, '', TARGETS);
347 processGlobal();