propmangle.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. /***********************************************************************
  2. A JavaScript tokenizer / parser / beautifier / compressor.
  3. https://github.com/mishoo/UglifyJS2
  4. -------------------------------- (C) ---------------------------------
  5. Author: Mihai Bazon
  6. <mihai.bazon@gmail.com>
  7. http://mihai.bazon.net/blog
  8. Distributed under the BSD license:
  9. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  10. Redistribution and use in source and binary forms, with or without
  11. modification, are permitted provided that the following conditions
  12. are met:
  13. * Redistributions of source code must retain the above
  14. copyright notice, this list of conditions and the following
  15. disclaimer.
  16. * Redistributions in binary form must reproduce the above
  17. copyright notice, this list of conditions and the following
  18. disclaimer in the documentation and/or other materials
  19. provided with the distribution.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  21. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  22. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  23. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  24. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  25. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  26. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  27. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  29. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  30. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  31. SUCH DAMAGE.
  32. ***********************************************************************/
  33. "use strict";
  34. /* global global, self */
  35. import {
  36. defaults,
  37. push_uniq,
  38. has_annotation,
  39. clear_annotation,
  40. } from "./utils/index.js";
  41. import { base54 } from "./scope.js";
  42. import {
  43. AST_Binary,
  44. AST_Call,
  45. AST_ClassPrivateProperty,
  46. AST_Conditional,
  47. AST_Dot,
  48. AST_DotHash,
  49. AST_ObjectKeyVal,
  50. AST_ObjectProperty,
  51. AST_PrivateMethod,
  52. AST_PrivateGetter,
  53. AST_PrivateSetter,
  54. AST_PrivateIn,
  55. AST_Sequence,
  56. AST_String,
  57. AST_Sub,
  58. TreeTransformer,
  59. TreeWalker,
  60. _KEY,
  61. _MANGLEPROP,
  62. walk,
  63. } from "./ast.js";
  64. import { domprops } from "../tools/domprops.js";
  65. function find_builtins(reserved) {
  66. domprops.forEach(add);
  67. // Compatibility fix for some standard defined globals not defined on every js environment
  68. var new_globals = ["Symbol", "Map", "Promise", "Proxy", "Reflect", "Set", "WeakMap", "WeakSet"];
  69. var objects = {};
  70. var global_ref = typeof global === "object" ? global : self;
  71. new_globals.forEach(function (new_global) {
  72. objects[new_global] = global_ref[new_global] || function() {};
  73. });
  74. [
  75. "null",
  76. "true",
  77. "false",
  78. "NaN",
  79. "Infinity",
  80. "-Infinity",
  81. "undefined",
  82. ].forEach(add);
  83. [ Object, Array, Function, Number,
  84. String, Boolean, Error, Math,
  85. Date, RegExp, objects.Symbol, ArrayBuffer,
  86. DataView, decodeURI, decodeURIComponent,
  87. encodeURI, encodeURIComponent, eval, EvalError,
  88. Float32Array, Float64Array, Int8Array, Int16Array,
  89. Int32Array, isFinite, isNaN, JSON, objects.Map, parseFloat,
  90. parseInt, objects.Promise, objects.Proxy, RangeError, ReferenceError,
  91. objects.Reflect, objects.Set, SyntaxError, TypeError, Uint8Array,
  92. Uint8ClampedArray, Uint16Array, Uint32Array, URIError,
  93. objects.WeakMap, objects.WeakSet
  94. ].forEach(function(ctor) {
  95. Object.getOwnPropertyNames(ctor).map(add);
  96. if (ctor.prototype) {
  97. Object.getOwnPropertyNames(ctor.prototype).map(add);
  98. }
  99. });
  100. function add(name) {
  101. reserved.add(name);
  102. }
  103. }
  104. function reserve_quoted_keys(ast, reserved) {
  105. function add(name) {
  106. push_uniq(reserved, name);
  107. }
  108. ast.walk(new TreeWalker(function(node) {
  109. if (node instanceof AST_ObjectKeyVal && node.quote) {
  110. add(node.key);
  111. } else if (node instanceof AST_ObjectProperty && node.quote) {
  112. add(node.key.name);
  113. } else if (node instanceof AST_Sub) {
  114. addStrings(node.property, add);
  115. }
  116. }));
  117. }
  118. function addStrings(node, add) {
  119. node.walk(new TreeWalker(function(node) {
  120. if (node instanceof AST_Sequence) {
  121. addStrings(node.tail_node(), add);
  122. } else if (node instanceof AST_String) {
  123. add(node.value);
  124. } else if (node instanceof AST_Conditional) {
  125. addStrings(node.consequent, add);
  126. addStrings(node.alternative, add);
  127. }
  128. return true;
  129. }));
  130. }
  131. function mangle_private_properties(ast, options) {
  132. var cprivate = -1;
  133. var private_cache = new Map();
  134. var nth_identifier = options.nth_identifier || base54;
  135. ast = ast.transform(new TreeTransformer(function(node) {
  136. if (
  137. node instanceof AST_ClassPrivateProperty
  138. || node instanceof AST_PrivateMethod
  139. || node instanceof AST_PrivateGetter
  140. || node instanceof AST_PrivateSetter
  141. || node instanceof AST_PrivateIn
  142. ) {
  143. node.key.name = mangle_private(node.key.name);
  144. } else if (node instanceof AST_DotHash) {
  145. node.property = mangle_private(node.property);
  146. }
  147. }));
  148. return ast;
  149. function mangle_private(name) {
  150. let mangled = private_cache.get(name);
  151. if (!mangled) {
  152. mangled = nth_identifier.get(++cprivate);
  153. private_cache.set(name, mangled);
  154. }
  155. return mangled;
  156. }
  157. }
  158. function find_annotated_props(ast) {
  159. var annotated_props = new Set();
  160. walk(ast, node => {
  161. if (
  162. node instanceof AST_ClassPrivateProperty
  163. || node instanceof AST_PrivateMethod
  164. || node instanceof AST_PrivateGetter
  165. || node instanceof AST_PrivateSetter
  166. || node instanceof AST_DotHash
  167. ) {
  168. // handled by mangle_private_properties
  169. } else if (node instanceof AST_ObjectKeyVal) {
  170. if (typeof node.key == "string" && has_annotation(node, _MANGLEPROP)) {
  171. annotated_props.add(node.key);
  172. }
  173. } else if (node instanceof AST_ObjectProperty) {
  174. // setter or getter, since KeyVal is handled above
  175. if (has_annotation(node, _MANGLEPROP)) {
  176. annotated_props.add(node.key.name);
  177. }
  178. } else if (node instanceof AST_Dot) {
  179. if (has_annotation(node, _MANGLEPROP)) {
  180. annotated_props.add(node.property);
  181. }
  182. } else if (node instanceof AST_Sub) {
  183. if (node.property instanceof AST_String && has_annotation(node, _MANGLEPROP)) {
  184. annotated_props.add(node.property.value);
  185. }
  186. }
  187. });
  188. return annotated_props;
  189. }
  190. function mangle_properties(ast, options, annotated_props = find_annotated_props(ast)) {
  191. options = defaults(options, {
  192. builtins: false,
  193. cache: null,
  194. debug: false,
  195. keep_quoted: false,
  196. nth_identifier: base54,
  197. only_cache: false,
  198. regex: null,
  199. reserved: null,
  200. undeclared: false,
  201. only_annotated: false,
  202. }, true);
  203. var nth_identifier = options.nth_identifier;
  204. var reserved_option = options.reserved;
  205. if (!Array.isArray(reserved_option)) reserved_option = [reserved_option];
  206. var reserved = new Set(reserved_option);
  207. if (!options.builtins) find_builtins(reserved);
  208. var cname = -1;
  209. var cache;
  210. if (options.cache) {
  211. cache = options.cache.props;
  212. } else {
  213. cache = new Map();
  214. }
  215. var only_annotated = options.only_annotated;
  216. var regex = options.regex && new RegExp(options.regex);
  217. // note debug is either false (disabled), or a string of the debug suffix to use (enabled).
  218. // note debug may be enabled as an empty string, which is falsey. Also treat passing 'true'
  219. // the same as passing an empty string.
  220. var debug = options.debug !== false;
  221. var debug_name_suffix;
  222. if (debug) {
  223. debug_name_suffix = (options.debug === true ? "" : options.debug);
  224. }
  225. var names_to_mangle = new Set();
  226. var unmangleable = new Set();
  227. // Track each already-mangled name to prevent nth_identifier from generating
  228. // the same name.
  229. cache.forEach((mangled_name) => unmangleable.add(mangled_name));
  230. var keep_quoted = !!options.keep_quoted;
  231. // step 1: find candidates to mangle
  232. ast.walk(new TreeWalker(function(node) {
  233. if (
  234. node instanceof AST_ClassPrivateProperty
  235. || node instanceof AST_PrivateMethod
  236. || node instanceof AST_PrivateGetter
  237. || node instanceof AST_PrivateSetter
  238. || node instanceof AST_DotHash
  239. ) {
  240. // handled by mangle_private_properties
  241. } else if (node instanceof AST_ObjectKeyVal) {
  242. if (typeof node.key == "string" && (!keep_quoted || !node.quote)) {
  243. add(node.key);
  244. }
  245. } else if (node instanceof AST_ObjectProperty) {
  246. // setter or getter, since KeyVal is handled above
  247. if (!keep_quoted || !node.quote) {
  248. add(node.key.name);
  249. }
  250. } else if (node instanceof AST_Dot) {
  251. var declared = !!options.undeclared;
  252. if (!declared) {
  253. var root = node;
  254. while (root.expression) {
  255. root = root.expression;
  256. }
  257. declared = !(root.thedef && root.thedef.undeclared);
  258. }
  259. if (declared &&
  260. (!keep_quoted || !node.quote)) {
  261. add(node.property);
  262. }
  263. } else if (node instanceof AST_Sub) {
  264. if (!keep_quoted) {
  265. addStrings(node.property, add);
  266. }
  267. } else if (node instanceof AST_Call
  268. && node.expression.print_to_string() == "Object.defineProperty") {
  269. addStrings(node.args[1], add);
  270. } else if (node instanceof AST_Binary && node.operator === "in") {
  271. addStrings(node.left, add);
  272. } else if (node instanceof AST_String && has_annotation(node, _KEY)) {
  273. add(node.value);
  274. }
  275. }));
  276. // step 2: transform the tree, renaming properties
  277. return ast.transform(new TreeTransformer(function(node) {
  278. if (
  279. node instanceof AST_ClassPrivateProperty
  280. || node instanceof AST_PrivateMethod
  281. || node instanceof AST_PrivateGetter
  282. || node instanceof AST_PrivateSetter
  283. || node instanceof AST_DotHash
  284. ) {
  285. // handled by mangle_private_properties
  286. } else if (node instanceof AST_ObjectKeyVal) {
  287. if (typeof node.key == "string" && (!keep_quoted || !node.quote)) {
  288. node.key = mangle(node.key);
  289. }
  290. } else if (node instanceof AST_ObjectProperty) {
  291. // setter, getter, method or class field
  292. if (!keep_quoted || !node.quote) {
  293. node.key.name = mangle(node.key.name);
  294. }
  295. } else if (node instanceof AST_Dot) {
  296. if (!keep_quoted || !node.quote) {
  297. node.property = mangle(node.property);
  298. }
  299. } else if (!keep_quoted && node instanceof AST_Sub) {
  300. node.property = mangleStrings(node.property);
  301. } else if (node instanceof AST_Call
  302. && node.expression.print_to_string() == "Object.defineProperty") {
  303. node.args[1] = mangleStrings(node.args[1]);
  304. } else if (node instanceof AST_Binary && node.operator === "in") {
  305. node.left = mangleStrings(node.left);
  306. } else if (node instanceof AST_String && has_annotation(node, _KEY)) {
  307. // Clear _KEY annotation to prevent double mangling
  308. clear_annotation(node, _KEY);
  309. node.value = mangle(node.value);
  310. }
  311. }));
  312. // only function declarations after this line
  313. function can_mangle(name) {
  314. if (unmangleable.has(name)) return false;
  315. if (reserved.has(name)) return false;
  316. if (options.only_cache) {
  317. return cache.has(name);
  318. }
  319. if (/^-?[0-9]+(\.[0-9]+)?(e[+-][0-9]+)?$/.test(name)) return false;
  320. return true;
  321. }
  322. function should_mangle(name) {
  323. if (only_annotated && !annotated_props.has(name)) return false;
  324. if (regex && !regex.test(name)) {
  325. return annotated_props.has(name);
  326. }
  327. if (reserved.has(name)) return false;
  328. return cache.has(name)
  329. || names_to_mangle.has(name);
  330. }
  331. function add(name) {
  332. if (can_mangle(name)) {
  333. names_to_mangle.add(name);
  334. }
  335. if (!should_mangle(name)) {
  336. unmangleable.add(name);
  337. }
  338. }
  339. function mangle(name) {
  340. if (!should_mangle(name)) {
  341. return name;
  342. }
  343. var mangled = cache.get(name);
  344. if (!mangled) {
  345. if (debug) {
  346. // debug mode: use a prefix and suffix to preserve readability, e.g. o.foo -> o._$foo$NNN_.
  347. var debug_mangled = "_$" + name + "$" + debug_name_suffix + "_";
  348. if (can_mangle(debug_mangled)) {
  349. mangled = debug_mangled;
  350. }
  351. }
  352. // either debug mode is off, or it is on and we could not use the mangled name
  353. if (!mangled) {
  354. do {
  355. mangled = nth_identifier.get(++cname);
  356. } while (!can_mangle(mangled));
  357. }
  358. cache.set(name, mangled);
  359. }
  360. return mangled;
  361. }
  362. function mangleStrings(node) {
  363. return node.transform(new TreeTransformer(function(node) {
  364. if (node instanceof AST_Sequence) {
  365. var last = node.expressions.length - 1;
  366. node.expressions[last] = mangleStrings(node.expressions[last]);
  367. } else if (node instanceof AST_String) {
  368. // Clear _KEY annotation to prevent double mangling
  369. clear_annotation(node, _KEY);
  370. node.value = mangle(node.value);
  371. } else if (node instanceof AST_Conditional) {
  372. node.consequent = mangleStrings(node.consequent);
  373. node.alternative = mangleStrings(node.alternative);
  374. }
  375. return node;
  376. }));
  377. }
  378. }
  379. export {
  380. reserve_quoted_keys,
  381. mangle_properties,
  382. mangle_private_properties,
  383. find_annotated_props,
  384. };