source: frontend/node_modules/sucrase/dist/cli.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 10.2 KB
RevLine 
[9af201e]1"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }/* eslint-disable no-console */
2var _commander = require('commander'); var _commander2 = _interopRequireDefault(_commander);
3var _tinyglobby = require('tinyglobby');
4var _fs = require('mz/fs');
5var _path = require('path');
6
7var _index = require('./index');
8
9
10
11
12
13
14
15
16
17
18
19 function run() {
20 _commander2.default
21 .description(`Sucrase: super-fast Babel alternative.`)
22 .usage("[options] <srcDir>")
23 .option(
24 "-d, --out-dir <out>",
25 "Compile an input directory of modules into an output directory.",
26 )
27 .option(
28 "-p, --project <dir>",
29 "Compile a TypeScript project, will read from tsconfig.json in <dir>",
30 )
31 .option("--out-extension <extension>", "File extension to use for all output files.", "js")
32 .option("--exclude-dirs <paths>", "Names of directories that should not be traversed.")
33 .option("-q, --quiet", "Don't print the names of converted files.")
34 .option("-t, --transforms <transforms>", "Comma-separated list of transforms to run.")
35 .option("--disable-es-transforms", "Opt out of all ES syntax transforms.")
36 .option("--jsx-runtime <string>", "Transformation mode for the JSX transform.")
37 .option("--production", "Disable debugging information from JSX in output.")
38 .option(
39 "--jsx-import-source <string>",
40 "Automatic JSX transform import path prefix, defaults to `React.Fragment`.",
41 )
42 .option(
43 "--jsx-pragma <string>",
44 "Classic JSX transform element creation function, defaults to `React.createElement`.",
45 )
46 .option(
47 "--jsx-fragment-pragma <string>",
48 "Classic JSX transform fragment component, defaults to `React.Fragment`.",
49 )
50 .option("--keep-unused-imports", "Disable automatic removal of type-only imports/exports.")
51 .option("--preserve-dynamic-import", "Don't transpile dynamic import() to require.")
52 .option(
53 "--inject-create-require-for-import-require",
54 "Use `createRequire` when transpiling TS `import = require` to ESM.",
55 )
56 .option(
57 "--enable-legacy-typescript-module-interop",
58 "Use default TypeScript ESM/CJS interop strategy.",
59 )
60 .option("--enable-legacy-babel5-module-interop", "Use Babel 5 ESM/CJS interop strategy.")
61 .parse(process.argv);
62
63 if (_commander2.default.project) {
64 if (
65 _commander2.default.outDir ||
66 _commander2.default.transforms ||
67 _commander2.default.args[0] ||
68 _commander2.default.enableLegacyTypescriptModuleInterop
69 ) {
70 console.error(
71 "If TypeScript project is specified, out directory, transforms, source " +
72 "directory, and --enable-legacy-typescript-module-interop may not be specified.",
73 );
74 process.exit(1);
75 }
76 } else {
77 if (!_commander2.default.outDir) {
78 console.error("Out directory is required");
79 process.exit(1);
80 }
81
82 if (!_commander2.default.transforms) {
83 console.error("Transforms option is required.");
84 process.exit(1);
85 }
86
87 if (!_commander2.default.args[0]) {
88 console.error("Source directory is required.");
89 process.exit(1);
90 }
91 }
92
93 const options = {
94 outDirPath: _commander2.default.outDir,
95 srcDirPath: _commander2.default.args[0],
96 project: _commander2.default.project,
97 outExtension: _commander2.default.outExtension,
98 excludeDirs: _commander2.default.excludeDirs ? _commander2.default.excludeDirs.split(",") : [],
99 quiet: _commander2.default.quiet,
100 sucraseOptions: {
101 transforms: _commander2.default.transforms ? _commander2.default.transforms.split(",") : [],
102 disableESTransforms: _commander2.default.disableEsTransforms,
103 jsxRuntime: _commander2.default.jsxRuntime,
104 production: _commander2.default.production,
105 jsxImportSource: _commander2.default.jsxImportSource,
106 jsxPragma: _commander2.default.jsxPragma || "React.createElement",
107 jsxFragmentPragma: _commander2.default.jsxFragmentPragma || "React.Fragment",
108 keepUnusedImports: _commander2.default.keepUnusedImports,
109 preserveDynamicImport: _commander2.default.preserveDynamicImport,
110 injectCreateRequireForImportRequire: _commander2.default.injectCreateRequireForImportRequire,
111 enableLegacyTypeScriptModuleInterop: _commander2.default.enableLegacyTypescriptModuleInterop,
112 enableLegacyBabel5ModuleInterop: _commander2.default.enableLegacyBabel5ModuleInterop,
113 },
114 };
115
116 buildDirectory(options).catch((e) => {
117 process.exitCode = 1;
118 console.error(e);
119 });
120} exports.default = run;
121
122
123
124
125
126
127async function findFiles(options) {
128 const outDirPath = options.outDirPath;
129 const srcDirPath = options.srcDirPath;
130
131 const extensions = options.sucraseOptions.transforms.includes("typescript")
132 ? [".ts", ".tsx"]
133 : [".js", ".jsx"];
134
135 if (!(await _fs.exists.call(void 0, outDirPath))) {
136 await _fs.mkdir.call(void 0, outDirPath);
137 }
138
139 const outArr = [];
140 for (const child of await _fs.readdir.call(void 0, srcDirPath)) {
141 if (["node_modules", ".git"].includes(child) || options.excludeDirs.includes(child)) {
142 continue;
143 }
144 const srcChildPath = _path.join.call(void 0, srcDirPath, child);
145 const outChildPath = _path.join.call(void 0, outDirPath, child);
146 if ((await _fs.stat.call(void 0, srcChildPath)).isDirectory()) {
147 const innerOptions = {...options};
148 innerOptions.srcDirPath = srcChildPath;
149 innerOptions.outDirPath = outChildPath;
150 const innerFiles = await findFiles(innerOptions);
151 outArr.push(...innerFiles);
152 } else if (extensions.some((ext) => srcChildPath.endsWith(ext))) {
153 const outPath = outChildPath.replace(/\.\w+$/, `.${options.outExtension}`);
154 outArr.push({
155 srcPath: srcChildPath,
156 outPath,
157 });
158 }
159 }
160
161 return outArr;
162}
163
164async function runGlob(options) {
165 const tsConfigPath = _path.join.call(void 0, options.project, "tsconfig.json");
166
167 let str;
168 try {
169 str = await _fs.readFile.call(void 0, tsConfigPath, "utf8");
170 } catch (err) {
171 console.error("Could not find project tsconfig.json");
172 console.error(` --project=${options.project}`);
173 console.error(err);
174 process.exit(1);
175 }
176 const json = JSON.parse(str);
177
178 const foundFiles = [];
179
180 const files = json.files;
181 const include = json.include;
182
183 const absProject = _path.join.call(void 0, process.cwd(), options.project);
184 const outDirs = [];
185
186 if (!(await _fs.exists.call(void 0, options.outDirPath))) {
187 await _fs.mkdir.call(void 0, options.outDirPath);
188 }
189
190 if (files) {
191 for (const file of files) {
192 if (file.endsWith(".d.ts")) {
193 continue;
194 }
195 if (!file.endsWith(".ts") && !file.endsWith(".js")) {
196 continue;
197 }
198
199 const srcFile = _path.join.call(void 0, absProject, file);
200 const outFile = _path.join.call(void 0, options.outDirPath, file);
201 const outPath = outFile.replace(/\.\w+$/, `.${options.outExtension}`);
202
203 const outDir = _path.dirname.call(void 0, outPath);
204 if (!outDirs.includes(outDir)) {
205 outDirs.push(outDir);
206 }
207
208 foundFiles.push({
209 srcPath: srcFile,
210 outPath,
211 });
212 }
213 }
214 if (include) {
215 for (const pattern of include) {
216 const globFiles = await _tinyglobby.glob.call(void 0, _path.join.call(void 0, absProject, pattern), {expandDirectories: false});
217 for (const file of globFiles) {
218 if (!file.endsWith(".ts") && !file.endsWith(".js")) {
219 continue;
220 }
221 if (file.endsWith(".d.ts")) {
222 continue;
223 }
224
225 const relativeFile = _path.relative.call(void 0, absProject, file);
226 const outFile = _path.join.call(void 0, options.outDirPath, relativeFile);
227 const outPath = outFile.replace(/\.\w+$/, `.${options.outExtension}`);
228
229 const outDir = _path.dirname.call(void 0, outPath);
230 if (!outDirs.includes(outDir)) {
231 outDirs.push(outDir);
232 }
233
234 foundFiles.push({
235 srcPath: file,
236 outPath,
237 });
238 }
239 }
240 }
241
242 for (const outDirPath of outDirs) {
243 if (!(await _fs.exists.call(void 0, outDirPath))) {
244 await _fs.mkdir.call(void 0, outDirPath);
245 }
246 }
247
248 // TODO: read exclude
249
250 return foundFiles;
251}
252
253async function updateOptionsFromProject(options) {
254 /**
255 * Read the project information and assign the following.
256 * - outDirPath
257 * - transform: imports
258 * - transform: typescript
259 * - enableLegacyTypescriptModuleInterop: true/false.
260 */
261
262 const tsConfigPath = _path.join.call(void 0, options.project, "tsconfig.json");
263
264 let str;
265 try {
266 str = await _fs.readFile.call(void 0, tsConfigPath, "utf8");
267 } catch (err) {
268 console.error("Could not find project tsconfig.json");
269 console.error(` --project=${options.project}`);
270 console.error(err);
271 process.exit(1);
272 }
273 const json = JSON.parse(str);
274 const sucraseOpts = options.sucraseOptions;
275 if (!sucraseOpts.transforms.includes("typescript")) {
276 sucraseOpts.transforms.push("typescript");
277 }
278
279 const compilerOpts = json.compilerOptions;
280 if (compilerOpts.outDir) {
281 options.outDirPath = _path.join.call(void 0, process.cwd(), options.project, compilerOpts.outDir);
282 }
283 if (compilerOpts.esModuleInterop !== true) {
284 sucraseOpts.enableLegacyTypeScriptModuleInterop = true;
285 }
286 if (compilerOpts.module === "commonjs") {
287 if (!sucraseOpts.transforms.includes("imports")) {
288 sucraseOpts.transforms.push("imports");
289 }
290 }
291}
292
293async function buildDirectory(options) {
294 let files;
295 if (options.outDirPath && options.srcDirPath) {
296 files = await findFiles(options);
297 } else if (options.project) {
298 await updateOptionsFromProject(options);
299 files = await runGlob(options);
300 } else {
301 console.error("Project or Source directory required.");
302 process.exit(1);
303 }
304
305 for (const file of files) {
306 await buildFile(file.srcPath, file.outPath, options);
307 }
308}
309
310async function buildFile(srcPath, outPath, options) {
311 if (!options.quiet) {
312 console.log(`${srcPath} -> ${outPath}`);
313 }
314 const code = (await _fs.readFile.call(void 0, srcPath)).toString();
315 const transformedCode = _index.transform.call(void 0, code, {...options.sucraseOptions, filePath: srcPath}).code;
316 await _fs.writeFile.call(void 0, outPath, transformedCode);
317}
Note: See TracBrowser for help on using the repository browser.