summaryrefslogtreecommitdiff
path: root/thirdparty/preact/config/codemod-const.js
blob: 4bffd9add2e55cef17caf2fe913611a7867ef42b (plain)
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
/* eslint no-console:0 */

/** Find constants (identified by ALL_CAPS_DECLARATIONS), and inline them globally.
 *	This is safe because Preact *only* uses global constants.
 */
export default (file, api) => {
	let j = api.jscodeshift,
		code = j(file.source),
		constants = {},
		found = 0;

	code.find(j.VariableDeclaration)
		.filter( decl => {
			for (let i=decl.value.declarations.length; i--; ) {
				let node = decl.value.declarations[i],
					name = node.id && node.id.name,
					init = node.init;
				if (name && init && name.match(/^[A-Z0-9_$]+$/g)) {
					if (init.type==='Literal') {
						console.log(`Inlining constant: ${name}=${init.raw}`);
						found++;
						constants[name] = init;
						// remove declaration
						decl.value.declarations.splice(i, 1);
						// if it's the last, we'll remove the whole statement
						return !decl.value.declarations.length;
					}
				}
			}
			return false;
		})
		.remove();

	code.find(j.Identifier)
		.filter( path => path.value.name && constants.hasOwnProperty(path.value.name) )
		.replaceWith( path => (found++, constants[path.value.name]) );

	return found ? code.toSource({ quote: 'single' }) : null;
};