UNPKG

8.81 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3require("@jsii/check-node/run");
4const path = require("node:path");
5const util = require("node:util");
6const log4js = require("log4js");
7const package_json_1 = require("typescript/package.json");
8const yargs = require("yargs");
9const compiler_1 = require("./compiler");
10const jsii_diagnostic_1 = require("./jsii-diagnostic");
11const project_info_1 = require("./project-info");
12const support_1 = require("./support");
13const tsconfig_1 = require("./tsconfig");
14const utils = require("./utils");
15const version_1 = require("./version");
16const warnings_1 = require("./warnings");
17const warningTypes = Object.keys(warnings_1.enabledWarnings);
18function choiceWithDesc(choices, desc) {
19 return {
20 choices: Object.keys(choices),
21 desc: [desc, ...Object.entries(choices).map(([choice, docs]) => `${choice}: ${docs}`)].join('\n'),
22 };
23}
24var OPTION_GROUP;
25(function (OPTION_GROUP) {
26 OPTION_GROUP["JSII"] = "jsii compiler options:";
27 OPTION_GROUP["TS"] = "TypeScript config options:";
28})(OPTION_GROUP || (OPTION_GROUP = {}));
29const ruleSets = {
30 [tsconfig_1.TypeScriptConfigValidationRuleSet.STRICT]: 'Validates the provided config against a strict rule set designed for maximum backwards-compatibility.',
31 [tsconfig_1.TypeScriptConfigValidationRuleSet.GENERATED]: 'Enforces a config as created by --generate-tsconfig. Use this to stay compatible with the generated config, but have full ownership over the file.',
32 [tsconfig_1.TypeScriptConfigValidationRuleSet.MINIMAL]: 'Only enforce options that are known to be incompatible with jsii. This rule set is likely to be incomplete and new rules will be added without notice as incompatibilities emerge.',
33 [tsconfig_1.TypeScriptConfigValidationRuleSet.NONE]: 'Disables all config validation, including options that are known to be incompatible with jsii. Intended for experimentation only. Use at your own risk.',
34};
35(async () => {
36 await (0, support_1.emitSupportPolicyInformation)();
37 await yargs
38 .env('JSII')
39 .command(['$0 [PROJECT_ROOT]', 'compile [PROJECT_ROOT]'], 'Compiles a jsii/TypeScript project', (argv) => argv
40 .positional('PROJECT_ROOT', {
41 type: 'string',
42 desc: 'The root of the project to be compiled',
43 default: '.',
44 normalize: true,
45 })
46 .option('watch', {
47 alias: 'w',
48 type: 'boolean',
49 desc: 'Watch for file changes and recompile automatically',
50 })
51 .option('project-references', {
52 group: OPTION_GROUP.JSII,
53 alias: 'r',
54 type: 'boolean',
55 desc: 'Generate TypeScript project references (also [package.json].jsii.projectReferences)\nHas no effect if --tsconfig is provided',
56 })
57 .option('fix-peer-dependencies', {
58 type: 'boolean',
59 default: true,
60 desc: 'This option no longer has any effect.',
61 hidden: true,
62 })
63 .options('fail-on-warnings', {
64 group: OPTION_GROUP.JSII,
65 alias: 'Werr',
66 type: 'boolean',
67 desc: 'Treat warnings as errors',
68 })
69 .option('silence-warnings', {
70 group: OPTION_GROUP.JSII,
71 type: 'array',
72 default: [],
73 desc: `List of warnings to silence (warnings: ${warningTypes.join(',')})`,
74 })
75 .option('strip-deprecated', {
76 group: OPTION_GROUP.JSII,
77 type: 'string',
78 desc: '[EXPERIMENTAL] Hides all @deprecated members from the API (implementations remain). If an optional file name is given, only FQNs present in the file will be stripped.',
79 })
80 .option('add-deprecation-warnings', {
81 group: OPTION_GROUP.JSII,
82 type: 'boolean',
83 default: false,
84 desc: '[EXPERIMENTAL] Injects warning statements for all deprecated elements, to be printed at runtime',
85 })
86 .option('generate-tsconfig', {
87 group: OPTION_GROUP.TS,
88 type: 'string',
89 defaultDescription: 'tsconfig.json',
90 desc: 'Name of the typescript configuration file to generate with compiler settings',
91 })
92 .option('tsconfig', {
93 group: OPTION_GROUP.TS,
94 alias: 'c',
95 type: 'string',
96 desc: '[EXPERIMENTAL] Use this typescript configuration file to compile the jsii project.',
97 })
98 .conflicts('tsconfig', ['generate-tsconfig', 'project-references'])
99 .option('validate-tsconfig', {
100 group: OPTION_GROUP.TS,
101 ...choiceWithDesc(ruleSets, '[EXPERIMENTAL] Validate the provided typescript configuration file against a set of rules.'),
102 defaultDescription: tsconfig_1.TypeScriptConfigValidationRuleSet.STRICT,
103 })
104 .option('compress-assembly', {
105 group: OPTION_GROUP.JSII,
106 type: 'boolean',
107 default: false,
108 desc: 'Emit a compressed version of the assembly',
109 })
110 .option('verbose', {
111 alias: 'v',
112 type: 'count',
113 desc: 'Increase the verbosity of output',
114 global: true,
115 }), async (argv) => {
116 _configureLog4js(argv.verbose);
117 if (argv['generate-tsconfig'] != null && argv.tsconfig != null) {
118 throw new Error('Options --generate-tsconfig and --tsconfig are mutually exclusive');
119 }
120 const projectRoot = path.normalize(path.resolve(process.cwd(), argv.PROJECT_ROOT));
121 const { projectInfo, diagnostics: projectInfoDiagnostics } = (0, project_info_1.loadProjectInfo)(projectRoot);
122 // disable all silenced warnings
123 for (const key of argv['silence-warnings']) {
124 if (!(key in warnings_1.enabledWarnings)) {
125 throw new Error(`Unknown warning type ${key}. Must be one of: ${warningTypes.join(', ')}`);
126 }
127 warnings_1.enabledWarnings[key] = false;
128 }
129 (0, jsii_diagnostic_1.configureCategories)(projectInfo.diagnostics ?? {});
130 const typeScriptConfig = argv.tsconfig ?? projectInfo.packageJson.jsii?.tsconfig;
131 const validateTypeScriptConfig = argv['validate-tsconfig'] ??
132 projectInfo.packageJson.jsii?.validateTsconfig ??
133 tsconfig_1.TypeScriptConfigValidationRuleSet.STRICT;
134 const compiler = new compiler_1.Compiler({
135 projectInfo,
136 projectReferences: argv['project-references'],
137 failOnWarnings: argv['fail-on-warnings'],
138 stripDeprecated: argv['strip-deprecated'] != null,
139 stripDeprecatedAllowListFile: argv['strip-deprecated'],
140 addDeprecationWarnings: argv['add-deprecation-warnings'],
141 generateTypeScriptConfig: argv['generate-tsconfig'],
142 typeScriptConfig,
143 validateTypeScriptConfig,
144 compressAssembly: argv['compress-assembly'],
145 });
146 const emitResult = argv.watch ? await compiler.watch() : compiler.emit();
147 const allDiagnostics = [...projectInfoDiagnostics, ...emitResult.diagnostics];
148 for (const diagnostic of allDiagnostics) {
149 utils.logDiagnostic(diagnostic, projectRoot);
150 }
151 if (emitResult.emitSkipped) {
152 process.exitCode = 1;
153 }
154 })
155 .help()
156 .version(`${version_1.VERSION}, typescript ${package_json_1.version}`)
157 .parse();
158})().catch((e) => {
159 console.error(`Error: ${e.stack}`);
160 process.exitCode = -1;
161});
162function _configureLog4js(verbosity) {
163 const stderrColor = !!process.stderr.isTTY;
164 const stdoutColor = !!process.stdout.isTTY;
165 log4js.addLayout('passThroughNoColor', () => {
166 return (loggingEvent) => utils.stripAnsi(util.format(...loggingEvent.data));
167 });
168 log4js.configure({
169 appenders: {
170 console: {
171 type: 'stderr',
172 layout: { type: stderrColor ? 'colored' : 'basic' },
173 },
174 [utils.DIAGNOSTICS]: {
175 type: 'stdout',
176 layout: {
177 type: stdoutColor ? 'messagePassThrough' : 'passThroughNoColor',
178 },
179 },
180 },
181 categories: {
182 default: { appenders: ['console'], level: _logLevel() },
183 // The diagnostics logger must be set to INFO or more verbose, or watch won't show important messages
184 [utils.DIAGNOSTICS]: {
185 appenders: ['diagnostics'],
186 level: _logLevel(Math.max(verbosity, 1)),
187 },
188 },
189 });
190 function _logLevel(verbosityLevel = verbosity) {
191 switch (verbosityLevel) {
192 case 0:
193 return 'WARN';
194 case 1:
195 return 'INFO';
196 case 2:
197 return 'DEBUG';
198 case 3:
199 return 'TRACE';
200 default:
201 return 'ALL';
202 }
203 }
204}
205//# sourceMappingURL=main.js.map
\No newline at end of file