UNPKG

7.16 kBJavaScriptView Raw
1"use strict";
2/**
3 * @license
4 * Copyright (c) 2017 The Polymer Project Authors. All rights reserved. This
5 * code may only be used under the BSD style license found at
6 * http://polymer.github.io/LICENSE.txt The complete set of authors may be
7 * found at http://polymer.github.io/AUTHORS.txt The complete set of
8 * contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code
9 * distributed by Google as part of the polymer project is also subject to an
10 * additional IP rights grant found at http://polymer.github.io/PATENTS.txt
11 */
12var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
13 return new (P || (P = Promise))(function (resolve, reject) {
14 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
15 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
16 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
17 step((generator = generator.apply(thisArg, _arguments || [])).next());
18 });
19};
20Object.defineProperty(exports, "__esModule", { value: true });
21require("source-map-support/register");
22const fsExtra = require("fs-extra");
23const glob = require("glob");
24const path = require("path");
25const gen_ts_1 = require("./gen-ts");
26const verify_1 = require("./verify");
27const commandLineArgs = require("command-line-args");
28const commandLineUsage = require("command-line-usage");
29const argDefs = [
30 {
31 name: 'help',
32 type: Boolean,
33 description: 'Print this help text.',
34 },
35 {
36 name: 'version',
37 type: Boolean,
38 description: 'Print the installed version.',
39 },
40 {
41 name: 'root',
42 type: String,
43 defaultValue: '.',
44 description: 'Root directory of the package to analyze (default ".").',
45 },
46 {
47 name: 'config',
48 type: String,
49 description: 'JSON configuration file (default "<root>/gen-tsd.json" if exists).',
50 },
51 {
52 name: 'outDir',
53 type: String,
54 description: 'Type declarations output directory (required).',
55 },
56 {
57 name: 'deleteExisting',
58 type: Boolean,
59 description: 'Recursively delete all .d.ts files in <outDir> before ' +
60 'writing new typings, excluding node_modules/, bower_components/, ' +
61 'or any file added using the <addReferences> or <autoImport> config ' +
62 'options.',
63 },
64 {
65 name: 'verify',
66 type: Boolean,
67 description: 'Compile the generated types with TypeScript 3.0 and fail ' +
68 'if they are invalid.',
69 },
70 {
71 name: 'googModules',
72 type: Boolean,
73 description: 'If true, outputs declarations in \'goog:\' modules instead' +
74 ' of using simple ES modules. This is a temporary hack to account for' +
75 ' how modules are resolved for TypeScript inside google3. This' +
76 ' is probably not at all useful for anyone but the Polymer team.'
77 }
78];
79function run(argv) {
80 return __awaiter(this, void 0, void 0, function* () {
81 const args = commandLineArgs(argDefs, { argv });
82 if (args.help) {
83 console.log(commandLineUsage([
84 {
85 header: `gen-typescript-declarations`,
86 content: 'https://github.com/Polymer/tools/tree/master/packages/' +
87 'gen-typescript-declarations',
88 },
89 {
90 header: `Options`,
91 optionList: argDefs,
92 }
93 ]));
94 return;
95 }
96 if (args.version) {
97 console.log(require('../package.json').version);
98 return;
99 }
100 if (!args.outDir) {
101 throw new Error('--outDir is required');
102 }
103 const outDir = path.resolve(args.outDir);
104 if (!args.config) {
105 const p = path.join(args.root, 'gen-tsd.json');
106 if (yield fsExtra.pathExists(p)) {
107 args.config = p;
108 }
109 }
110 let config = {};
111 if (args.config) {
112 console.info(`Loading config from "${args.config}".`);
113 config = JSON.parse(yield fsExtra.readFile(args.config, 'utf8'));
114 }
115 if (args.googModules) {
116 config.googModules = true;
117 }
118 const fileMap = yield gen_ts_1.generateDeclarations(args.root, config);
119 if (args.deleteExisting) {
120 let dtsFiles = glob.sync('**/*.d.ts', {
121 cwd: outDir,
122 absolute: true,
123 nodir: true,
124 ignore: [
125 'node_modules/**',
126 'bower_components/**',
127 ]
128 });
129 // If the addReferences or autoImport options are used, it's probably to add
130 // some manually written typings. Since manually written typing files won't
131 // get re-generated, we shouldn't delete them.
132 const dontDelete = new Set();
133 for (const dtsFilePaths of Object.values(config.addReferences || {})) {
134 for (const dtsFilePath of dtsFilePaths) {
135 dontDelete.add(path.resolve(args.root, dtsFilePath));
136 }
137 }
138 for (const localModuleSpecifier of Object.keys(config.autoImport || {})) {
139 const dtsFilePath = localModuleSpecifier.replace(/\.js$/, '') + '.d.ts';
140 dontDelete.add(path.resolve(args.root, dtsFilePath));
141 }
142 dtsFiles = dtsFiles.filter((filepath) => !dontDelete.has(filepath));
143 console.log(`Deleting ${dtsFiles.length} existing d.ts files from ${outDir}`);
144 yield Promise.all(dtsFiles.map((filepath) => fsExtra.remove(filepath)));
145 }
146 console.log(`Writing type declarations to ${outDir}`);
147 yield writeFileMap(args.outDir, fileMap);
148 if (args.verify) {
149 console.log('Verifying type declarations');
150 const declarationFiles = [...fileMap.keys()].map((filePath) => path.join(outDir, filePath));
151 const result = verify_1.verifyTypings(declarationFiles);
152 if (result.success === true) {
153 console.log('Compilation successful');
154 }
155 else {
156 console.log('Compilation failed');
157 console.log(result.errorLog);
158 process.exit(1);
159 }
160 }
161 });
162}
163function writeFileMap(rootDir, files) {
164 return __awaiter(this, void 0, void 0, function* () {
165 const promises = [];
166 for (const [relPath, contents] of files) {
167 const fullPath = path.join(rootDir, relPath);
168 promises.push(fsExtra.outputFile(fullPath, contents));
169 }
170 yield Promise.all(promises);
171 });
172}
173(() => __awaiter(this, void 0, void 0, function* () {
174 try {
175 yield run(process.argv);
176 }
177 catch (e) {
178 console.error(e);
179 process.exit(1);
180 }
181}))();
182//# sourceMappingURL=cli.js.map
\No newline at end of file