target.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. /** @template T @typedef {{ [P in keyof T]?: never }} Never<T> */
  59. /** @template A @template B @typedef {(A & Never<B>) | (Never<A> & B) | (A & B)} Mix<A,B> */
  60. /** @typedef {Mix<Mix<PlatformTargetProperties, ElectronContextTargetProperties>, Mix<ApiTargetProperties, EcmaTargetProperties>>} TargetProperties */
  61. const versionDependent = (major, minor) => {
  62. if (!major) return () => /** @type {undefined} */ (undefined);
  63. major = +major;
  64. minor = minor ? +minor : 0;
  65. return (vMajor, vMinor = 0) => {
  66. return major > vMajor || (major === vMajor && minor >= vMinor);
  67. };
  68. };
  69. /** @type {[string, string, RegExp, (...args: string[]) => TargetProperties | false][]} */
  70. const TARGETS = [
  71. [
  72. "browserslist / browserslist:env / browserslist:query / browserslist:path-to-config / browserslist:path-to-config:env",
  73. "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",
  74. /^browserslist(?::(.+))?$/,
  75. (rest, context) => {
  76. const browserslistTargetHandler = getBrowserslistTargetHandler();
  77. const browsers = browserslistTargetHandler.load(
  78. rest ? rest.trim() : null,
  79. context
  80. );
  81. if (!browsers) {
  82. throw new Error(`No browserslist config found to handle the 'browserslist' target.
  83. See https://github.com/browserslist/browserslist#queries for possible ways to provide a config.
  84. The recommended way is to add a 'browserslist' key to your package.json and list supported browsers (resp. node.js versions).
  85. You can also more options via the 'target' option: 'browserslist' / 'browserslist:env' / 'browserslist:query' / 'browserslist:path-to-config' / 'browserslist:path-to-config:env'`);
  86. }
  87. return browserslistTargetHandler.resolve(browsers);
  88. }
  89. ],
  90. [
  91. "web",
  92. "Web browser.",
  93. /^web$/,
  94. () => {
  95. return {
  96. web: true,
  97. browser: true,
  98. webworker: null,
  99. node: false,
  100. electron: false,
  101. nwjs: false,
  102. document: true,
  103. importScriptsInWorker: true,
  104. fetchWasm: true,
  105. nodeBuiltins: false,
  106. importScripts: false,
  107. require: false,
  108. global: false
  109. };
  110. }
  111. ],
  112. [
  113. "webworker",
  114. "Web Worker, SharedWorker or Service Worker.",
  115. /^webworker$/,
  116. () => {
  117. return {
  118. web: true,
  119. browser: true,
  120. webworker: true,
  121. node: false,
  122. electron: false,
  123. nwjs: false,
  124. importScripts: true,
  125. importScriptsInWorker: true,
  126. fetchWasm: true,
  127. nodeBuiltins: false,
  128. require: false,
  129. document: false,
  130. global: false
  131. };
  132. }
  133. ],
  134. [
  135. "[async-]node[X[.Y]]",
  136. "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.",
  137. /^(async-)?node(\d+(?:\.(\d+))?)?$/,
  138. (asyncFlag, major, minor) => {
  139. const v = versionDependent(major, minor);
  140. // see https://node.green/
  141. return {
  142. node: true,
  143. electron: false,
  144. nwjs: false,
  145. web: false,
  146. webworker: false,
  147. browser: false,
  148. require: !asyncFlag,
  149. nodeBuiltins: true,
  150. global: true,
  151. document: false,
  152. fetchWasm: false,
  153. importScripts: false,
  154. importScriptsInWorker: false,
  155. globalThis: v(12),
  156. const: v(6),
  157. templateLiteral: v(4),
  158. optionalChaining: v(14),
  159. arrowFunction: v(6),
  160. forOf: v(5),
  161. destructuring: v(6),
  162. bigIntLiteral: v(10, 4),
  163. dynamicImport: v(12, 17),
  164. dynamicImportInWorker: major ? false : undefined,
  165. module: v(12, 17)
  166. };
  167. }
  168. ],
  169. [
  170. "electron[X[.Y]]-main/preload/renderer",
  171. "Electron in version X.Y. Script is running in main, preload resp. renderer context.",
  172. /^electron(\d+(?:\.(\d+))?)?-(main|preload|renderer)$/,
  173. (major, minor, context) => {
  174. const v = versionDependent(major, minor);
  175. // see https://node.green/ + https://github.com/electron/releases
  176. return {
  177. node: true,
  178. electron: true,
  179. web: context !== "main",
  180. webworker: false,
  181. browser: false,
  182. nwjs: false,
  183. electronMain: context === "main",
  184. electronPreload: context === "preload",
  185. electronRenderer: context === "renderer",
  186. global: true,
  187. nodeBuiltins: true,
  188. require: true,
  189. document: context === "renderer",
  190. fetchWasm: context === "renderer",
  191. importScripts: false,
  192. importScriptsInWorker: true,
  193. globalThis: v(5),
  194. const: v(1, 1),
  195. templateLiteral: v(1, 1),
  196. optionalChaining: v(8),
  197. arrowFunction: v(1, 1),
  198. forOf: v(0, 36),
  199. destructuring: v(1, 1),
  200. bigIntLiteral: v(4),
  201. dynamicImport: v(11),
  202. dynamicImportInWorker: major ? false : undefined,
  203. module: v(11)
  204. };
  205. }
  206. ],
  207. [
  208. "nwjs[X[.Y]] / node-webkit[X[.Y]]",
  209. "NW.js in version X.Y.",
  210. /^(?:nwjs|node-webkit)(\d+(?:\.(\d+))?)?$/,
  211. (major, minor) => {
  212. const v = versionDependent(major, minor);
  213. // see https://node.green/ + https://github.com/nwjs/nw.js/blob/nw48/CHANGELOG.md
  214. return {
  215. node: true,
  216. web: true,
  217. nwjs: true,
  218. webworker: null,
  219. browser: false,
  220. electron: false,
  221. global: true,
  222. nodeBuiltins: true,
  223. document: false,
  224. importScriptsInWorker: false,
  225. fetchWasm: false,
  226. importScripts: false,
  227. require: false,
  228. globalThis: v(0, 43),
  229. const: v(0, 15),
  230. templateLiteral: v(0, 13),
  231. optionalChaining: v(0, 44),
  232. arrowFunction: v(0, 15),
  233. forOf: v(0, 13),
  234. destructuring: v(0, 15),
  235. bigIntLiteral: v(0, 32),
  236. dynamicImport: v(0, 43),
  237. dynamicImportInWorker: major ? false : undefined,
  238. module: v(0, 43)
  239. };
  240. }
  241. ],
  242. [
  243. "esX",
  244. "EcmaScript in this version. Examples: es2020, es5.",
  245. /^es(\d+)$/,
  246. version => {
  247. let v = +version;
  248. if (v < 1000) v = v + 2009;
  249. return {
  250. const: v >= 2015,
  251. templateLiteral: v >= 2015,
  252. optionalChaining: v >= 2020,
  253. arrowFunction: v >= 2015,
  254. forOf: v >= 2015,
  255. destructuring: v >= 2015,
  256. module: v >= 2015,
  257. globalThis: v >= 2020,
  258. bigIntLiteral: v >= 2020,
  259. dynamicImport: v >= 2020,
  260. dynamicImportInWorker: v >= 2020
  261. };
  262. }
  263. ]
  264. ];
  265. /**
  266. * @param {string} target the target
  267. * @param {string} context the context directory
  268. * @returns {TargetProperties} target properties
  269. */
  270. const getTargetProperties = (target, context) => {
  271. for (const [, , regExp, handler] of TARGETS) {
  272. const match = regExp.exec(target);
  273. if (match) {
  274. const [, ...args] = match;
  275. const result = handler(...args, context);
  276. if (result) return result;
  277. }
  278. }
  279. throw new Error(
  280. `Unknown target '${target}'. The following targets are supported:\n${TARGETS.map(
  281. ([name, description]) => `* ${name}: ${description}`
  282. ).join("\n")}`
  283. );
  284. };
  285. const mergeTargetProperties = targetProperties => {
  286. const keys = new Set();
  287. for (const tp of targetProperties) {
  288. for (const key of Object.keys(tp)) {
  289. keys.add(key);
  290. }
  291. }
  292. const result = {};
  293. for (const key of keys) {
  294. let hasTrue = false;
  295. let hasFalse = false;
  296. for (const tp of targetProperties) {
  297. const value = tp[key];
  298. switch (value) {
  299. case true:
  300. hasTrue = true;
  301. break;
  302. case false:
  303. hasFalse = true;
  304. break;
  305. }
  306. }
  307. if (hasTrue || hasFalse)
  308. result[key] = hasFalse && hasTrue ? null : hasTrue ? true : false;
  309. }
  310. return /** @type {TargetProperties} */ (result);
  311. };
  312. /**
  313. * @param {string[]} targets the targets
  314. * @param {string} context the context directory
  315. * @returns {TargetProperties} target properties
  316. */
  317. const getTargetsProperties = (targets, context) => {
  318. return mergeTargetProperties(
  319. targets.map(t => getTargetProperties(t, context))
  320. );
  321. };
  322. exports.getDefaultTarget = getDefaultTarget;
  323. exports.getTargetProperties = getTargetProperties;
  324. exports.getTargetsProperties = getTargetsProperties;