index.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. "use strict";
  2. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  3. if (k2 === undefined) k2 = k;
  4. var desc = Object.getOwnPropertyDescriptor(m, k);
  5. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  6. desc = { enumerable: true, get: function() { return m[k]; } };
  7. }
  8. Object.defineProperty(o, k2, desc);
  9. }) : (function(o, m, k, k2) {
  10. if (k2 === undefined) k2 = k;
  11. o[k2] = m[k];
  12. }));
  13. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  14. Object.defineProperty(o, "default", { enumerable: true, value: v });
  15. }) : function(o, v) {
  16. o["default"] = v;
  17. });
  18. var __exportStar = (this && this.__exportStar) || function(m, exports) {
  19. for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
  20. };
  21. var __importStar = (this && this.__importStar) || function (mod) {
  22. if (mod && mod.__esModule) return mod;
  23. var result = {};
  24. if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  25. __setModuleDefault(result, mod);
  26. return result;
  27. };
  28. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  29. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  30. return new (P || (P = Promise))(function (resolve, reject) {
  31. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  32. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  33. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  34. step((generator = generator.apply(thisArg, _arguments || [])).next());
  35. });
  36. };
  37. var __rest = (this && this.__rest) || function (s, e) {
  38. var t = {};
  39. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  40. t[p] = s[p];
  41. if (s != null && typeof Object.getOwnPropertySymbols === "function")
  42. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  43. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  44. t[p[i]] = s[p[i]];
  45. }
  46. return t;
  47. };
  48. Object.defineProperty(exports, "__esModule", { value: true });
  49. exports.DEFAULT_EXTENSIONS = exports.getBinaryMetadata = exports.__experimental_registerGlobalTraceConfig = exports.minifySync = exports.minify = exports.bundle = exports.transformFileSync = exports.transformFile = exports.transformSync = exports.transform = exports.printSync = exports.print = exports.parseFileSync = exports.parseFile = exports.parseSync = exports.parse = exports.Compiler = exports.plugins = exports.version = void 0;
  50. const path_1 = require("path");
  51. __exportStar(require("@swc/types"), exports);
  52. const spack_1 = require("./spack");
  53. const assert = __importStar(require("assert"));
  54. // Allow overrides to the location of the .node binding file
  55. const bindingsOverride = process.env["SWC_BINARY_PATH"];
  56. // `@swc/core` includes d.ts for the `@swc/wasm` to provide typed fallback bindings
  57. // todo: fix package.json scripts
  58. let fallbackBindings;
  59. const bindings = (() => {
  60. let binding;
  61. try {
  62. binding = !!bindingsOverride ? require((0, path_1.resolve)(bindingsOverride)) : require('./binding');
  63. // If native binding loaded successfully, it should return proper target triple constant.
  64. const triple = binding.getTargetTriple();
  65. assert.ok(triple, 'Failed to read target triple from native binary.');
  66. return binding;
  67. }
  68. catch (_) {
  69. // postinstall supposed to install `@swc/wasm` already
  70. fallbackBindings = require('@swc/wasm');
  71. }
  72. finally {
  73. return binding;
  74. }
  75. })();
  76. /**
  77. * Version of the swc binding.
  78. */
  79. exports.version = require("./package.json").version;
  80. /**
  81. * @deprecated JavaScript API is deprecated. Please use Wasm plugin instead.
  82. */
  83. function plugins(ps) {
  84. return mod => {
  85. let m = mod;
  86. for (const p of ps) {
  87. m = p(m);
  88. }
  89. return m;
  90. };
  91. }
  92. exports.plugins = plugins;
  93. class Compiler {
  94. constructor() {
  95. this.fallbackBindingsPluginWarningDisplayed = false;
  96. }
  97. minify(src, opts) {
  98. return __awaiter(this, void 0, void 0, function* () {
  99. if (bindings) {
  100. return bindings.minify(toBuffer(src), toBuffer(opts !== null && opts !== void 0 ? opts : {}));
  101. }
  102. else if (fallbackBindings) {
  103. return fallbackBindings.minify(src, opts);
  104. }
  105. throw new Error('Bindings not found.');
  106. });
  107. }
  108. minifySync(src, opts) {
  109. if (bindings) {
  110. return bindings.minifySync(toBuffer(src), toBuffer(opts !== null && opts !== void 0 ? opts : {}));
  111. }
  112. else if (fallbackBindings) {
  113. return fallbackBindings.minifySync(src, opts);
  114. }
  115. throw new Error('Bindings not found.');
  116. }
  117. parse(src, options, filename) {
  118. return __awaiter(this, void 0, void 0, function* () {
  119. options = options || { syntax: "ecmascript" };
  120. options.syntax = options.syntax || "ecmascript";
  121. if (!bindings && !!fallbackBindings) {
  122. throw new Error('Fallback bindings does not support this interface yet.');
  123. }
  124. else if (!bindings) {
  125. throw new Error('Bindings not found.');
  126. }
  127. if (bindings) {
  128. const res = yield bindings.parse(src, toBuffer(options), filename);
  129. return JSON.parse(res);
  130. }
  131. else if (fallbackBindings) {
  132. return fallbackBindings.parse(src, options);
  133. }
  134. throw new Error('Bindings not found.');
  135. });
  136. }
  137. parseSync(src, options, filename) {
  138. options = options || { syntax: "ecmascript" };
  139. options.syntax = options.syntax || "ecmascript";
  140. if (bindings) {
  141. return JSON.parse(bindings.parseSync(src, toBuffer(options), filename));
  142. }
  143. else if (fallbackBindings) {
  144. return fallbackBindings.parseSync(src, options);
  145. }
  146. throw new Error('Bindings not found.');
  147. }
  148. parseFile(path, options) {
  149. return __awaiter(this, void 0, void 0, function* () {
  150. options = options || { syntax: "ecmascript" };
  151. options.syntax = options.syntax || "ecmascript";
  152. if (!bindings && !!fallbackBindings) {
  153. throw new Error('Fallback bindings does not support filesystem access.');
  154. }
  155. else if (!bindings) {
  156. throw new Error('Bindings not found.');
  157. }
  158. const res = yield bindings.parseFile(path, toBuffer(options));
  159. return JSON.parse(res);
  160. });
  161. }
  162. parseFileSync(path, options) {
  163. options = options || { syntax: "ecmascript" };
  164. options.syntax = options.syntax || "ecmascript";
  165. if (!bindings && !!fallbackBindings) {
  166. throw new Error('Fallback bindings does not support filesystem access');
  167. }
  168. else if (!bindings) {
  169. throw new Error('Bindings not found.');
  170. }
  171. return JSON.parse(bindings.parseFileSync(path, toBuffer(options)));
  172. }
  173. /**
  174. * Note: this method should be invoked on the compiler instance used
  175. * for `parse()` / `parseSync()`.
  176. */
  177. print(m, options) {
  178. return __awaiter(this, void 0, void 0, function* () {
  179. options = options || {};
  180. if (bindings) {
  181. return bindings.print(JSON.stringify(m), toBuffer(options));
  182. }
  183. else if (fallbackBindings) {
  184. return fallbackBindings.print(m, options);
  185. }
  186. throw new Error('Bindings not found.');
  187. });
  188. }
  189. /**
  190. * Note: this method should be invoked on the compiler instance used
  191. * for `parse()` / `parseSync()`.
  192. */
  193. printSync(m, options) {
  194. options = options || {};
  195. if (bindings) {
  196. return bindings.printSync(JSON.stringify(m), toBuffer(options));
  197. }
  198. else if (fallbackBindings) {
  199. return fallbackBindings.printSync(m, options);
  200. }
  201. throw new Error('Bindings not found.');
  202. }
  203. transform(src, options) {
  204. var _a, _b, _c;
  205. return __awaiter(this, void 0, void 0, function* () {
  206. const isModule = typeof src !== "string";
  207. options = options || {};
  208. if ((_a = options === null || options === void 0 ? void 0 : options.jsc) === null || _a === void 0 ? void 0 : _a.parser) {
  209. options.jsc.parser.syntax = (_b = options.jsc.parser.syntax) !== null && _b !== void 0 ? _b : 'ecmascript';
  210. }
  211. const { plugin } = options, newOptions = __rest(options, ["plugin"]);
  212. if (bindings) {
  213. if (plugin) {
  214. const m = typeof src === "string"
  215. ? yield this.parse(src, (_c = options === null || options === void 0 ? void 0 : options.jsc) === null || _c === void 0 ? void 0 : _c.parser, options.filename)
  216. : src;
  217. return this.transform(plugin(m), newOptions);
  218. }
  219. return bindings.transform(isModule ? JSON.stringify(src) : src, isModule, toBuffer(newOptions));
  220. }
  221. else if (fallbackBindings) {
  222. if (plugin && !this.fallbackBindingsPluginWarningDisplayed) {
  223. console.warn(`Fallback bindings does not support legacy plugins, it'll be ignored.`);
  224. this.fallbackBindingsPluginWarningDisplayed = true;
  225. }
  226. return fallbackBindings.transform(src, options);
  227. }
  228. throw new Error('Bindings not found.');
  229. });
  230. }
  231. transformSync(src, options) {
  232. var _a, _b, _c;
  233. const isModule = typeof src !== "string";
  234. options = options || {};
  235. if ((_a = options === null || options === void 0 ? void 0 : options.jsc) === null || _a === void 0 ? void 0 : _a.parser) {
  236. options.jsc.parser.syntax = (_b = options.jsc.parser.syntax) !== null && _b !== void 0 ? _b : 'ecmascript';
  237. }
  238. const { plugin } = options, newOptions = __rest(options, ["plugin"]);
  239. if (bindings) {
  240. if (plugin) {
  241. const m = typeof src === "string" ? this.parseSync(src, (_c = options === null || options === void 0 ? void 0 : options.jsc) === null || _c === void 0 ? void 0 : _c.parser, options.filename) : src;
  242. return this.transformSync(plugin(m), newOptions);
  243. }
  244. return bindings.transformSync(isModule ? JSON.stringify(src) : src, isModule, toBuffer(newOptions));
  245. }
  246. else if (fallbackBindings) {
  247. if (plugin && !this.fallbackBindingsPluginWarningDisplayed) {
  248. console.warn(`Fallback bindings does not support legacy plugins, it'll be ignored.`);
  249. this.fallbackBindingsPluginWarningDisplayed = true;
  250. }
  251. return fallbackBindings.transformSync(isModule ? JSON.stringify(src) : src, options);
  252. }
  253. throw new Error("Bindings not found");
  254. }
  255. transformFile(path, options) {
  256. var _a, _b, _c;
  257. return __awaiter(this, void 0, void 0, function* () {
  258. if (!bindings && !!fallbackBindings) {
  259. throw new Error('Fallback bindings does not support filesystem access.');
  260. }
  261. else if (!bindings) {
  262. throw new Error('Bindings not found.');
  263. }
  264. options = options || {};
  265. if ((_a = options === null || options === void 0 ? void 0 : options.jsc) === null || _a === void 0 ? void 0 : _a.parser) {
  266. options.jsc.parser.syntax = (_b = options.jsc.parser.syntax) !== null && _b !== void 0 ? _b : 'ecmascript';
  267. }
  268. const { plugin } = options, newOptions = __rest(options, ["plugin"]);
  269. newOptions.filename = path;
  270. if (plugin) {
  271. const m = yield this.parseFile(path, (_c = options === null || options === void 0 ? void 0 : options.jsc) === null || _c === void 0 ? void 0 : _c.parser);
  272. return this.transform(plugin(m), newOptions);
  273. }
  274. return bindings.transformFile(path, false, toBuffer(newOptions));
  275. });
  276. }
  277. transformFileSync(path, options) {
  278. var _a, _b, _c;
  279. if (!bindings && !!fallbackBindings) {
  280. throw new Error('Fallback bindings does not support filesystem access.');
  281. }
  282. else if (!bindings) {
  283. throw new Error('Bindings not found.');
  284. }
  285. options = options || {};
  286. if ((_a = options === null || options === void 0 ? void 0 : options.jsc) === null || _a === void 0 ? void 0 : _a.parser) {
  287. options.jsc.parser.syntax = (_b = options.jsc.parser.syntax) !== null && _b !== void 0 ? _b : 'ecmascript';
  288. }
  289. const { plugin } = options, newOptions = __rest(options, ["plugin"]);
  290. newOptions.filename = path;
  291. if (plugin) {
  292. const m = this.parseFileSync(path, (_c = options === null || options === void 0 ? void 0 : options.jsc) === null || _c === void 0 ? void 0 : _c.parser);
  293. return this.transformSync(plugin(m), newOptions);
  294. }
  295. return bindings.transformFileSync(path, /* isModule */ false, toBuffer(newOptions));
  296. }
  297. bundle(options) {
  298. return __awaiter(this, void 0, void 0, function* () {
  299. if (!bindings && !!fallbackBindings) {
  300. throw new Error('Fallback bindings does not support this interface yet.');
  301. }
  302. else if (!bindings) {
  303. throw new Error('Bindings not found.');
  304. }
  305. const opts = yield (0, spack_1.compileBundleOptions)(options);
  306. if (Array.isArray(opts)) {
  307. const all = yield Promise.all(opts.map((opt) => __awaiter(this, void 0, void 0, function* () {
  308. return this.bundle(opt);
  309. })));
  310. let obj = {};
  311. for (const o of all) {
  312. obj = Object.assign(Object.assign({}, obj), o);
  313. }
  314. return obj;
  315. }
  316. return bindings.bundle(toBuffer(Object.assign({}, opts)));
  317. });
  318. }
  319. }
  320. exports.Compiler = Compiler;
  321. const compiler = new Compiler();
  322. function parse(src, options) {
  323. return compiler.parse(src, options);
  324. }
  325. exports.parse = parse;
  326. function parseSync(src, options) {
  327. return compiler.parseSync(src, options);
  328. }
  329. exports.parseSync = parseSync;
  330. function parseFile(path, options) {
  331. return compiler.parseFile(path, options);
  332. }
  333. exports.parseFile = parseFile;
  334. function parseFileSync(path, options) {
  335. return compiler.parseFileSync(path, options);
  336. }
  337. exports.parseFileSync = parseFileSync;
  338. function print(m, options) {
  339. return compiler.print(m, options);
  340. }
  341. exports.print = print;
  342. function printSync(m, options) {
  343. return compiler.printSync(m, options);
  344. }
  345. exports.printSync = printSync;
  346. function transform(src, options) {
  347. return compiler.transform(src, options);
  348. }
  349. exports.transform = transform;
  350. function transformSync(src, options) {
  351. return compiler.transformSync(src, options);
  352. }
  353. exports.transformSync = transformSync;
  354. function transformFile(path, options) {
  355. return compiler.transformFile(path, options);
  356. }
  357. exports.transformFile = transformFile;
  358. function transformFileSync(path, options) {
  359. return compiler.transformFileSync(path, options);
  360. }
  361. exports.transformFileSync = transformFileSync;
  362. function bundle(options) {
  363. return compiler.bundle(options);
  364. }
  365. exports.bundle = bundle;
  366. function minify(src, opts) {
  367. return __awaiter(this, void 0, void 0, function* () {
  368. return compiler.minify(src, opts);
  369. });
  370. }
  371. exports.minify = minify;
  372. function minifySync(src, opts) {
  373. return compiler.minifySync(src, opts);
  374. }
  375. exports.minifySync = minifySync;
  376. /**
  377. * Configure custom trace configuration runs for a process lifecycle.
  378. * Currently only chromium's trace event format is supported.
  379. * (https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview)
  380. *
  381. * This should be called before calling any binding interfaces exported in `@swc/core`, such as
  382. * `transform*`, or `parse*` or anything. To avoid breaking changes, each binding fn internally
  383. * sets default trace subscriber if not set.
  384. *
  385. * Unlike other configuration, this does not belong to individual api surface using swcrc
  386. * or api's parameters (`transform(..., {trace})`). This is due to current tracing subscriber
  387. * can be configured only once for the global scope. Calling `registerGlobalTraceConfig` multiple
  388. * time won't cause error, subsequent calls will be ignored.
  389. *
  390. * As name implies currently this is experimental interface may change over time without semver
  391. * major breaking changes. Please provide feedbacks,
  392. * or bug report at https://github.com/swc-project/swc/discussions.
  393. */
  394. function __experimental_registerGlobalTraceConfig(traceConfig) {
  395. // Do not raise error if binding doesn't exists - fallback binding will not support
  396. // this ever.
  397. if (bindings) {
  398. if (traceConfig.type === 'traceEvent') {
  399. bindings.initCustomTraceSubscriber(traceConfig.fileName);
  400. }
  401. }
  402. }
  403. exports.__experimental_registerGlobalTraceConfig = __experimental_registerGlobalTraceConfig;
  404. /**
  405. * @ignore
  406. *
  407. * Returns current binary's metadata to determine which binary is actually loaded.
  408. *
  409. * This is undocumented interface, does not guarantee stability across `@swc/core`'s semver
  410. * as internal representation may change anytime. Use it with caution.
  411. */
  412. function getBinaryMetadata() {
  413. return {
  414. target: bindings ? bindings === null || bindings === void 0 ? void 0 : bindings.getTargetTriple() : undefined
  415. };
  416. }
  417. exports.getBinaryMetadata = getBinaryMetadata;
  418. exports.DEFAULT_EXTENSIONS = Object.freeze([
  419. ".js",
  420. ".jsx",
  421. ".es6",
  422. ".es",
  423. ".mjs",
  424. ".ts",
  425. ".tsx",
  426. ".cts",
  427. ".mts"
  428. ]);
  429. function toBuffer(t) {
  430. return Buffer.from(JSON.stringify(t));
  431. }