aboutsummaryrefslogtreecommitdiffstats
path: root/share/qbs/modules/typescript/TypeScriptModule.qbs
blob: c8ca270e062eda2f985f925dddcb00480c43f9d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qbs.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

import qbs.File
import qbs.FileInfo
import qbs.Host
import qbs.ModUtils
import qbs.Probes
import qbs.Process
import "typescript.js" as TypeScript

Module {
    // Qbs does NOT support standalone TypeScript installations
    // (for example, %PROGRAMFILES%\Microsoft SDKs\TypeScript and some Debian and RPM packages),
    // because they do not include typescript.d.ts, which is necessary for building internal tools.
    // Only npm-based installations of TypeScript are supported (this is also the most common).
    Depends { name: "nodejs" }

    additionalProductTypes: ["compiled_typescript"]

    Probes.TypeScriptProbe {
        id: tsc
        interpreterPath: FileInfo.path(nodejs.interpreterFilePath)
        packageManagerBinPath: nodejs.packageManagerBinPath
        packageManagerRootPath: nodejs.packageManagerRootPath
    }

    property path toolchainInstallPath: tsc.path

    property path toolchainLibDirName: (versionMajor > 1 || (versionMajor === 1 && versionMinor >= 6)) ? "lib" : "bin"
    property path toolchainLibInstallPath: FileInfo.joinPaths(nodejs.packageManagerRootPath, "typescript", toolchainLibDirName)

    version: tsc.version ? tsc.version[2] : undefined
    property var versionParts: version ? version.split('.').map(function(item) { return parseInt(item, 10); }) : []
    property int versionMajor: versionParts[0]
    property int versionMinor: versionParts[1]
    property int versionPatch: versionParts[2]
    property int versionBuild: versionParts[3]
    property string versionSuffix: tsc.version ? tsc.version[3] : undefined

    property string compilerName: tsc.fileName
    property string compilerPath: tsc.filePath

    property string warningLevel: "normal"
    PropertyOptions {
        name: "warningLevel"
        description: "pedantic to warn on expressions and declarations with an implied 'any' type"
        allowedValues: ["normal", "pedantic"]
    }

    property string targetVersion
    PropertyOptions {
        name: "targetVersion"
        description: "ECMAScript target version"
        allowedValues: ["ES3", "ES5", "ES2015"]
    }

    property string moduleLoader
    PropertyOptions {
        name: "moduleLoader"
        allowedValues: ["commonjs", "amd"]
    }

    property bool stripComments: !qbs.debugInformation
    PropertyOptions {
        name: "stripComments"
        description: "whether to remove comments from the generated output"
    }

    property bool generateDeclarations: false
    PropertyOptions {
        name: "generateDeclarations"
        description: "whether to generate corresponding .d.ts files during compilation"
    }

    // In release mode, nodejs can/should default-enable minification and obfuscation,
    // making the source maps useless, so these default settings work out fine
    property bool generateSourceMaps: qbs.debugInformation
    PropertyOptions {
        name: "generateSourceMaps"
        description: "whether to generate corresponding .map files during compilation"
    }

    property stringList compilerFlags
    PropertyOptions {
        name: "compilerFlags"
        description: "additional flags for the TypeScript compiler"
    }

    property bool singleFile: false
    PropertyOptions {
        name: "singleFile"
        description: "whether to compile all source files to a single output file"
    }

    validate: {
        var interpreterMessage = "TypeScript requires the Node.js interpreter to be called 'node'.";
        if (File.exists("/etc/debian_version")) {
            interpreterMessage += " Did you forget to install the nodejs-legacy package? " +
                "See https://lists.debian.org/debian-devel-announce/2012/07/msg00002.html " +
                "for more information.";
        }

        var preValidator = new ModUtils.PropertyValidator("nodejs");
        preValidator.addCustomValidator("interpreterFileName", nodejs.interpreterFileName, function (value) {
            return value === "node" + (Host.os().contains("windows") ? ".exe" : "");
        }, interpreterMessage);
        preValidator.addCustomValidator("interpreterFilePath", nodejs.interpreterFilePath, function (value) {
            return value.endsWith(nodejs.interpreterFileName);
        }, interpreterMessage);
        preValidator.validate();

        var validator = new ModUtils.PropertyValidator("typescript");
        validator.setRequiredProperty("toolchainInstallPath", toolchainInstallPath);
        validator.setRequiredProperty("compilerName", compilerName);
        validator.setRequiredProperty("compilerPath", compilerPath);
        validator.setRequiredProperty("version", version);
        validator.setRequiredProperty("versionParts", versionParts);
        validator.setRequiredProperty("versionMajor", versionMajor);
        validator.setRequiredProperty("versionMinor", versionMinor);
        validator.setRequiredProperty("versionPatch", versionPatch);
        validator.addVersionValidator("version", version, 3, 4);
        validator.addRangeValidator("versionMajor", versionMajor, 1);
        validator.addRangeValidator("versionMinor", versionMinor, 0);
        validator.addRangeValidator("versionPatch", versionPatch, 0);

        if (versionParts && versionParts.length >= 4) {
            validator.setRequiredProperty("versionBuild", versionBuild);
            validator.addRangeValidator("versionBuild", versionBuild, 0);
        }

        validator.validate();
    }

    // TypeScript declaration files
    FileTagger {
        patterns: ["*.d.ts"]
        fileTags: ["typescript_declaration"]
    }

    // TypeScript source files
    FileTagger {
        patterns: ["*.ts"]
        fileTags: ["typescript"]
    }

    Group {
        name: "io.qt.qbs.internal.typescript-helper"
        files: [
            FileInfo.joinPaths(path, "qbs-tsc-scan", "qbs-tsc-scan.ts"),
            FileInfo.joinPaths(typescript.toolchainLibInstallPath, "typescript.d.ts"),
            FileInfo.joinPaths(typescript.toolchainLibInstallPath, "..", "package.json")
        ]
        fileTags: ["typescript.typescript-internal"]
    }

    Rule {
        multiplex: true
        inputs: ["typescript.typescript-internal"]

        outputFileTags: ["typescript.compiled_typescript-internal"]
        outputArtifacts: {
            if (!TypeScript.supportsModernFeatures(product))
                return [];
            return [{
                filePath: FileInfo.joinPaths(product.buildDirectory,
                                             ".io.qt.qbs.internal.typescript", "qbs-tsc-scan.ts"),
                fileTags: ["typescript.typescript-internal.copy"]
            },
            {
                filePath: FileInfo.joinPaths(product.buildDirectory,
                                             ".io.qt.qbs.internal.typescript",
                                             "node_modules", "typescript", "lib", "typescript.d.ts"),
                fileTags: ["typescript.typescript-internal.copy"]
            },
            {
                filePath: FileInfo.joinPaths(product.buildDirectory,
                                             ".io.qt.qbs.internal.typescript",
                                             "node_modules", "typescript", "package.json"),
                fileTags: ["typescript.typescript-internal.copy"]
            },
            {
                filePath: FileInfo.joinPaths(product.buildDirectory,
                                             ".io.qt.qbs.internal.typescript", "qbs-tsc-scan.js"),
                fileTags: ["typescript.compiled_typescript-internal"]
            }];
        }

        prepare: {
            var inputPaths = inputs["typescript.typescript-internal"].map(function (input) {
                return input.filePath;
            });

            var outputPaths = outputs["typescript.typescript-internal.copy"].map(function (output) {
                return output.filePath;
            });

            var sortFunc = function (a, b) {
                return FileInfo.fileName(a).localeCompare(FileInfo.fileName(b));
            };

            var jcmd = new JavaScriptCommand();
            jcmd.ignoreDryRun = true;
            jcmd.silent = true;
            jcmd.inputPaths = inputPaths.sort(sortFunc);
            jcmd.outputPaths = outputPaths.sort(sortFunc);
            jcmd.sourceCode = function() {
                for (var i = 0; i < inputPaths.length; ++i)
                    File.copy(inputPaths[i], outputPaths[i]);
            };

            var outDir = FileInfo.path(
                        outputs["typescript.compiled_typescript-internal"][0].filePath);
            var args = ["--module", "commonjs",
                        "--outDir", outDir].concat(outputPaths.filter(function (f) { return !f.endsWith(".json"); }));
            var cmd = new Command(ModUtils.moduleProperty(product, "compilerPath"), args);
            cmd.ignoreDryRun = true;
            cmd.silent = true;
            return [jcmd, cmd];
        }
    }

    Rule {
        id: typescriptCompiler
        multiplex: true
        inputs: ["typescript"]
        inputsFromDependencies: ["typescript_declaration"]
        explicitlyDependsOn: ["typescript.compiled_typescript-internal"]

        outputArtifacts: TypeScript.outputArtifacts(product, inputs)

        outputFileTags: ["application_js", "compiled_typescript", "js", "source_map", "typescript_declaration"]

        prepare: {
            var cmd, cmds = [];

            cmd = new Command(ModUtils.moduleProperty(product, "compilerPath"),
                              TypeScript.tscArguments(product, inputs));
            cmd.description = "compiling " + (ModUtils.moduleProperty(product, "singleFile")
                                                ? outputs.compiled_typescript[0].fileName
                                                : inputs.typescript.map(function(obj) {
                                                                return obj.fileName; }).join(", "));
            cmd.highlight = "compiler";
            cmds.push(cmd);

            // QBS-5
            // Move the compiled JavaScript files compiled by TypeScript to an intermediate
            // directory so that the nodejs module can perform any necessary postprocessing
            // on the result. The nodejs module will move the files back to their original
            // locations after postprocessing.
            cmd = new JavaScriptCommand();
            cmd.silent = true;
            cmd.outDir = product.buildDirectory;
            cmd.sourceCode = function() {
                for (var i = 0; i < outputs.compiled_typescript.length; ++i) {
                    var output = outputs.compiled_typescript[i];
                    var intermediatePath = FileInfo.path(FileInfo.relativePath(product.moduleProperty("nodejs", "compiledIntermediateDir"), output.filePath));
                    var originalFilePath = FileInfo.joinPaths(outDir, intermediatePath, output.fileName);
                    File.copy(originalFilePath, output.filePath);
                    File.remove(originalFilePath);
                }
            };
            cmds.push(cmd);

            return cmds;
        }
    }
}