target.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const memoize = require("../util/memoize");
  7. const getBrowserslistTargetHandler = memoize(() =>
  8. require("./browserslistTargetHandler")
  9. );
  10. /**
  11. * @param {string} context the context directory
  12. * @returns {string} default target
  13. */
  14. const getDefaultTarget = context => {
  15. const browsers = getBrowserslistTargetHandler().load(null, context);
  16. return browsers ? "browserslist" : "web";
  17. };
  18. /**
  19. * @typedef {Object} PlatformTargetProperties
  20. * @property {boolean | null} web web platform, importing of http(s) and std: is available
  21. * @property {boolean | null} browser browser platform, running in a normal web browser
  22. * @property {boolean | null} webworker (Web)Worker platform, running in a web/shared/service worker
  23. * @property {boolean | null} node node platform, require of node built-in modules is available
  24. * @property {boolean | null} nwjs nwjs platform, require of legacy nw.gui is available
  25. * @property {boolean | null} electron electron platform, require of some electron built-in modules is available
  26. */
  27. /**
  28. * @typedef {Object} ElectronContextTargetProperties
  29. * @property {boolean | null} electronMain in main context
  30. * @property {boolean | null} electronPreload in preload context
  31. * @property {boolean | null} electronRenderer in renderer context with node integration
  32. */
  33. /**
  34. * @typedef {Object} ApiTargetProperties
  35. * @property {boolean | null} require has require function available
  36. * @property {boolean | null} nodeBuiltins has node.js built-in modules available
  37. * @property {boolean | null} document has document available (allows script tags)
  38. * @property {boolean | null} importScripts has importScripts available
  39. * @property {boolean | null} importScriptsInWorker has importScripts available when creating a worker
  40. * @property {boolean | null} fetchWasm has fetch function available for WebAssembly
  41. * @property {boolean | null} global has global variable available
  42. */
  43. /**
  44. * @typedef {Object} EcmaTargetProperties
  45. * @property {boolean | null} globalThis has globalThis variable available
  46. * @property {boolean | null} bigIntLiteral big int literal syntax is available
  47. * @property {boolean | null} const const and let variable declarations are available
  48. * @property {boolean | null} arrowFunction arrow functions are available
  49. * @property {boolean | null} forOf for of iteration is available
  50. * @property {boolean | null} destructuring destructuring is available
  51. * @property {boolean | null} dynamicImport async import() is available
  52. * @property {boolean | null} dynamicImportInWorker async import() is available when creating a worker
  53. * @property {boolean | null} module ESM syntax is available (when in module)
  54. * @property {boolean | null} optionalChaining optional chaining is available
  55. * @property {boolean | null} templateLiteral template literal is available
  56. */
  57. ///** @typedef {PlatformTargetProperties | ApiTargetProperties | EcmaTargetProperties | PlatformTargetProperties & ApiTargetProperties | PlatformTargetProperties & EcmaTargetProperties | ApiTargetProperties & EcmaTargetProperties} TargetProperties */
  58. /**
  59. * @template T
  60. * @typedef {{ [P in keyof T]?: never }} Never<T>
  61. */
  62. /**
  63. * @template A
  64. * @template B
  65. * @typedef {(A & Never<B>) | (Never<A> & B) | (A & B)} Mix<A, B>
  66. */
  67. /** @typedef {Mix<Mix<PlatformTargetProperties, ElectronContextTargetProperties>, Mix<ApiTargetProperties, EcmaTargetProperties>>} TargetProperties */
  68. /**
  69. * @param {string} major major version
  70. * @param {string | undefined} minor minor version
  71. * @returns {(vMajor: number, vMinor?: number) => boolean | undefined} check if version is greater or equal
  72. */
  73. const versionDependent = (major, minor) => {
  74. if (!major) {
  75. return () => /** @type {undefined} */ (undefined);
  76. }
  77. /** @type {number} */
  78. const nMajor = +major;
  79. /** @type {number} */
  80. const nMinor = minor ? +minor : 0;
  81. return (vMajor, vMinor = 0) => {
  82. return nMajor > vMajor || (nMajor === vMajor && nMinor >= vMinor);
  83. };
  84. };
  85. /** @type {[string, string, RegExp, (...args: string[]) => Partial<TargetProperties>][]} */
  86. const TARGETS = [
  87. [
  88. "browserslist / browserslist:env / browserslist:query / browserslist:path-to-config / browserslist:path-to-config:env",
  89. "Resolve features from browserslist. Will resolve browserslist config automatically. Only browser or node queries are supported (electron is not supported). Examples: 'browserslist:modern' to use 'modern' environment from browserslist config",
  90. /^browserslist(?::(.+))?$/,
  91. (rest, context) => {
  92. const browserslistTargetHandler = getBrowserslistTargetHandler();
  93. const browsers = browserslistTargetHandler.load(
  94. rest ? rest.trim() : null,
  95. context
  96. );
  97. if (!browsers) {
  98. throw new Error(`No browserslist config found to handle the 'browserslist' target.
  99. See https://github.com/browserslist/browserslist#queries for possible ways to provide a config.
  100. The recommended way is to add a 'browserslist' key to your package.json and list supported browsers (resp. node.js versions).
  101. You can also more options via the 'target' option: 'browserslist' / 'browserslist:env' / 'browserslist:query' / 'browserslist:path-to-config' / 'browserslist:path-to-config:env'`);
  102. }
  103. return browserslistTargetHandler.resolve(browsers);
  104. }
  105. ],
  106. [
  107. "web",
  108. "Web browser.",
  109. /^web$/,
  110. () => {
  111. return {
  112. web: true,
  113. browser: true,
  114. webworker: null,
  115. node: false,
  116. electron: false,
  117. nwjs: false,
  118. document: true,
  119. importScriptsInWorker: true,
  120. fetchWasm: true,
  121. nodeBuiltins: false,
  122. importScripts: false,
  123. require: false,
  124. global: false
  125. };
  126. }
  127. ],
  128. [
  129. "webworker",
  130. "Web Worker, SharedWorker or Service Worker.",
  131. /^webworker$/,
  132. () => {
  133. return {
  134. web: true,
  135. browser: true,
  136. webworker: true,
  137. node: false,
  138. electron: false,
  139. nwjs: false,
  140. importScripts: true,
  141. importScriptsInWorker: true,
  142. fetchWasm: true,
  143. nodeBuiltins: false,
  144. require: false,
  145. document: false,
  146. global: false
  147. };
  148. }
  149. ],
  150. [
  151. "[async-]node[X[.Y]]",
  152. "Node.js in version X.Y. The 'async-' prefix will load chunks asynchronously via 'fs' and 'vm' instead of 'require()'. Examples: node14.5, async-node10.",
  153. /^(async-)?node(\d+(?:\.(\d+))?)?$/,
  154. (asyncFlag, major, minor) => {
  155. const v = versionDependent(major, minor);
  156. // see https://node.green/
  157. return {
  158. node: true,
  159. electron: false,
  160. nwjs: false,
  161. web: false,
  162. webworker: false,
  163. browser: false,
  164. require: !asyncFlag,
  165. nodeBuiltins: true,
  166. global: true,
  167. document: false,
  168. fetchWasm: false,
  169. importScripts: false,
  170. importScriptsInWorker: false,
  171. globalThis: v(12),
  172. const: v(6),
  173. templateLiteral: v(4),
  174. optionalChaining: v(14),
  175. arrowFunction: v(6),
  176. forOf: v(5),
  177. destructuring: v(6),
  178. bigIntLiteral: v(10, 4),
  179. dynamicImport: v(12, 17),
  180. dynamicImportInWorker: major ? false : undefined,
  181. module: v(12, 17)
  182. };
  183. }
  184. ],
  185. [
  186. "electron[X[.Y]]-main/preload/renderer",
  187. "Electron in version X.Y. Script is running in main, preload resp. renderer context.",
  188. /^electron(\d+(?:\.(\d+))?)?-(main|preload|renderer)$/,
  189. (major, minor, context) => {
  190. const v = versionDependent(major, minor);
  191. // see https://node.green/ + https://github.com/electron/releases
  192. return {
  193. node: true,
  194. electron: true,
  195. web: context !== "main",
  196. webworker: false,
  197. browser: false,
  198. nwjs: false,
  199. electronMain: context === "main",
  200. electronPreload: context === "preload",
  201. electronRenderer: context === "renderer",
  202. global: true,
  203. nodeBuiltins: true,
  204. require: true,
  205. document: context === "renderer",
  206. fetchWasm: context === "renderer",
  207. importScripts: false,
  208. importScriptsInWorker: true,
  209. globalThis: v(5),
  210. const: v(1, 1),
  211. templateLiteral: v(1, 1),
  212. optionalChaining: v(8),
  213. arrowFunction: v(1, 1),
  214. forOf: v(0, 36),
  215. destructuring: v(1, 1),
  216. bigIntLiteral: v(4),
  217. dynamicImport: v(11),
  218. dynamicImportInWorker: major ? false : undefined,
  219. module: v(11)
  220. };
  221. }
  222. ],
  223. [
  224. "nwjs[X[.Y]] / node-webkit[X[.Y]]",
  225. "NW.js in version X.Y.",
  226. /^(?:nwjs|node-webkit)(\d+(?:\.(\d+))?)?$/,
  227. (major, minor) => {
  228. const v = versionDependent(major, minor);
  229. // see https://node.green/ + https://github.com/nwjs/nw.js/blob/nw48/CHANGELOG.md
  230. return {
  231. node: true,
  232. web: true,
  233. nwjs: true,
  234. webworker: null,
  235. browser: false,
  236. electron: false,
  237. global: true,
  238. nodeBuiltins: true,
  239. document: false,
  240. importScriptsInWorker: false,
  241. fetchWasm: false,
  242. importScripts: false,
  243. require: false,
  244. globalThis: v(0, 43),
  245. const: v(0, 15),
  246. templateLiteral: v(0, 13),
  247. optionalChaining: v(0, 44),
  248. arrowFunction: v(0, 15),
  249. forOf: v(0, 13),
  250. destructuring: v(0, 15),
  251. bigIntLiteral: v(0, 32),
  252. dynamicImport: v(0, 43),
  253. dynamicImportInWorker: major ? false : undefined,
  254. module: v(0, 43)
  255. };
  256. }
  257. ],
  258. [
  259. "esX",
  260. "EcmaScript in this version. Examples: es2020, es5.",
  261. /^es(\d+)$/,
  262. version => {
  263. let v = +version;
  264. if (v < 1000) v = v + 2009;
  265. return {
  266. const: v >= 2015,
  267. templateLiteral: v >= 2015,
  268. optionalChaining: v >= 2020,
  269. arrowFunction: v >= 2015,
  270. forOf: v >= 2015,
  271. destructuring: v >= 2015,
  272. module: v >= 2015,
  273. globalThis: v >= 2020,
  274. bigIntLiteral: v >= 2020,
  275. dynamicImport: v >= 2020,
  276. dynamicImportInWorker: v >= 2020
  277. };
  278. }
  279. ]
  280. ];
  281. /**
  282. * @param {string} target the target
  283. * @param {string} context the context directory
  284. * @returns {TargetProperties} target properties
  285. */
  286. const getTargetProperties = (target, context) => {
  287. for (const [, , regExp, handler] of TARGETS) {
  288. const match = regExp.exec(target);
  289. if (match) {
  290. const [, ...args] = match;
  291. const result = handler(...args, context);
  292. if (result) return /** @type {TargetProperties} */ (result);
  293. }
  294. }
  295. throw new Error(
  296. `Unknown target '${target}'. The following targets are supported:\n${TARGETS.map(
  297. ([name, description]) => `* ${name}: ${description}`
  298. ).join("\n")}`
  299. );
  300. };
  301. /**
  302. * @param {TargetProperties[]} targetProperties array of target properties
  303. * @returns {TargetProperties} merged target properties
  304. */
  305. const mergeTargetProperties = targetProperties => {
  306. /** @type {Set<keyof TargetProperties>} */
  307. const keys = new Set();
  308. for (const tp of targetProperties) {
  309. for (const key of Object.keys(tp)) {
  310. keys.add(/** @type {keyof TargetProperties} */ (key));
  311. }
  312. }
  313. /** @type {Object} */
  314. const result = {};
  315. for (const key of keys) {
  316. let hasTrue = false;
  317. let hasFalse = false;
  318. for (const tp of targetProperties) {
  319. const value = tp[key];
  320. switch (value) {
  321. case true:
  322. hasTrue = true;
  323. break;
  324. case false:
  325. hasFalse = true;
  326. break;
  327. }
  328. }
  329. if (hasTrue || hasFalse)
  330. /** @type {TargetProperties} */
  331. (result)[key] = hasFalse && hasTrue ? null : hasTrue ? true : false;
  332. }
  333. return /** @type {TargetProperties} */ (result);
  334. };
  335. /**
  336. * @param {string[]} targets the targets
  337. * @param {string} context the context directory
  338. * @returns {TargetProperties} target properties
  339. */
  340. const getTargetsProperties = (targets, context) => {
  341. return mergeTargetProperties(
  342. targets.map(t => getTargetProperties(t, context))
  343. );
  344. };
  345. exports.getDefaultTarget = getDefaultTarget;
  346. exports.getTargetProperties = getTargetProperties;
  347. exports.getTargetsProperties = getTargetsProperties;