├── .gitignore ├── .npmignore ├── .travis.yml ├── .vscode └── settings.json ├── CHANGELOG.md ├── Gruntfile.js ├── LICENSE ├── README.md ├── package.json ├── src ├── index.ts └── modules │ ├── compiler.ts │ ├── host.ts │ ├── option.ts │ ├── task.ts │ ├── util.ts │ └── watcher.ts ├── tasks ├── index.js └── modules │ ├── compiler.js │ ├── host.js │ ├── option.js │ ├── task.js │ ├── util.js │ └── watcher.js ├── test ├── errorTest.js ├── fixtures │ ├── amd.ts │ ├── async.ts │ ├── basepath.ts │ ├── comments.ts │ ├── commonjs.ts │ ├── crlf.ts │ ├── declaration.ts │ ├── decorator.ts │ ├── decorator2.ts │ ├── dest.ts │ ├── error-syntax.ts │ ├── error-typecheck.ts │ ├── es5.ts │ ├── es6.ts │ ├── jsxpreserve.jsx │ ├── jsxpreserve.tsx │ ├── jsxreact.tsx │ ├── lf.ts │ ├── noLib.ts │ ├── ref.ts │ ├── simple.ts │ ├── single │ │ ├── dir │ │ │ └── single2.ts │ │ └── single1.ts │ ├── sourcemap.ts │ ├── system.ts │ └── umd.ts ├── libs │ └── extlib.d.ts ├── test.js ├── watch │ ├── multi │ │ └── dest │ │ │ ├── target1 │ │ │ └── target1.ts │ │ │ ├── target2 │ │ │ └── target2.ts │ │ │ └── target3 │ │ │ └── target3.ts │ ├── simple │ │ └── dest │ │ │ ├── simple1.ts │ │ │ └── simple2.ts │ └── single │ │ └── dest │ │ ├── single1.ts │ │ └── single2.ts └── watchTest.js ├── tsconfig.json └── typings ├── bluebird.d.ts ├── grunt.d.ts ├── lib.support.d.ts ├── node.d.ts ├── react.d.ts └── typescript.d.ts /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | npm-debug.log 3 | test/temp 4 | test/expected 5 | test/fixtures/**/*.js 6 | test/fixtures/**/*.js.map 7 | test/fixtures/**/*.d.ts 8 | /.idea -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | npm-debug.log 3 | test 4 | typings 5 | /.idea 6 | src 7 | /.gitignore 8 | /egen.sh 9 | /tsd.json 10 | /.travis.yml 11 | /Gruntfile.js 12 | /.npmignore 13 | /lib 14 | /.vscode 15 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - 0.10 4 | 5 | before_install: 6 | - npm install -g grunt-cli 7 | - npm install 8 | - grunt setup 9 | - npm start 10 | 11 | notifications: 12 | email: false 13 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | // Place your settings in this file to overwrite default and user settings. 2 | { 3 | } -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | #Released 2 | 3 | ##0.8 4 | * Typescript 1.6.2 に対応 5 | * experimentalAsyncFunctions オプションに対応 6 | * jsx オプションに対応 7 | 8 | ##0.7 9 | * Typescript 1.5.3 に対応 10 | * module の system と umd に対応 11 | * emitDecoratorMetadata オプションに対応 12 | * experimentalDecorators オプションに対応 13 | * newLine オプションに対応 14 | * inlineSourceMap オプションに対応 15 | * inlineSources オプションに対応 16 | * noEmitHelpers オプションに対応 17 | 18 | ##0.6.2 19 | * コンパイルのコードファイルをtypescriptService.js から typescript.js に変更 20 | * Typescript 1.5-beta に対応 21 | * dest でディレクトリを指定した際のディレクトリ階層の保持方法をtscと同じ動きに変更 22 | * 以前のディレクトリ階層の保持ができるように keepDirectoryHierarchy オプションを追加 23 | * basePath オプションをobsoluteに変更 24 | * rootDir オプションに対応 25 | * generateTsConfig オプションを追加 26 | 27 | ##0.6.1 28 | * 不具合修正 29 | * 内部処理でScriptTargetが設定されていない場合に例外が発生することがある不具合?に初期値を設定しておくことで対応 30 | 31 | ## 0.6.0 32 | * Typescript 1.4.1 に対応 33 | * preserveConstEnums オプションの追加 34 | * noEmitOnError オプションの追加と ignoreError オプションの obsolete 化 35 | * suppressImplicitAnyIndexErrors オプションの追加 36 | * target オプションに ES6 を追加 37 | * comment オプションの削除 38 | * コンパイルのコードファイルをコマンドライン用の tsc.js から typescriptService.js に変更 39 | 40 | ## 0.4.7 / 0.4.8 41 | * watch の時に reference で指定されているファイルが更新されていても内容が反映されない不具合を修正 42 | 43 | ## 0.4.6 44 | * taskにdescription を追加 45 | * grunt-jsmin-sourcemap と競合?して grunt が task を実行できていなかった挙動の修正 46 | 47 | ## 0.4.5 48 | * README の option の記述を修正 49 | 50 | ## 0.4.4 51 | * TypeScript 1.3.0 に対応 52 | 53 | ## 0.4.3 54 | * 不具合の修正 55 | * 同じファイルが何回もemit実行されてしまうため "lib.d.ts を Emmit 時の対象外に変更" を取りやめ 56 | 57 | ## 0.4.2 58 | * 不具合の修正 59 | * 例外を握りつぶしてしまっていたのを表示するように修正 60 | * パフォーマンス対応 61 | * lib.d.ts を TypeCheck の対象外に変更 62 | * lib.d.ts を Emmit 時の対象外に変更 63 | * grunt の --verbose に対応 64 | * grunt の実行時に --showtsc オプションを付加することで処理内容と近い tsc コマンドを表示するように対応 65 | 66 | ## 0.4.1 67 | * 不具合の修正 68 | * watch のコンパイル失敗時の次回コンパイル対象 69 | * 参照するファイルを設定する references オプションを追加 70 | * lib.core.d.ts や lib.dom.d.ts の参照にも対応 71 | 72 | 73 | ## 0.4.0 74 | * All rewrite 75 | 全部書き直しを実施 76 | * Support TypeScript version 1.1.0-1 77 | TypeScript の ver 1.1.0-1 で動作するように対応 78 | 79 | ## 0.3.7 80 | * Added support to include the files that fail to file the next target of the compilation failure. 81 | watchのコンパイルが失敗した時に、次回のコンパイル対象に含めるように対応 82 | * Fixed a bug that it had failed to check the update date and time in the file deletion. 83 | watchでファイル削除時に更新日時の取得に失敗していた不具合を修正 84 | 85 | ## 0.3.6 86 | * Add support TypeScript version 1.0.0 and 1.0.1 87 | 88 | ## 0.3.5 89 | * Added watch.atBegin option to run tasks when watcher starts 90 | watch.atBeginオプションを追加。watchが開始された時にコンパイルを実行します。 91 | * Corresponding to delete files from the cache when a file is deleted 92 | ファイルが削除された時に、ファイルキャッシュからも削除してコンパイル対象にならないように対応 93 | 94 | ## 0.3.3 / 0.3.4 95 | * Compilation with watch option is more fast. 96 | 97 | ## 0.3.1 / 0.3.2 98 | * Added watch option 99 | 100 | ## 0.3.0 101 | * Update to TypeScript `1.0.0`. 102 | * Remove `base_path`, `sourcemap` and `nolib` options. (Changed to `basePath`, `sourceMap` and `noLib`) 103 | * Remove `ignoreTypeCheck` option. 104 | * **Breaking Changes**: `ignoreError:true` is now the default. 105 | -------------------------------------------------------------------------------- /Gruntfile.js: -------------------------------------------------------------------------------- 1 | module.exports = function(grunt){ 2 | 3 | var fs = require("fs"), 4 | path = require("path"), 5 | cp = require("child_process"), 6 | Promise = require("bluebird"); 7 | 8 | grunt.initConfig({ 9 | typescript: { 10 | simple: { 11 | src: ["test/fixtures/simple.ts"] 12 | }, 13 | dest:{ 14 | src:"test/fixtures/dest.ts", 15 | dest: "test/temp/dest", 16 | options: { 17 | keepDirectoryHierarchy: true 18 | } 19 | }, 20 | basePath:{ 21 | src:"test/fixtures/basepath.ts", 22 | dest: "test/temp/basepath", 23 | options: { 24 | basePath: "test/fixtures", 25 | keepDirectoryHierarchy: true 26 | } 27 | }, 28 | declaration:{ 29 | src:"test/fixtures/declaration.ts", 30 | options:{ 31 | declaration: true 32 | } 33 | }, 34 | sourcemap:{ 35 | src:"test/fixtures/sourcemap.ts", 36 | options:{ 37 | sourceMap:true 38 | } 39 | }, 40 | "sourcemap dest":{ 41 | src:"test/fixtures/sourcemap.ts", 42 | dest:"test/temp/sourcemap/", 43 | options:{ 44 | keepDirectoryHierarchy: true, 45 | basePath: "test/fixtures/", 46 | sourceMap:true 47 | } 48 | }, 49 | es5:{ 50 | src:"test/fixtures/es5.ts", 51 | options:{ 52 | target:"ES5" 53 | } 54 | }, 55 | es6:{ 56 | src:"test/fixtures/es6.ts", 57 | options:{ 58 | target:"ES6", 59 | noLib: true, 60 | references: "core" 61 | } 62 | }, 63 | amd:{ 64 | src:"test/fixtures/amd.ts", 65 | options:{ 66 | module:"amd" 67 | } 68 | }, 69 | commonjs:{ 70 | src:"test/fixtures/commonjs.ts", 71 | options:{ 72 | module:"commonjs" 73 | } 74 | }, 75 | umd: { 76 | src: "test/fixtures/umd.ts", 77 | options: { 78 | module: "umd" 79 | } 80 | }, 81 | system: { 82 | src: "test/fixtures/system.ts", 83 | options: { 84 | module: "system" 85 | } 86 | }, 87 | single:{ 88 | src: "test/fixtures/single/**/*.ts", 89 | dest: "test/temp/single.js", 90 | options: { 91 | declaration: true, 92 | sourceMap: true 93 | } 94 | }, 95 | crlf: { 96 | src: "test/fixtures/crlf.ts", 97 | options: { 98 | newLine: "crlf" 99 | } 100 | }, 101 | lf: { 102 | src: "test/fixtures/lf.ts", 103 | options: { 104 | newLine: "lf" 105 | } 106 | }, 107 | deco: { 108 | src: "test/fixtures/decorator.ts", 109 | options: { 110 | experimentalDecorators: true, 111 | target: "ES5" 112 | } 113 | }, 114 | deco2: { 115 | src: "test/fixtures/decorator2.ts", 116 | options: { 117 | experimentalDecorators: true, 118 | emitDecoratorMetadata: true, 119 | target: "ES5" 120 | } 121 | }, 122 | "comment default": { 123 | src: "test/fixtures/comments.ts", 124 | dest: "test/temp/comments.js" 125 | }, 126 | "comment remove true": { 127 | src: "test/fixtures/comments.ts", 128 | dest: "test/temp/comments_true.js", 129 | options: { 130 | removeComments: true 131 | } 132 | }, 133 | "comment remove false": { 134 | src: "test/fixtures/comments.ts", 135 | dest: "test/temp/comments_false.js", 136 | options: { 137 | removeComments: false 138 | } 139 | }, 140 | "jsx preserve": { 141 | src: "test/fixtures/jsxpreserve.tsx", 142 | options: { 143 | jsx: "preserve" 144 | } 145 | }, 146 | "jsx react": { 147 | src: "test/fixtures/jsxreact.tsx", 148 | options: { 149 | jsx: "react" 150 | } 151 | }, 152 | "async": { 153 | src: "test/fixtures/async.ts", 154 | options: { 155 | target: "ES6", 156 | experimentalAsyncFunctions: true 157 | } 158 | }, 159 | "references": { 160 | src: "test/fixtures/ref.ts", 161 | options: { 162 | noLib: true, 163 | references: ["core", "test/libs/**/*.d.ts"] 164 | } 165 | }, 166 | "noLib safe": { 167 | src: "test/fixtures/noLib.ts", 168 | options: { 169 | noLib: true, 170 | references: ["dom"] 171 | } 172 | }, 173 | "noLib": grunt.option("error") ? { 174 | src: "test/fixtures/noLib.ts", 175 | options: { 176 | noLib: true 177 | } 178 | } : {}, 179 | "noLibCore": grunt.option("error") ? { 180 | src: "test/fixtures/noLib.ts", 181 | options: { 182 | noLib: true, 183 | references: "core" 184 | } 185 | } : {}, 186 | "errorTypecheck": grunt.option("error") ? { 187 | src: "test/fixtures/error-typecheck.ts", 188 | options: { 189 | noEmitOnError: false 190 | } 191 | } : {}, 192 | "errorSyntax": grunt.option("error") ? { 193 | src: "test/fixtures/error-syntax.ts", 194 | options: { 195 | noEmitOnError: true 196 | } 197 | } : {}, 198 | simpleWatch: grunt.option("watch") ? { 199 | src: "test/watch/simple/target/**/*.ts", 200 | options: { 201 | watch: { 202 | before: ["watchBeforeTask"], 203 | after: ["watchAfterTask"], 204 | atBegin: true 205 | } 206 | } 207 | } : {}, 208 | singleWatch: grunt.option("watch") ? { 209 | src: "test/watch/single/target/**/*.ts", 210 | dest: "test/watch/single/target/result.js", 211 | options: { 212 | watch: { 213 | before: ["watchBeforeTask"], 214 | after: ["watchAfterTask"], 215 | atBegin: true 216 | } 217 | } 218 | } : {}, 219 | multiWatch: grunt.option("watch") ? { 220 | src: "test/watch/multi/target/**/*.ts", 221 | options: { 222 | watch: { 223 | path:["test/watch/multi/target/target1","test/watch/multi/target/target2"] 224 | } 225 | } 226 | } : {} 227 | }, 228 | nodeunit:{ 229 | tests:["test/test.js", "test/errorTest.js"] 230 | //tests:["test/errorTest.js"] 231 | //tests:["test/watchTest.js"] 232 | }, 233 | clean: { 234 | test: [ 235 | "test/fixtures/**/*.js", 236 | "test/fixtures/**/*.jsx", 237 | "test/fixtures/**/*.js.map", 238 | "test/fixtures/**/*.d.ts", 239 | "test/temp/**/*.*", 240 | "test/temp" 241 | ], 242 | expect: "test/expected" 243 | } 244 | }); 245 | 246 | function tsc(tsfile, option){ 247 | var command = "node " + path.resolve(path.dirname(require.resolve("typescript")), "tsc "); 248 | var optArray = Object.keys(option || {}).reduce(function(res, key){ 249 | res.push(key); 250 | if(option[key]){ 251 | res.push(option[key]); 252 | } 253 | return res; 254 | }, []) 255 | 256 | return new Promise(function(resolve, reject){ 257 | var childProcess = cp.exec(command + " " + tsfile + " " + optArray.join(" "), {}); 258 | childProcess.stdout.on('data', function (d) { grunt.log.writeln(d); }); 259 | childProcess.stderr.on('data', function (d) { grunt.log.error(d); }); 260 | 261 | childProcess.on('exit', function(code) { 262 | if (code !== 0) { 263 | reject(); 264 | } 265 | resolve(); 266 | }); 267 | }); 268 | } 269 | 270 | function getTestTsTasks(){ 271 | var results = []; 272 | results.push("clean:test"); 273 | 274 | var tsConfig = grunt.config.getRaw("typescript"); 275 | for(var p in tsConfig){ 276 | if(!tsConfig.hasOwnProperty(p)){ 277 | continue; 278 | } 279 | results.push("typescript:" + p); 280 | } 281 | results.push("nodeunit"); 282 | return results; 283 | } 284 | 285 | grunt.loadTasks("tasks"); 286 | grunt.loadNpmTasks("grunt-contrib-nodeunit"); 287 | grunt.loadNpmTasks("grunt-contrib-clean"); 288 | 289 | grunt.registerTask("egen", "Generate test expected files", function(){ 290 | var done = this.async(), 291 | start = Date.now(), 292 | execTsc = function(title, command){ 293 | start = Date.now(); 294 | return tsc(command).then(function(){ 295 | grunt.log.writeln(title + "(" + (Date.now() - start) + "ms)" ); 296 | }); 297 | } 298 | 299 | execTsc("Simple", "test/fixtures/simple.ts").then(function(){ 300 | grunt.file.copy("test/fixtures/simple.js", "test/expected/simple.js"); 301 | return execTsc("Dest", "test/fixtures/dest.ts --outDir test/expected"); 302 | }).then(function(){ 303 | return execTsc("BasePath", "test/fixtures/basepath.ts --outDir test/expected"); 304 | }).then(function(){ 305 | return execTsc("Declaration", "test/fixtures/declaration.ts --declaration"); 306 | }).then(function(){ 307 | grunt.file.copy("test/fixtures/declaration.js", "test/expected/declaration.js"); 308 | grunt.file.copy("test/fixtures/declaration.d.ts", "test/expected/declaration.d.ts"); 309 | return execTsc("SourceMap", "test/fixtures/sourcemap.ts --sourcemap"); 310 | }).then(function(){ 311 | grunt.file.copy("test/fixtures/sourcemap.js","test/expected/sourcemap.js"); 312 | grunt.file.copy("test/fixtures/sourcemap.js.map", "test/expected/sourcemap.js.map"); 313 | return execTsc("SourceMap Dest", "test/fixtures/sourcemap.ts --outDir test/expected/sourcemap --sourcemap"); 314 | }).then(function(){ 315 | grunt.file.copy("test/fixtures/sourcemap.js","test/expected/sourcemap.js"); 316 | grunt.file.copy("test/fixtures/sourcemap.js.map", "test/expected/sourcemap.js.map"); 317 | return execTsc("ES5", "test/fixtures/es5.ts --target ES5"); 318 | }).then(function(){ 319 | grunt.file.copy("test/fixtures/es5.js", "test/expected/es5.js"); 320 | return execTsc("ES6", "test/fixtures/es6.ts --target ES6") 321 | }).then(function(){ 322 | grunt.file.copy("test/fixtures/es6.js", "test/expected/es6.js"); 323 | return execTsc("AMD", "test/fixtures/amd.ts --module amd"); 324 | }).then(function(){ 325 | grunt.file.copy("test/fixtures/amd.js", "test/expected/amd.js"); 326 | return execTsc("CommonJS", "test/fixtures/commonjs.ts --module commonjs"); 327 | }).then(function(){ 328 | grunt.file.copy("test/fixtures/commonjs.js", "test/expected/commonjs.js"); 329 | return execTsc("UMD", "test/fixtures/umd.ts --module umd"); 330 | }).then(function(){ 331 | grunt.file.copy("test/fixtures/umd.js", "test/expected/umd.js"); 332 | return execTsc("System", "test/fixtures/system.ts --module system"); 333 | }).then(function(){ 334 | grunt.file.copy("test/fixtures/system.js", "test/expected/system.js"); 335 | return execTsc("CrLf", "test/fixtures/crlf.ts --newline crlf"); 336 | }).then(function(){ 337 | grunt.file.copy("test/fixtures/crlf.js", "test/expected/crlf.js"); 338 | return execTsc("Lf", "test/fixtures/lf.ts --newline lf"); 339 | }).then(function(){ 340 | grunt.file.copy("test/fixtures/lf.js", "test/expected/lf.js"); 341 | return execTsc("Decorator", "test/fixtures/decorator.ts --experimentalDecorators --target ES5"); 342 | }).then(function(){ 343 | grunt.file.copy("test/fixtures/decorator.js", "test/expected/decorator.js"); 344 | return execTsc("Decorator2", "test/fixtures/decorator2.ts --experimentalDecorators --target ES5 --emitDecoratorMetadata"); 345 | }).then(function(){ 346 | grunt.file.copy("test/fixtures/decorator2.js", "test/expected/decorator2.js"); 347 | return execTsc("Single", "test/fixtures/single/dir/single2.ts test/fixtures/single/single1.ts --out test/temp/single.js --sourceMap"); 348 | }).then(function(){ 349 | grunt.file.copy("test/temp/single.js", "test/expected/single.js"); 350 | return execTsc("Comment", "test/fixtures/comments.ts --out test/expected/comments.js"); 351 | }).then(function(){ 352 | return execTsc("Comment true", "test/fixtures/comments.ts --out test/expected/comments_true.js --removeComments"); 353 | }).then(function(){ 354 | return execTsc("Comment false", "test/fixtures/comments.ts --out test/expected/comments_false.js"); //default 355 | }).then(function(){ 356 | return execTsc("Preserve Jsx", "test/fixtures/jsxpreserve.tsx --jsx preserve"); 357 | }).then(function(){ 358 | grunt.file.copy("test/fixtures/jsxpreserve.jsx", "test/expected/jsxpreserve.jsx"); 359 | return execTsc("React Jsx", "test/fixtures/jsxreact.tsx --jsx react"); 360 | }).then(function(){ 361 | grunt.file.copy("test/fixtures/jsxreact.js", "test/expected/jsxreact.js"); 362 | return execTsc("Async", "test/fixtures/async.ts --experimentalAsyncFunctions -t ES6"); 363 | }).then(function(){ 364 | grunt.file.copy("test/fixtures/async.js", "test/expected/async.js"); 365 | done(true); 366 | }).catch(function(){ 367 | done(false); 368 | }); 369 | 370 | //execTsc("ES6", "test/fixtures/es6.ts --target ES6").then(function(){ 371 | // done(true); 372 | //}); 373 | }); 374 | 375 | grunt.registerTask("build", "Build", function(){ 376 | var done = this.async(); 377 | tsc("").then(function(){ 378 | done(true); 379 | }).catch(function(){ 380 | done(false); 381 | }); 382 | }); 383 | 384 | grunt.registerTask("watchBeforeTask", function(){ 385 | var done = this.async(); 386 | setTimeout(function(){ 387 | console.log("before"); 388 | done(true); 389 | },100); 390 | }); 391 | 392 | grunt.registerTask("watchAfterTask", function(){ 393 | var done = this.async(); 394 | setTimeout(function(){ 395 | console.log("after"); 396 | done(true); 397 | },100); 398 | }); 399 | 400 | grunt.registerTask("test", getTestTsTasks()); 401 | 402 | grunt.registerTask("setup", ["clean", "egen"]); 403 | }; 404 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2013-2015 Kazuhide Maruyama 2 | 3 | Permission is hereby granted, free of charge, to any person 4 | obtaining a copy of this software and associated documentation 5 | files (the "Software"), to deal in the Software without 6 | restriction, including without limitation the rights to use, 7 | copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the 9 | Software is furnished to do so, subject to the following 10 | conditions: 11 | 12 | The above copyright notice and this permission notice shall be 13 | included in all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 17 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 18 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 19 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 20 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 21 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | grunt-typescript 2 | ================ 3 | [![Build Status](https://travis-ci.org/k-maru/grunt-typescript.png?branch=master)](https://travis-ci.org/k-maru/grunt-typescript) [![NPM version](https://badge.fury.io/js/grunt-typescript.png)](http://badge.fury.io/js/grunt-typescript) 4 | 5 | [![NPM](https://nodei.co/npm/grunt-typescript.png?downloads=true)](https://nodei.co/npm/grunt-typescript/) 6 | 7 | Compile TypeScript in Grunt 8 | 9 | [Release Note](CHANGELOG.md) 10 | 11 | Important! 12 | ---------- 13 | `` 14 | BasePath option has been deprecated. Method for determining an output directory has been changed in the same way as the TSC. Please re-set output directory with the new rootDir option or use keepDirectoryHierachy option.However, keepDirectoryHierachy option would not be available long. 15 | `` 16 | 17 | ## Documentation 18 | You'll need to install `grunt-typescript` first: 19 | 20 | ``` 21 | npm install grunt-typescript --save-dev 22 | ``` 23 | 24 | or add the following line to devDependencies in your package.json 25 | 26 | ``` 27 | "grunt-typescript": "", 28 | ``` 29 | 30 | Then modify your `Gruntfile.js` file by adding the following line: 31 | 32 | ```js 33 | grunt.loadNpmTasks('grunt-typescript'); 34 | ``` 35 | 36 | Then add some configuration for the plugin like so: 37 | 38 | ```js 39 | grunt.initConfig({ 40 | ... 41 | typescript: { 42 | base: { 43 | src: ['path/to/typescript/files/**/*.ts'], 44 | dest: 'where/you/want/your/js/files', 45 | options: { 46 | module: 'amd', //or commonjs 47 | target: 'es5', //or es3 48 | basePath: 'path/to/typescript/files', 49 | sourceMap: true, 50 | declaration: true 51 | } 52 | } 53 | }, 54 | ... 55 | }); 56 | ``` 57 | 58 | If you want to create a js file that is a concatenation of all the ts file (like -out option from tsc), 59 | you should specify the name of the file with the '.js' extension to dest option. 60 | 61 | ```js 62 | grunt.initConfig({ 63 | ... 64 | typescript: { 65 | base: { 66 | src: ['path/to/typescript/files/**/*.ts'], 67 | dest: 'where/you/want/your/js/file.js', 68 | options: { 69 | module: 'amd', //or commonjs 70 | } 71 | } 72 | }, 73 | ... 74 | }); 75 | ``` 76 | 77 | ## Options 78 | 79 | ### typescript options 80 | 81 | | name | type | description | 82 | |--------------------------------|---------|---------------------------------------------------------------------------------------------------------------------------------------| 83 | | noLib | boolean | Do not include a default lib.d.ts with global declarations | 84 | | target | string | Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES6' | 85 | | module | string | Specify module code generation: "commonjs" (default), "amd", "system" or "umd" | 86 | | sourceMap | boolean | Generates corresponding .map files | 87 | | declaration | boolean | Generates corresponding .d.ts file | 88 | | removeComments | boolean | Do not emit comments to output. | 89 | | noImplicitAny | boolean | Warn on expressions and declarations with an implied 'any' type. | 90 | | noResolve | boolean | Skip resolution and preprocessing. | 91 | | preserveConstEnums | boolean | Do not erase const enum declarations in generated code. | 92 | | noEmitOnError | boolean | Do not emit outputs if any type checking errors were reported.The default for this option is set to true for backwards compatibility. | 93 | | suppressImplicitAnyIndexErrors | boolean | Suppress noImplicitAny errors for indexing objects lacking index signatures. | 94 | | experimentalDecorators | boolean | | 95 | | emitDecoratorMetadata | boolean | | 96 | | newLine | string | | 97 | | inlineSourceMap | boolean | | 98 | | inlineSources | boolean | | 99 | | noEmitHelpers | boolean | Do not generate custom helper functions like __extends in compiled output. | 100 | | jsx | string | Support JSX in '.tsx' files: 'React' or 'Preserve'. | 101 | | experimentalAsyncFunctions | boolean | Support ES7-proposed asynchronous functions using the async/await keywords. | 102 | | rootDir | string | Specifies the root directory of input files. Only use to control the output directory structure with outDir option. | 103 | 104 | ### original options 105 | 106 | ####generateTsConfig 107 | **type**: `string` | `boolean` 108 | 109 | generateTsConfig option will generate the content and equivalent tsconfig.json that are specified in the option. 110 | The value specify the directory name to be output. It is output to the current directory when you specify true. 111 | 112 | #### references 113 | **type**: `string` | `string[]` 114 | 115 | Set auto reference libraries. 116 | 117 | ```js 118 | grunt.initConfig({ 119 | ... 120 | typescript: { 121 | base: { 122 | src: ['path/to/typescript/files/**/*.ts'], 123 | options: { 124 | references: [ 125 | "core", //lib.core.d.ts 126 | "dom", //lib.dom.d.ts 127 | "scriptHost", //lib.scriptHost.d.ts 128 | "webworker", //lib.webworker.d.ts 129 | "path/to/reference/files/**/*.d.ts" 130 | ] 131 | } 132 | } 133 | }, 134 | ... 135 | }); 136 | ``` 137 | 138 | #### watch 139 | **type**: `string` | `boolean` | { path?:<`string` | `string[]``>; before?: <`string` | `string[]``>; after?: <`string` | `string[]``>; atBegin: `boolean` } 140 | 141 | Watch .ts files. 142 | It runs very quickly the second time since the compilation. It is because you only want to read and output file is limited. 143 | 144 | Specify the directory where you want to monitor in the options. 145 | 146 | ```js 147 | grunt.initConfig({ 148 | ... 149 | typescript: { 150 | base: { 151 | src: ['path/to/typescript/files/**/*.ts'], 152 | options: { 153 | watch: 'path/to/typescript/files' //or ['path/to/typescript/files1', 'path/to/typescript/files2'] 154 | } 155 | } 156 | }, 157 | ... 158 | }); 159 | ``` 160 | 161 | If you specify the true, then automatically detects the directory. 162 | 163 | ```js 164 | grunt.initConfig({ 165 | ... 166 | typescript: { 167 | base: { 168 | src: ['path/to/typescript/files/**/*.ts'], 169 | options: { 170 | watch: true //Detect all target files root. eg: 'path/to/typescript/files/' 171 | } 172 | } 173 | }, 174 | ... 175 | }); 176 | ``` 177 | 178 | For expansion of the future, You can also be specified 'object'. 179 | 180 | ```js 181 | grunt.initConfig({ 182 | ... 183 | typescript: { 184 | base: { 185 | src: ['path/to/typescript/files/**/*.ts'], 186 | options: { 187 | watch: { 188 | path: 'path/to/typescript/files', //or ['path/to/typescript/files1', 'path/to/typescript/files2'] 189 | before: ['beforetasks'], //Set before tasks. eg: clean task 190 | after: ['aftertasks'] //Set after tasks. eg: minify task 191 | atBegin: true //Run tasks when watcher starts. default false 192 | } 193 | } 194 | } 195 | }, 196 | ... 197 | }); 198 | ``` 199 | 200 | #### basePath(obsolete) 201 | **type**: `string` 202 | 203 | Path component to cut off when mapping the source files to dest files. 204 | 205 | #### keepDirectoryHierarchy(obsolete) 206 | **type**: `boolean` 207 | 208 | Path component to cut off when mapping the source files to dest files. 209 | 210 | ```js 211 | grunt.initConfig({ 212 | ... 213 | typescript: { 214 | base: { 215 | src: ['path/to/typescript/files/**/*.ts'], 216 | dest: 'bin' 217 | options: { 218 | keepDirectoryHierarchy: true 219 | } 220 | } 221 | }, 222 | ... 223 | }); 224 | ``` 225 | 226 | If keepDirectoryHierarchy option is true, it is output as follows. 227 | 228 | ``` 229 | /bin 230 | - /path 231 | --- /to 232 | ----- /typescript 233 | ------- /files 234 | --------- *.ts 235 | ``` 236 | 237 | If keepDirectoryHierarchy option is false or not set, it is output as follows. 238 | It is same way as the tsc. 239 | 240 | ``` 241 | /bin 242 | - *.ts 243 | ``` 244 | 245 | 246 | ※I'm sorry for poor English 247 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "author": "kazuhide maruyama", 3 | "name": "grunt-typescript", 4 | "description": "compile typescript to javascript", 5 | "version": "0.8.0", 6 | "homepage": "https://github.com/k-maru/grunt-typescript", 7 | "repository": { 8 | "type": "git", 9 | "url": "git@github.com:k-maru/grunt-typescript.git" 10 | }, 11 | "bugs": { 12 | "url": "https://github.com/k-maru/grunt-typescript/issues" 13 | }, 14 | "licenses": [ 15 | { 16 | "type": "MIT", 17 | "url": "https://github.com/k-maru/grunt-typescript/blob/master/LICENSE" 18 | } 19 | ], 20 | "main": "Gruntfile.js", 21 | "scripts": { 22 | "start": "grunt build", 23 | "test": "grunt test" 24 | }, 25 | "engines": { 26 | "node": ">= 0.8.0" 27 | }, 28 | "dependencies": { 29 | "typescript": "1.6.2", 30 | "bluebird": "~2.9.34", 31 | "chokidar": "^1.0.5" 32 | }, 33 | "peerDependencies": { 34 | "grunt": "~0.4.5" 35 | }, 36 | "devDependencies": { 37 | "grunt": "~0.4.5", 38 | "grunt-contrib-nodeunit": "~0.4.1", 39 | "grunt-contrib-clean": "~0.6.0" 40 | }, 41 | "optionalDependencies": { 42 | }, 43 | "keywords": [ 44 | "gruntplugin", 45 | "typescript" 46 | ] 47 | } 48 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | /// 4 | /// 5 | 6 | import * as ts from "typescript"; 7 | import * as gts from "./modules/task"; 8 | 9 | import * as util from "./modules/util"; 10 | import * as Promise from "bluebird"; 11 | import * as compiler from "./modules/compiler"; 12 | 13 | function startup(grunt: IGrunt) { 14 | 15 | grunt.registerMultiTask("typescript", "Compile typescript to javascript.", function(){ 16 | let that: grunt.task.IMultiTask<{src: string;}> = this, 17 | done = that.async(), 18 | promises = that.files.map((gruntFile) => { 19 | let task = new gts.Task(grunt, that.options({}), gruntFile) 20 | return compiler.execute(task); 21 | }); 22 | 23 | Promise.all(promises).then(() => { 24 | done() 25 | }).catch(() => { 26 | done(false); 27 | }); 28 | }); 29 | } 30 | export = startup; -------------------------------------------------------------------------------- /src/modules/compiler.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | /// 4 | /// 5 | /// 6 | /// 7 | /// 8 | 9 | import * as ts from "typescript"; 10 | import * as gts from "./task"; 11 | import * as util from "./util"; 12 | import * as watche from "./watcher"; 13 | import * as Promise from "bluebird"; 14 | 15 | let _os: NodeJS.OS = require("os"); 16 | 17 | export function execute(task: gts.Task): Promise { 18 | 19 | let host = task.getHost(), 20 | options = task.getOptions(), 21 | promise = new Promise((resolve, reject) => { 22 | if(options.watch){ 23 | watch(task); 24 | }else{ 25 | try{ 26 | if(compile(task)){ 27 | resolve(undefined); 28 | }else{ 29 | reject(false); 30 | } 31 | 32 | }catch(e){ 33 | reject(false); 34 | } 35 | } 36 | }); 37 | return promise; 38 | } 39 | 40 | function watch(task: gts.Task): void{ 41 | let options = task.getOptions(), 42 | watchOpt = options.watch, 43 | watchPath = watchOpt.path, 44 | targetPaths: {[key:string]: string;} = {}, 45 | startCompile = (files?: string[]) => { 46 | return runTask(task, watchOpt.before).then(() => { 47 | if(!recompile(task, files)){ 48 | //失敗だった場合はリセット 49 | task.getHost().reset(files); 50 | } 51 | return runTask(task, watchOpt.after); 52 | }).then(function(){ 53 | writeWatching(watchPath); 54 | }); 55 | }, 56 | watcher = watche.createWatcher(watchPath, (files, done) => { 57 | startCompile(Object.keys(files)).finally(() => { 58 | done(); 59 | }); 60 | }); 61 | 62 | if(watchOpt.atBegin){ 63 | startCompile().finally(() => { 64 | watcher.start(); 65 | }); 66 | }else{ 67 | watcher.start(); 68 | } 69 | } 70 | 71 | function writeWatching(watchPath: string[]): void { 72 | util.write(""); 73 | util.write("Watching... " + watchPath); 74 | } 75 | 76 | function recompile(task: gts.Task, updateFiles: string[] = []): boolean { 77 | 78 | task.verbose("--task.recompile"); 79 | 80 | task.getHost().reset(updateFiles); 81 | return compile(task); 82 | } 83 | 84 | function runTask(task: gts.Task, tasks: string[]): Promise { 85 | 86 | let grunt = task.getGrunt(); 87 | 88 | task.verbose("--task.runTask"); 89 | 90 | return asyncEach(tasks, (taskName:string, index:number, next:()=> void) => { 91 | 92 | task.verbose(" external task start: " + taskName); 93 | 94 | let flags = grunt.option.flags().map(f => !!f ? f + "" : ""); 95 | 96 | grunt.util.spawn({ 97 | cmd: undefined, 98 | grunt: true, 99 | args: [taskName].concat(flags), 100 | opts: {stdio: 'inherit'} 101 | }, (err, result, code) => { 102 | 103 | task.verbose("external task end: " + task); 104 | 105 | next(); 106 | }); 107 | }); 108 | } 109 | 110 | function asyncEach(items: T[], callback: (item: T, index: number, next: () => void) => void): Promise{ 111 | return new Promise((resolve, reject) => { 112 | let length = items.length, 113 | exec = (i: number) => { 114 | if(length <= i){ 115 | resolve(undefined); 116 | return; 117 | } 118 | let item = items[i]; 119 | callback(item, i, () => { 120 | i = i + 1; 121 | exec(i); 122 | }); 123 | }; 124 | exec(0); 125 | }); 126 | } 127 | 128 | function compile(task: gts.Task): boolean{ 129 | 130 | let start = Date.now(), 131 | options = task.getOptions(), 132 | host = task.getHost(), 133 | targetFiles = getTargetFiles(options); 134 | 135 | task.verbose("- write tsconfig.json"); 136 | writeTsConfig(options, targetFiles, task); 137 | 138 | task.verbose("- create program"); 139 | 140 | let program = ts.createProgram(targetFiles, options.tsOptions, host); 141 | let diagnostics = program.getSyntacticDiagnostics(); 142 | 143 | reportDiagnostics(diagnostics); 144 | 145 | if(diagnostics.length){ 146 | return false; 147 | } 148 | 149 | if (diagnostics.length === 0) { 150 | diagnostics = program.getGlobalDiagnostics(); 151 | reportDiagnostics(diagnostics); 152 | 153 | if (diagnostics.length === 0) { 154 | diagnostics = program.getSemanticDiagnostics(); 155 | reportDiagnostics(diagnostics); 156 | } 157 | } 158 | if(diagnostics.length){ 159 | return false; 160 | } 161 | 162 | if(options.tsOptions.noEmit){ 163 | host.writeResult(Date.now() - start); 164 | return true; 165 | } 166 | 167 | task.verbose("- emit"); 168 | let emitOutput = program.emit(); 169 | reportDiagnostics(emitOutput.diagnostics); 170 | 171 | if(emitOutput.diagnostics.length){ 172 | return false; 173 | } 174 | 175 | if (emitOutput.emitSkipped) { 176 | task.verbose(" emit skipped"); 177 | } 178 | 179 | host.writeResult(Date.now() - start); 180 | 181 | return true; 182 | } 183 | 184 | function getTargetFiles(options: gts.CompilerOptions): string[]{ 185 | 186 | let codeFiles = options.targetFiles(), 187 | libFiles: string[] = options.references(); 188 | 189 | return libFiles.concat(codeFiles); 190 | } 191 | 192 | function reportDiagnostic(diagnostic: ts.Diagnostic, isWarn = false) { 193 | let output = "", 194 | newLine = _os.EOL; 195 | 196 | if (diagnostic.file) { 197 | var loc = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); 198 | 199 | output += `${ diagnostic.file.fileName }(${ loc.line + 1 },${ loc.character + 1 }): `; 200 | } 201 | 202 | var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); 203 | output += `${ category } TS${ diagnostic.code }: ${ ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine) }${ newLine }`; 204 | 205 | if(isWarn){ 206 | util.writeWarn(output); 207 | }else{ 208 | util.writeError(output); 209 | } 210 | } 211 | 212 | function reportDiagnostics(diagnostics: ts.Diagnostic[], isWarn = false) { 213 | for(let d of diagnostics){ 214 | reportDiagnostic(d, isWarn); 215 | } 216 | } 217 | 218 | function writeTsConfig(options: gts.CompilerOptions, targetFiles: string[], logger: gts.Logger): void { 219 | 220 | if(!options.generateTsConfig){ 221 | return; 222 | } 223 | 224 | let outputDir = util.getCurrentDirectory(); 225 | 226 | if(typeof options.generateTsConfig === "string"){ 227 | outputDir = util.abs(options.generateTsConfig.toString()); 228 | } 229 | 230 | let outputFile = util.combinePaths(outputDir, "tsconfig.json"); 231 | 232 | logger.verbose(` dir: ${outputDir}, file: ${outputFile}`); 233 | 234 | let tsOpts = options.tsOptions; 235 | 236 | let config = { 237 | compilerOptions: { 238 | removeComments: tsOpts.removeComments, 239 | sourceMap: tsOpts.sourceMap, 240 | declaration: tsOpts.declaration, 241 | out: tsOpts.out, 242 | outDir: tsOpts.outDir, 243 | noLib: tsOpts.noLib, 244 | noImplicitAny: tsOpts.noImplicitAny, 245 | noResolve: tsOpts.noResolve, 246 | target: tsOpts.target === ts.ScriptTarget.ES3 ? "es3" : 247 | tsOpts.target === ts.ScriptTarget.ES5 ? "es5" : 248 | tsOpts.target === ts.ScriptTarget.ES6 ? "es6" : undefined, 249 | rootDir: tsOpts.rootDir, 250 | module: tsOpts.module === ts.ModuleKind.AMD ? "amd" : 251 | tsOpts.module === ts.ModuleKind.CommonJS ? "commonjs" : 252 | tsOpts.module === ts.ModuleKind.System ? "system" : 253 | tsOpts.module === ts.ModuleKind.UMD ? "umd" : undefined , 254 | preserveConstEnums: tsOpts.preserveConstEnums, 255 | noEmitOnError: tsOpts.noEmitOnError, 256 | suppressImplicitAnyIndexErrors: tsOpts.suppressImplicitAnyIndexErrors, 257 | emitDecoratorMetadata: tsOpts.emitDecoratorMetadata, 258 | newLine: tsOpts.newLine === ts.NewLineKind.CarriageReturnLineFeed ? "crlf" : 259 | tsOpts.newLine === ts.NewLineKind.LineFeed ? "lf" : undefined, 260 | inlineSourceMap: tsOpts.inlineSourceMap, 261 | inlineSources: tsOpts.inlineSources, 262 | noEmitHelper: tsOpts.noEmitHelpers 263 | }, 264 | files: targetFiles.map(targetFile => util.normalizePath(util.relativePath(outputDir, targetFile))) 265 | }; 266 | 267 | util.createDirectoryRecurse(outputDir); 268 | util.writeFile(outputFile, JSON.stringify(config, null, " ")); 269 | 270 | util.writeInfo(`tsconfig.json generated: ${outputFile}`); 271 | } -------------------------------------------------------------------------------- /src/modules/host.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | /// 4 | /// 5 | /// 6 | /// 7 | 8 | import * as ts from "typescript"; 9 | import * as gts from "./task"; 10 | import * as util from "./util"; 11 | import * as option from "./option"; 12 | 13 | let _path: NodeJS.Path = require("path"), 14 | _fs: NodeJS.FileSystem = require("fs"), 15 | _os: NodeJS.OS = require("os"), 16 | existingDirectories: ts.Map = {}; 17 | 18 | 19 | 20 | function createSourceFile(fileName: string, text: string, languageVersion: ts.ScriptTarget): gts.SourceFile{ 21 | if(text !== undefined){ 22 | let result = ts.createSourceFile(fileName, text, languageVersion); 23 | result.mtime = _fs.statSync(fileName).mtime.getTime(); 24 | return result; 25 | } 26 | } 27 | 28 | function directoryExists(directoryPath: string): boolean { 29 | if (util.hasProperty(existingDirectories, directoryPath)) { 30 | return true; 31 | } 32 | //TODO: 33 | if (util.directoryExists(directoryPath)) { 34 | existingDirectories[directoryPath] = true; 35 | return true; 36 | } 37 | return false; 38 | } 39 | 40 | function ensureDirectoriesExist(directoryPath: string) { 41 | if (directoryPath.length > util.getRootLength(directoryPath) && !directoryExists(directoryPath)) { 42 | let parentDirectory = util.getDirectoryPath(directoryPath); 43 | ensureDirectoriesExist(parentDirectory); 44 | //TODO: 45 | util.createDirectory(directoryPath); 46 | } 47 | } 48 | 49 | function prepareOutputDir(fileName: string, options: gts.CompilerOptions): string{ 50 | if(options.singleFile || !options.dest){ 51 | return fileName; 52 | } 53 | 54 | var currentPath = util.getCurrentDirectory(), 55 | relativePath = util.normalizePath(_path.relative(currentPath, fileName)), 56 | basePath = options.basePath; 57 | 58 | if(basePath){ 59 | if(relativePath.substr(0, basePath.length) !== basePath){ 60 | throw new Error(fileName + " is not started basePath"); 61 | } 62 | relativePath = relativePath.substr(basePath.length); 63 | } 64 | return util.normalizePath(_path.resolve(currentPath, options.dest, relativePath)); 65 | } 66 | 67 | function prepareSourcePath(sourceFileName: string, preparedFileName: string, contents: string, options: gts.CompilerOptions): string{ 68 | if(options.singleFile || !options.dest){ 69 | return contents; 70 | } 71 | if(sourceFileName === preparedFileName){ 72 | return contents; 73 | } 74 | if(!(/\.js\.map$/.test(sourceFileName))){ 75 | return contents; 76 | } 77 | var mapData: any = JSON.parse(contents), 78 | source = mapData.sources[0]; 79 | mapData.sources.length = 0; 80 | var relative = _path.relative(_path.dirname(preparedFileName), sourceFileName); 81 | mapData.sources.push(util.normalizePath(_path.join(_path.dirname(relative), source))); 82 | return JSON.stringify(mapData); 83 | } 84 | 85 | function getNewLineChar(options: gts.CompilerOptions): string{ 86 | let optValue = options.tsOptions.newLine; 87 | if(optValue === ts.NewLineKind.CarriageReturnLineFeed) { 88 | return "\r\n"; 89 | } else if(optValue === ts.NewLineKind.LineFeed) { 90 | return "\n"; 91 | } 92 | return _os.EOL; 93 | } 94 | 95 | export function createHost(grunt: IGrunt, options: gts.CompilerOptions, logger: gts.Logger): gts.CompilerHost{ 96 | 97 | let platform: string = _os.platform(), 98 | // win32\win64 are case insensitive platforms, MacOS (darwin) by default is also case insensitive 99 | useCaseSensitiveFileNames: boolean = platform !== "win32" && platform !== "win64" && platform !== "darwin", 100 | sourceFileCache: {[key: string]: gts.SourceFile} = {}, 101 | newSourceFiles: string[] = [], 102 | outputFiles: string[] = []; 103 | 104 | function getCanonicalFileName(fileName: string): string { 105 | // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. 106 | // otherwise use toLowerCase as a canonical form. 107 | return useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); 108 | } 109 | 110 | function getSourceFile(fileName: string, languageVersion: ts.ScriptTarget, onError?: (message: string) => void): gts.SourceFile { 111 | 112 | logger.verbose("--host.getSourceFile: " + fileName); 113 | 114 | let fullName = util.abs(fileName), 115 | text = ""; 116 | 117 | if(fullName in sourceFileCache){ 118 | let chechedSourceFile = sourceFileCache[fullName], 119 | newMtime = _fs.statSync(fullName).mtime.getTime(); 120 | 121 | if(chechedSourceFile.mtime !== newMtime){ 122 | delete sourceFileCache[fullName]; 123 | }else{ 124 | logger.verbose(" cached"); 125 | return sourceFileCache[fullName]; 126 | } 127 | } 128 | 129 | if(!util.dirOrFileExists(fileName)){ 130 | return; 131 | } 132 | 133 | try { 134 | text = util.readFile(fileName, options.tsOptions.charset); 135 | } 136 | catch (e) { 137 | if (onError) { 138 | onError(e.message); 139 | } 140 | text = ""; 141 | } 142 | 143 | let result = createSourceFile(fileName, text, languageVersion); 144 | 145 | if(result){ 146 | logger.verbose(" readed"); 147 | sourceFileCache[fullName] = result; 148 | // if(!options.singleFile && options.watch && !options.tsOptions.noEmit){ 149 | // newSourceFiles.push(fullName); 150 | // } 151 | } 152 | return result; 153 | } 154 | 155 | function writeFile(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void) { 156 | 157 | logger.verbose("--host.writeFile: " + fileName); 158 | 159 | let fullName = util.abs(fileName); 160 | 161 | // if(!options.singleFile && options.watch && !options.tsOptions.noEmit && newSourceFiles.length){ 162 | // return; 163 | // } 164 | 165 | //watch の時に新しいファイルだけ出力をしたいが、判定できないためコメントアウト 166 | // if(!options.singleFile){ 167 | // let tsFile = fullName.replace(/\.js\.map$/, ".ts").replace(/\.js$/, ".ts"); 168 | // if(!(tsFile in newSourceFiles)){ 169 | // tsFile = fullName.replace(/\.d\.ts$/, ".ts"); 170 | // if(!(tsFile in newSourceFiles)) { 171 | // logger.verbose(" canceled"); 172 | // return; 173 | // } 174 | // } 175 | // } 176 | 177 | //出力先ディレクトリのパスに変換 178 | if(!!options.keepDirectoryHierarchy){ 179 | try{ 180 | let newFileName = prepareOutputDir(fileName, options); 181 | //map ファイルの参照先パスを変換 182 | let targetData = prepareSourcePath(fileName, newFileName, data, options); 183 | logger.verbose(` change file path: ${fileName} -> ${newFileName}`); 184 | 185 | fileName = newFileName; 186 | data = targetData; 187 | fullName = util.abs(fileName); 188 | }catch(e){ 189 | console.log(e); 190 | } 191 | } 192 | 193 | try { 194 | ensureDirectoriesExist(util.getDirectoryPath(util.normalizePath(fullName))); 195 | //TODO: 196 | util.writeFile(fullName, data, writeByteOrderMark); 197 | outputFiles.push(fullName); 198 | 199 | logger.verbose(` write file: ${fullName}`); 200 | } 201 | catch (e) { 202 | if (onError) onError(e.message); 203 | } 204 | } 205 | 206 | function writeResult(ms: number): void{ 207 | let result: {js: string[]; m: string[]; d: string[]; other: string[];} = {js: [], m: [], d: [], other: []}, 208 | resultMessage: string, 209 | pluralizeFile = (n: number) => (n + " file") + ((n === 1) ? "" : "s"); 210 | 211 | outputFiles.forEach(function (item: string) { 212 | if (/\.js$/.test(item)) result.js.push(item); 213 | else if (/\.js\.map$/.test(item)) result.m.push(item); 214 | else if (/\.d\.ts$/.test(item)) result.d.push(item); 215 | else result.other.push(item); 216 | }); 217 | 218 | resultMessage = "js: " + pluralizeFile(result.js.length) 219 | + ", map: " + pluralizeFile(result.m.length) 220 | + ", declaration: " + pluralizeFile(result.d.length) 221 | + " (" + ms + "ms)"; 222 | 223 | if (options.singleFile) { 224 | if(result.js.length > 0){ 225 | util.write("File " + (result.js[0])["cyan"] + " created."); 226 | } 227 | util.write(resultMessage); 228 | } else { 229 | util.write(pluralizeFile(outputFiles.length)["cyan"] + " created. " + resultMessage); 230 | } 231 | } 232 | 233 | function reset(fileNames: string[]): void { 234 | if (util.isUndef(fileNames)) { 235 | sourceFileCache = {}; 236 | } 237 | if (util.isArray(fileNames)) { 238 | fileNames.forEach((f) => { 239 | let fullName = util.abs(f); 240 | if (fullName in sourceFileCache) { 241 | delete sourceFileCache[fullName]; 242 | } 243 | }); 244 | } 245 | 246 | outputFiles.length = 0; 247 | newSourceFiles = []; 248 | } 249 | 250 | let newLineChar = getNewLineChar(options); 251 | 252 | return { 253 | getSourceFile, 254 | getDefaultLibFileName: (options: ts.CompilerOptions) => { 255 | logger.verbose(`bin dir = ${util.getBinDir()}`); 256 | return util.combinePaths(util.getBinDir(), options.target === ts.ScriptTarget.ES6 ? "lib.es6.d.ts" : "lib.d.ts"); 257 | }, 258 | writeFile, 259 | getCurrentDirectory: () => util.getCurrentDirectory(), 260 | useCaseSensitiveFileNames: () => useCaseSensitiveFileNames, 261 | getCanonicalFileName, 262 | getNewLine: () => newLineChar, 263 | fileExists: path => util.fileExists(path), 264 | readFile: fileName => util.readFile(fileName), 265 | writeResult, 266 | reset 267 | }; 268 | } -------------------------------------------------------------------------------- /src/modules/option.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | 4 | import * as util from "./util"; 5 | import * as ts from "typescript"; 6 | import * as gts from "./task"; 7 | 8 | let _path: NodeJS.Path = require("path"), 9 | _fs: NodeJS.FileSystem = require("fs"); 10 | 11 | function prepareWatch(opt: any, files: string[]): gts.WatchOptions{ 12 | let after: string[] = [], 13 | before: string[] = [], 14 | val: any = opt.watch, 15 | getDirNames = (files: string[]): string[] => { 16 | return files.map(file => { 17 | if(_fs.existsSync(file)){ 18 | if(_fs.statSync(file).isDirectory()){ 19 | return file; 20 | } 21 | }else{ 22 | if(!_path.extname(file)){ 23 | return file; 24 | } 25 | } 26 | return util.normalizePath(_path.resolve(_path.dirname(file))); 27 | }); 28 | }, 29 | extractPath = (files: string[]): string[] => { 30 | let dirNames: string[] = getDirNames(files), 31 | result = dirNames.reduce((prev, curr) => { 32 | if(!prev){ 33 | return curr; 34 | } 35 | let left = util.normalizePath(_path.relative(prev, curr)), 36 | right = util.normalizePath(_path.relative(curr, prev)), 37 | match = left.match(/^(\.\.(\/)?)+/); 38 | if(match){ 39 | return util.normalizePath(_path.resolve(prev, match[0])); 40 | } 41 | match = right.match(/^(\.\.(\/)?)+/); 42 | if(match){ 43 | return util.normalizePath( _path.resolve(curr, match[0])); 44 | } 45 | return prev; 46 | }, undefined); 47 | if(result){ 48 | return [result]; 49 | } 50 | }; 51 | 52 | if(!val){ 53 | return undefined; 54 | } 55 | if(util.isStr(val) || util.isArray(val)){ 56 | return { 57 | path: util.isStr(val) ? [val] : val, 58 | after: [], 59 | before: [], 60 | atBegin: false 61 | }; 62 | } 63 | if(util.isBool(val) && !!val){ 64 | return { 65 | path: extractPath(files), 66 | after: [], 67 | before: [], 68 | atBegin: false 69 | } 70 | } 71 | if(!val.path){ 72 | val.path = extractPath(files); 73 | if(!val.path){ 74 | //util.writeWarn("Can't auto detect watch directory. Please place one or more files or set the path option."); 75 | return undefined; 76 | } 77 | } 78 | if(val.after && !util.isArray(val.after)){ 79 | after.push(val.after); 80 | }else if(util.isArray(val.after)){ 81 | after = val.after; 82 | } 83 | 84 | if(val.before && !util.isArray(val.before)){ 85 | before.push(val.before); 86 | }else if(util.isArray(val.before)){ 87 | before = val.before; 88 | } 89 | return { 90 | path: val.path, 91 | after: after, 92 | before: before, 93 | atBegin: !!val.atBegin 94 | }; 95 | } 96 | 97 | 98 | function checkBasePath(opt: any): string{ 99 | 100 | if(util.isUndef(opt.basePath)){ 101 | return; 102 | } 103 | 104 | let result: string = ""; 105 | 106 | if(util.isStr(opt.basePath)){ 107 | result = opt.basePath; 108 | } 109 | if(!result){ 110 | return undefined; 111 | } 112 | 113 | result = util.normalizePath(result); 114 | if(result.lastIndexOf("/") !== result.length - 1){ 115 | result = result + "/"; 116 | } 117 | 118 | util.writeWarn("BasePath option has been deprecated. Method for determining an output directory has been changed in the same way as the TSC. " + 119 | "Please re-set output directory with the new rootDir option or use keepDirectoryHierachy option. " + 120 | "However, keepDirectoryHierachy option would not be available long.") 121 | return result; 122 | } 123 | 124 | 125 | function prepareTarget(opt: any): ts.ScriptTarget{ 126 | let result:ts.ScriptTarget = ts.ScriptTarget.ES3; 127 | if (opt.target) { 128 | let temp = (opt.target + "").toLowerCase(); 129 | if (temp === 'es3') { 130 | result = ts.ScriptTarget.ES3; 131 | } else if (temp == 'es5') { 132 | result = ts.ScriptTarget.ES5; 133 | } else if(temp == "es6") { 134 | result = ts.ScriptTarget.ES6; 135 | } 136 | } 137 | return result; 138 | } 139 | 140 | function prepareModule(opt: any): ts.ModuleKind { 141 | let result:ts.ModuleKind = ts.ModuleKind.None; 142 | if (opt.module) { 143 | let temp = (opt.module + "").toLowerCase(); 144 | if (temp === "commonjs" || temp === "node") { 145 | result = ts.ModuleKind.CommonJS; 146 | } else if (temp === "amd") { 147 | result = ts.ModuleKind.AMD; 148 | } else if (temp === "system"){ 149 | result = ts.ModuleKind.System; 150 | } else if (temp === "umd") { 151 | result = ts.ModuleKind.UMD; 152 | } 153 | } 154 | return result; 155 | } 156 | 157 | function prepareNewLine(opt: any): ts.NewLineKind { 158 | let result: ts.NewLineKind = undefined; 159 | if(opt.newLine) { 160 | let temp = (opt.newLine + "").toLowerCase(); 161 | if(temp === "crlf") { 162 | result = ts.NewLineKind.CarriageReturnLineFeed; 163 | }else if(temp === "lf") { 164 | result = ts.NewLineKind.LineFeed; 165 | } 166 | } 167 | return result; 168 | } 169 | 170 | function boolOrUndef(source: any, key: string, def?: boolean): boolean { 171 | let result = util.isUndef(source[key]) ? undefined : !!source[key]; 172 | if(util.isUndef(result) && !util.isUndef(def)){ 173 | result = def; 174 | } 175 | return result; 176 | } 177 | 178 | function prepareGenerateTsConfig(opt: any): boolean | string{ 179 | let result = false; 180 | if(!opt.generateTsConfig){ 181 | return false; 182 | } 183 | if(util.isBool(opt.generateTsConfig)){ 184 | return !!opt.generateTsConfig; 185 | } 186 | if(util.isStr(opt.generateTsConfig)){ 187 | return opt.generateTsConfig + ""; 188 | } 189 | return result; 190 | } 191 | 192 | function prepareJsx(opt: any): ts.JsxEmit { 193 | let jsx = (opt.jsx + "").toLowerCase(); 194 | return jsx === "react" ? ts.JsxEmit.React : 195 | jsx === "preserve" ? ts.JsxEmit.Preserve: undefined; 196 | } 197 | 198 | export function createGruntOption(source: any, grunt: IGrunt, gruntFile: grunt.file.IFilesConfig, logger: gts.Logger): gts.CompilerOptions { 199 | 200 | let dest = util.normalizePath(gruntFile.dest || ""), 201 | singleFile = !!dest && _path.extname(dest) === ".js", 202 | targetVersion = prepareTarget(source), 203 | basePath = checkBasePath(source), 204 | rootDir = util.isStr(source.rootDir) ? source.rootDir : undefined, 205 | keepDirectoryHierarchy = boolOrUndef(source, "keepDirectoryHierarchy"); 206 | 207 | function getTargetFiles(): string[]{ 208 | return grunt.file.expand(gruntFile.orig.src); 209 | } 210 | 211 | 212 | function getReferences(): string[]{ 213 | let target: string[], 214 | binPath = util.getBinDir(); 215 | 216 | if(!source.references){ 217 | return []; 218 | } 219 | if(util.isStr(source.references)){ 220 | target = [source.references]; 221 | } 222 | if(util.isArray(source.references)){ 223 | target = source.references.concat(); 224 | } 225 | if(!target){ 226 | return []; 227 | } 228 | target = target.map((item) => { 229 | if(item === "lib.core.d.ts" || item === "core"){ 230 | return util.combinePaths(binPath, 231 | targetVersion === ts.ScriptTarget.ES6 ? "lib.core.es6.d.ts" : "lib.core.d.ts"); 232 | } 233 | if(item === "lib.dom.d.ts" || item === "dom"){ 234 | return util.combinePaths(binPath, "lib.dom.d.ts"); 235 | } 236 | if(item === "lib.scriptHost.d.ts" || item === "scriptHost"){ 237 | return util.combinePaths(binPath, "lib.scriptHost.d.ts"); 238 | } 239 | if(item === "lib.webworker.d.ts" || item === "webworker"){ 240 | return util.combinePaths(binPath, "lib.webworker.d.ts"); 241 | } 242 | return item; 243 | }); 244 | return grunt.file.expand(target); 245 | } 246 | 247 | if(keepDirectoryHierarchy){ 248 | rootDir = undefined; 249 | }else{ 250 | basePath = undefined; 251 | } 252 | 253 | let result: gts.CompilerOptions = { 254 | targetFiles: getTargetFiles, 255 | dest: dest, 256 | singleFile: singleFile, 257 | basePath: basePath, 258 | keepDirectoryHierarchy: keepDirectoryHierarchy, 259 | watch: prepareWatch(source, getTargetFiles()), 260 | references: getReferences, 261 | generateTsConfig: prepareGenerateTsConfig(source), 262 | tsOptions: { 263 | removeComments: boolOrUndef(source, "removeComments"), 264 | sourceMap: boolOrUndef(source, "sourceMap"), 265 | declaration: boolOrUndef(source, "declaration"), 266 | out: singleFile ? dest : undefined, 267 | outDir: singleFile ? undefined: 268 | keepDirectoryHierarchy ? undefined: dest, 269 | noLib: boolOrUndef(source, "noLib"), 270 | noImplicitAny: boolOrUndef(source, "noImplicitAny"), 271 | noResolve: boolOrUndef(source, "noResolve"), 272 | target: targetVersion, 273 | rootDir: rootDir, 274 | module: prepareModule(source), 275 | preserveConstEnums: boolOrUndef(source, "preserveConstEnums"), 276 | noEmitOnError: boolOrUndef(source, "noEmitOnError", true), 277 | suppressImplicitAnyIndexErrors: boolOrUndef(source, "suppressImplicitAnyIndexErrors"), 278 | experimentalDecorators: boolOrUndef(source, "experimentalDecorators"), 279 | emitDecoratorMetadata: boolOrUndef(source, "emitDecoratorMetadata"), 280 | newLine: prepareNewLine(source), 281 | inlineSourceMap: boolOrUndef(source, "inlineSourceMap"), 282 | inlineSources: boolOrUndef(source, "inlineSources"), 283 | noEmitHelpers: boolOrUndef(source, "noEmitHelpers"), 284 | jsx: prepareJsx(source), 285 | experimentalAsyncFunctions: boolOrUndef(source, "experimentalAsyncFunctions") 286 | } 287 | }; 288 | 289 | logger.verbose("--option"); 290 | logger.verbose(JSON.stringify(result, null, " ")); 291 | 292 | return result; 293 | } 294 | -------------------------------------------------------------------------------- /src/modules/task.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | import * as ts from "typescript"; 4 | import * as option from "./option"; 5 | import * as host from "./host"; 6 | 7 | function prepareStackTrace(error, structuredStackTrace) { 8 | let lines = []; 9 | 10 | for(let trace of structuredStackTrace){ 11 | lines.push(`${trace.getMethodName() || trace.getFunctionName() || ""}[L${trace.getLineNumber()}] `); 12 | } 13 | return lines; 14 | // 15 | // structuredStackTrace[0]; 16 | // console.log(structuredStackTrace); 17 | // 18 | // 19 | // 20 | // return { 21 | // // method name 22 | // name: trace.getMethodName() || trace.getFunctionName() || "", 23 | // // file name 24 | // file: trace.getFileName(), 25 | // // line number 26 | // line: trace.getLineNumber(), 27 | // // column number 28 | // column: trace.getColumnNumber() 29 | // }; 30 | } 31 | 32 | function getTrace(caller?) { 33 | let err = (Error), 34 | original = err.prepareStackTrace, 35 | error = {}; 36 | err.captureStackTrace(error, caller || getTrace); 37 | err.prepareStackTrace = prepareStackTrace; 38 | var stack = error.stack; 39 | err.prepareStackTrace = original; 40 | return stack; 41 | } 42 | 43 | export class Task implements Logger{ 44 | 45 | private _options: CompilerOptions; 46 | private _host: CompilerHost; 47 | private _initTime: number = 0; 48 | 49 | constructor(private _grunt: IGrunt, 50 | private _source: any, 51 | private _gruntFile: grunt.file.IFilesConfig){ 52 | 53 | this._initTime = Date.now(); 54 | } 55 | 56 | getGrunt(): IGrunt{ 57 | return this._grunt; 58 | } 59 | 60 | getOptions(): CompilerOptions{ 61 | if(!this._options){ 62 | this._options = option.createGruntOption(this._source, this._grunt, this._gruntFile, this); 63 | } 64 | return this._options 65 | 66 | } 67 | 68 | getHost(): CompilerHost{ 69 | if(!this._host){ 70 | this._host = host.createHost(this._grunt, this.getOptions(), this); 71 | } 72 | return this._host; 73 | } 74 | 75 | verbose(message: string, stack?: boolean) { 76 | this._grunt.verbose.writeln(`${message} [${Date.now()-this._initTime}ms]`.grey); 77 | if(stack){ 78 | this._grunt.verbose.writeln(getTrace().join("\n").grey); 79 | } 80 | } 81 | 82 | } 83 | 84 | export interface Logger{ 85 | verbose(message: string, stack?: boolean): void; 86 | } 87 | 88 | export interface CompilerHost extends ts.CompilerHost { 89 | writeResult(ms: number): void; 90 | reset(fileNames: string[]): void; 91 | // io: GruntIO; 92 | //debug(value: any, format?: (value: any) => string): void; 93 | } 94 | 95 | export interface SourceFile extends ts.SourceFile{ 96 | mtime: number; 97 | } 98 | 99 | export interface WatchOptions{ 100 | path: string[]; 101 | after: string[]; 102 | before: string[]; 103 | atBegin: boolean; 104 | } 105 | 106 | export interface CompilerOptions { 107 | targetFiles(): string[]; 108 | dest: string; 109 | singleFile: boolean; 110 | basePath: string; 111 | keepDirectoryHierarchy?: boolean; 112 | //ignoreError?: boolean; 113 | watch?: WatchOptions; 114 | references(): string[]; 115 | //_showNearlyTscCommand: boolean; 116 | tsOptions: ts.CompilerOptions; 117 | 118 | generateTsConfig: boolean | string; 119 | } 120 | 121 | export interface Watcher{ 122 | start() : void 123 | } 124 | -------------------------------------------------------------------------------- /src/modules/util.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | let _path: NodeJS.Path = require("path"), 4 | _fs: NodeJS.FileSystem = require("fs"), 5 | _os: NodeJS.OS = require("os"); 6 | 7 | /** 8 | * string 型かどうか 9 | */ 10 | export function isStr(val: any): boolean{ 11 | return Object.prototype.toString.call(val) === "[object String]"; 12 | } 13 | /** 14 | * boolean 型かどうか 15 | */ 16 | export function isBool(val: any): boolean{ 17 | return Object.prototype.toString.call(val) === "[object Boolean]"; 18 | } 19 | /** 20 | * 配列かどうか 21 | */ 22 | export function isArray(val: any): boolean{ 23 | return Object.prototype.toString.call(val) === "[object Array]"; 24 | } 25 | /** 26 | * undefined かどうか 27 | */ 28 | export function isUndef(val: any): boolean{ 29 | return typeof val === "undefined"; 30 | } 31 | /** 32 | * bin ディレクトリのパス 33 | */ 34 | export function getBinDir(): string{ 35 | return _path.dirname(require.resolve("typescript")); 36 | } 37 | 38 | //ts 39 | 40 | var hasOwnProperty = Object.prototype.hasOwnProperty; 41 | 42 | export function hasProperty(value: any, key: string): boolean { 43 | return hasOwnProperty.call(value, key); 44 | } 45 | 46 | const colonCode = 0x3A; 47 | const slashCode = 0x2F; 48 | 49 | export function getRootLength(path: string): number { 50 | if (path.charCodeAt(0) === slashCode) { 51 | if (path.charCodeAt(1) !== slashCode) return 1; 52 | let p1 = path.indexOf("/", 2); 53 | if (p1 < 0) return 2; 54 | let p2 = path.indexOf("/", p1 + 1); 55 | if (p2 < 0) return p1 + 1; 56 | return p2 + 1; 57 | } 58 | if (path.charCodeAt(1) === colonCode) { 59 | if (path.charCodeAt(2) === slashCode) return 3; 60 | return 2; 61 | } 62 | let idx = path.indexOf("://"); 63 | if(idx !== -1) return idx + 3; 64 | 65 | return 0; 66 | } 67 | 68 | /** 69 | * パスの区切り文字を静音化(バックスラッシュをスラッシュに) 70 | */ 71 | export function normalizeSlashes(path: string): string { 72 | return path.replace(/\\/g, "/"); 73 | } 74 | 75 | const directorySeparator = "/"; 76 | function getNormalizedParts(normalizedSlashedPath: string, rootLength: number) { 77 | let parts = normalizedSlashedPath.substr(rootLength).split(directorySeparator); 78 | let normalized: string[] = []; 79 | for (let part of parts) { 80 | if (part !== ".") { 81 | if (part === ".." && normalized.length > 0 && normalized[normalized.length - 1] !== "..") { 82 | normalized.pop(); 83 | } 84 | else { 85 | if(part){ 86 | normalized.push(part); 87 | } 88 | } 89 | } 90 | } 91 | return normalized; 92 | } 93 | 94 | export function normalizePath(path: string): string { 95 | let spath = normalizeSlashes(path); 96 | let rootLength = getRootLength(spath); 97 | let normalized = getNormalizedParts(spath, rootLength); 98 | return spath.substr(0, rootLength) + normalized.join(directorySeparator); 99 | } 100 | 101 | export function combinePaths(path1: string, path2: string) { 102 | if (!(path1 && path1.length)) return path2; 103 | if (!(path2 && path2.length)) return path1; 104 | //if (path2.charAt(0) === directorySeparator) return path2; 105 | if (getRootLength(path2) !== 0) return path2; 106 | if (path1.charAt(path1.length - 1) === directorySeparator) return path1 + path2; 107 | return path1 + directorySeparator + path2; 108 | } 109 | 110 | export function getDirectoryPath(path: string) { 111 | return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(directorySeparator))); 112 | } 113 | 114 | 115 | export function readFile(fileName: string, encoding?: string): string { 116 | if (!_fs.existsSync(fileName)) { 117 | return undefined; 118 | } 119 | var buffer = _fs.readFileSync(fileName); 120 | var len = buffer.length; 121 | if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) { 122 | // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js, 123 | // flip all byte pairs and treat as little endian. 124 | len &= ~1; 125 | for (var i = 0; i < len; i += 2) { 126 | var temp = buffer[i]; 127 | buffer[i] = buffer[i + 1]; 128 | buffer[i + 1] = temp; 129 | } 130 | return buffer.toString("utf16le", 2); 131 | } 132 | if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) { 133 | // Little endian UTF-16 byte order mark detected 134 | return buffer.toString("utf16le", 2); 135 | } 136 | if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { 137 | // UTF-8 byte order mark detected 138 | return buffer.toString("utf8", 3); 139 | } 140 | // Default is UTF-8 with no byte order mark 141 | return buffer.toString("utf8"); 142 | } 143 | 144 | export function writeFile(fileName: string, data: string, writeByteOrderMark?: boolean): void { 145 | // If a BOM is required, emit one 146 | if (writeByteOrderMark) { 147 | data = '\uFEFF' + data; 148 | } 149 | 150 | _fs.writeFileSync(fileName, data, "utf8"); 151 | } 152 | 153 | export function abs(fileName: string): string{ 154 | return normalizePath(_path.resolve(".", normalizePath(fileName))); 155 | } 156 | 157 | export function fileExists(path: string): boolean{ 158 | return _fs.existsSync(path); 159 | } 160 | 161 | export function directoryExists(path:string):boolean { 162 | return _fs.existsSync(path) && _fs.statSync(path).isDirectory(); 163 | } 164 | 165 | export function dirOrFileExists(path:string):boolean { 166 | return _fs.existsSync(path); 167 | } 168 | 169 | 170 | export function createDirectory(directoryName:string):void { 171 | if (!directoryExists(directoryName)) { 172 | _fs.mkdirSync(directoryName); 173 | } 174 | } 175 | 176 | 177 | export function createDirectoryRecurse(directoryName: string) { 178 | if (directoryName.length > getRootLength(directoryName) && !directoryExists(directoryName)) { 179 | let parentDirectory = getDirectoryPath(directoryName); 180 | createDirectoryRecurse(parentDirectory); 181 | //TODO: 182 | createDirectory(directoryName); 183 | } 184 | } 185 | 186 | export function getCurrentDirectory(): string { 187 | return normalizePath(_path.resolve(".")) 188 | } 189 | 190 | export function relativePath(from: string, to: string): string{ 191 | return _path.relative(from, to); 192 | } 193 | 194 | export function write(str: string): void{ 195 | console.log(str); 196 | } 197 | 198 | export function writeAbort(str: string): void{ 199 | console.log((str || "").red); 200 | } 201 | 202 | export function writeError(str: string): void{ 203 | console.log(">> ".red + str.trim().replace(/\r/g, '').replace(/\n/g, "\n>> ".red)); 204 | } 205 | 206 | export function writeInfo(str: string): void{ 207 | console.log(">> ".cyan + str.trim().replace(/\r/g, '').replace(/\n/g, "\n>> ".cyan)); 208 | } 209 | 210 | export function writeWarn(str: string): void{ 211 | console.log(">> ".yellow + str.trim().replace(/\r/g, '').replace(/\n/g, "\n>> ".yellow)); 212 | } 213 | -------------------------------------------------------------------------------- /src/modules/watcher.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | import * as gts from "./task"; 4 | import * as util from "./util"; 5 | 6 | let _path: NodeJS.Path = require("path"), 7 | _fs: NodeJS.FileSystem = require("fs"); 8 | 9 | export function createWatcher(watchPaths: string[], callback: (targets: {[key: string]: {mtime: number; ev: string}}, done: () => void) => void): gts.Watcher{ 10 | 11 | let chokidar: any = require("chokidar"), 12 | watcher: any, 13 | timeoutId: NodeJS.Timer, 14 | callbacking = false, 15 | events: {[key: string]: {mtime: number; ev: string}} = {}; 16 | 17 | function start() : void{ 18 | if(watcher){ 19 | return; 20 | } 21 | 22 | watcher = chokidar.watch(watchPaths, { ignoreInitial: true, persistent: true, ignorePermissionErrors: true}); 23 | watcher.on("add", (path: string, stats: any) => { 24 | add(path, "add", stats); 25 | }).on("change", (path: string, stats: any) => { 26 | add(path, "change", stats); 27 | }).on("unlink", (path: string, stats: any) =>{ 28 | add(path, "unlink", stats); 29 | }).on("error", (error: string) => { 30 | util.writeError(error); 31 | }); 32 | } 33 | 34 | function add(path: string, eventName: string, stats: any){ 35 | if(_path.extname(path) !== ".ts" || _path.extname(path) !== ".tsx"){ 36 | return; 37 | } 38 | path = util.normalizePath(path); 39 | 40 | if(stats && stats.mtime){ 41 | events[path] = { 42 | mtime: stats.mtime.getTime(), 43 | ev: eventName 44 | }; 45 | }else{ 46 | events[path] = { 47 | mtime: eventName === "unlink" ? 0 : _fs.statSync(path).mtime.getTime(), 48 | ev: eventName 49 | }; 50 | } 51 | 52 | util.write(eventName.cyan + " " + path); 53 | 54 | executeCallback(); 55 | } 56 | 57 | function clone(value: {[key: string]: {mtime: number; ev: string}}): {[key: string]: {mtime: number; ev: string}}{ 58 | let result: {[key: string]: {mtime: number; ev: string}} = {}; 59 | Object.keys(value).forEach((item) => { 60 | result[item] = value[item]; 61 | }); 62 | return result; 63 | } 64 | 65 | function executeCallback(){ 66 | if(!Object.keys(events).length){ 67 | return; 68 | } 69 | if(callbacking){ 70 | return; 71 | } 72 | if(timeoutId){ 73 | clearTimeout(timeoutId); 74 | } 75 | 76 | timeoutId = setTimeout(function(){ 77 | callbacking = true; 78 | let value = clone(events); 79 | events = {}; 80 | 81 | try{ 82 | callback(value, function(){ 83 | callbacking = false; 84 | executeCallback(); 85 | }); 86 | }catch(e){ 87 | callbacking = false; 88 | } 89 | }, 1000); 90 | 91 | } 92 | 93 | return { 94 | start: start 95 | }; 96 | } -------------------------------------------------------------------------------- /tasks/index.js: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | /// 4 | /// 5 | var gts = require("./modules/task"); 6 | var Promise = require("bluebird"); 7 | var compiler = require("./modules/compiler"); 8 | function startup(grunt) { 9 | grunt.registerMultiTask("typescript", "Compile typescript to javascript.", function () { 10 | var that = this, done = that.async(), promises = that.files.map(function (gruntFile) { 11 | var task = new gts.Task(grunt, that.options({}), gruntFile); 12 | return compiler.execute(task); 13 | }); 14 | Promise.all(promises).then(function () { 15 | done(); 16 | }).catch(function () { 17 | done(false); 18 | }); 19 | }); 20 | } 21 | module.exports = startup; 22 | -------------------------------------------------------------------------------- /tasks/modules/compiler.js: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | /// 4 | /// 5 | /// 6 | /// 7 | /// 8 | var ts = require("typescript"); 9 | var util = require("./util"); 10 | var watche = require("./watcher"); 11 | var Promise = require("bluebird"); 12 | var _os = require("os"); 13 | function execute(task) { 14 | var host = task.getHost(), options = task.getOptions(), promise = new Promise(function (resolve, reject) { 15 | if (options.watch) { 16 | watch(task); 17 | } 18 | else { 19 | try { 20 | if (compile(task)) { 21 | resolve(undefined); 22 | } 23 | else { 24 | reject(false); 25 | } 26 | } 27 | catch (e) { 28 | reject(false); 29 | } 30 | } 31 | }); 32 | return promise; 33 | } 34 | exports.execute = execute; 35 | function watch(task) { 36 | var options = task.getOptions(), watchOpt = options.watch, watchPath = watchOpt.path, targetPaths = {}, startCompile = function (files) { 37 | return runTask(task, watchOpt.before).then(function () { 38 | if (!recompile(task, files)) { 39 | //失敗だった場合はリセット 40 | task.getHost().reset(files); 41 | } 42 | return runTask(task, watchOpt.after); 43 | }).then(function () { 44 | writeWatching(watchPath); 45 | }); 46 | }, watcher = watche.createWatcher(watchPath, function (files, done) { 47 | startCompile(Object.keys(files)).finally(function () { 48 | done(); 49 | }); 50 | }); 51 | if (watchOpt.atBegin) { 52 | startCompile().finally(function () { 53 | watcher.start(); 54 | }); 55 | } 56 | else { 57 | watcher.start(); 58 | } 59 | } 60 | function writeWatching(watchPath) { 61 | util.write(""); 62 | util.write("Watching... " + watchPath); 63 | } 64 | function recompile(task, updateFiles) { 65 | if (updateFiles === void 0) { updateFiles = []; } 66 | task.verbose("--task.recompile"); 67 | task.getHost().reset(updateFiles); 68 | return compile(task); 69 | } 70 | function runTask(task, tasks) { 71 | var grunt = task.getGrunt(); 72 | task.verbose("--task.runTask"); 73 | return asyncEach(tasks, function (taskName, index, next) { 74 | task.verbose(" external task start: " + taskName); 75 | var flags = grunt.option.flags().map(function (f) { return !!f ? f + "" : ""; }); 76 | grunt.util.spawn({ 77 | cmd: undefined, 78 | grunt: true, 79 | args: [taskName].concat(flags), 80 | opts: { stdio: 'inherit' } 81 | }, function (err, result, code) { 82 | task.verbose("external task end: " + task); 83 | next(); 84 | }); 85 | }); 86 | } 87 | function asyncEach(items, callback) { 88 | return new Promise(function (resolve, reject) { 89 | var length = items.length, exec = function (i) { 90 | if (length <= i) { 91 | resolve(undefined); 92 | return; 93 | } 94 | var item = items[i]; 95 | callback(item, i, function () { 96 | i = i + 1; 97 | exec(i); 98 | }); 99 | }; 100 | exec(0); 101 | }); 102 | } 103 | function compile(task) { 104 | var start = Date.now(), options = task.getOptions(), host = task.getHost(), targetFiles = getTargetFiles(options); 105 | task.verbose("- write tsconfig.json"); 106 | writeTsConfig(options, targetFiles, task); 107 | task.verbose("- create program"); 108 | var program = ts.createProgram(targetFiles, options.tsOptions, host); 109 | var diagnostics = program.getSyntacticDiagnostics(); 110 | reportDiagnostics(diagnostics); 111 | if (diagnostics.length) { 112 | return false; 113 | } 114 | if (diagnostics.length === 0) { 115 | diagnostics = program.getGlobalDiagnostics(); 116 | reportDiagnostics(diagnostics); 117 | if (diagnostics.length === 0) { 118 | diagnostics = program.getSemanticDiagnostics(); 119 | reportDiagnostics(diagnostics); 120 | } 121 | } 122 | if (diagnostics.length) { 123 | return false; 124 | } 125 | if (options.tsOptions.noEmit) { 126 | host.writeResult(Date.now() - start); 127 | return true; 128 | } 129 | task.verbose("- emit"); 130 | var emitOutput = program.emit(); 131 | reportDiagnostics(emitOutput.diagnostics); 132 | if (emitOutput.diagnostics.length) { 133 | return false; 134 | } 135 | if (emitOutput.emitSkipped) { 136 | task.verbose(" emit skipped"); 137 | } 138 | host.writeResult(Date.now() - start); 139 | return true; 140 | } 141 | function getTargetFiles(options) { 142 | var codeFiles = options.targetFiles(), libFiles = options.references(); 143 | return libFiles.concat(codeFiles); 144 | } 145 | function reportDiagnostic(diagnostic, isWarn) { 146 | if (isWarn === void 0) { isWarn = false; } 147 | var output = "", newLine = _os.EOL; 148 | if (diagnostic.file) { 149 | var loc = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); 150 | output += diagnostic.file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + "): "; 151 | } 152 | var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); 153 | output += category + " TS" + diagnostic.code + ": " + ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine) + newLine; 154 | if (isWarn) { 155 | util.writeWarn(output); 156 | } 157 | else { 158 | util.writeError(output); 159 | } 160 | } 161 | function reportDiagnostics(diagnostics, isWarn) { 162 | if (isWarn === void 0) { isWarn = false; } 163 | for (var _i = 0; _i < diagnostics.length; _i++) { 164 | var d = diagnostics[_i]; 165 | reportDiagnostic(d, isWarn); 166 | } 167 | } 168 | function writeTsConfig(options, targetFiles, logger) { 169 | if (!options.generateTsConfig) { 170 | return; 171 | } 172 | var outputDir = util.getCurrentDirectory(); 173 | if (typeof options.generateTsConfig === "string") { 174 | outputDir = util.abs(options.generateTsConfig.toString()); 175 | } 176 | var outputFile = util.combinePaths(outputDir, "tsconfig.json"); 177 | logger.verbose(" dir: " + outputDir + ", file: " + outputFile); 178 | var tsOpts = options.tsOptions; 179 | var config = { 180 | compilerOptions: { 181 | removeComments: tsOpts.removeComments, 182 | sourceMap: tsOpts.sourceMap, 183 | declaration: tsOpts.declaration, 184 | out: tsOpts.out, 185 | outDir: tsOpts.outDir, 186 | noLib: tsOpts.noLib, 187 | noImplicitAny: tsOpts.noImplicitAny, 188 | noResolve: tsOpts.noResolve, 189 | target: tsOpts.target === 0 /* ES3 */ ? "es3" : 190 | tsOpts.target === 1 /* ES5 */ ? "es5" : 191 | tsOpts.target === 2 /* ES6 */ ? "es6" : undefined, 192 | rootDir: tsOpts.rootDir, 193 | module: tsOpts.module === 2 /* AMD */ ? "amd" : 194 | tsOpts.module === 1 /* CommonJS */ ? "commonjs" : 195 | tsOpts.module === 4 /* System */ ? "system" : 196 | tsOpts.module === 3 /* UMD */ ? "umd" : undefined, 197 | preserveConstEnums: tsOpts.preserveConstEnums, 198 | noEmitOnError: tsOpts.noEmitOnError, 199 | suppressImplicitAnyIndexErrors: tsOpts.suppressImplicitAnyIndexErrors, 200 | emitDecoratorMetadata: tsOpts.emitDecoratorMetadata, 201 | newLine: tsOpts.newLine === 0 /* CarriageReturnLineFeed */ ? "crlf" : 202 | tsOpts.newLine === 1 /* LineFeed */ ? "lf" : undefined, 203 | inlineSourceMap: tsOpts.inlineSourceMap, 204 | inlineSources: tsOpts.inlineSources, 205 | noEmitHelper: tsOpts.noEmitHelpers 206 | }, 207 | files: targetFiles.map(function (targetFile) { return util.normalizePath(util.relativePath(outputDir, targetFile)); }) 208 | }; 209 | util.createDirectoryRecurse(outputDir); 210 | util.writeFile(outputFile, JSON.stringify(config, null, " ")); 211 | util.writeInfo("tsconfig.json generated: " + outputFile); 212 | } 213 | -------------------------------------------------------------------------------- /tasks/modules/host.js: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | /// 4 | /// 5 | /// 6 | /// 7 | var ts = require("typescript"); 8 | var util = require("./util"); 9 | var _path = require("path"), _fs = require("fs"), _os = require("os"), existingDirectories = {}; 10 | function createSourceFile(fileName, text, languageVersion) { 11 | if (text !== undefined) { 12 | var result = ts.createSourceFile(fileName, text, languageVersion); 13 | result.mtime = _fs.statSync(fileName).mtime.getTime(); 14 | return result; 15 | } 16 | } 17 | function directoryExists(directoryPath) { 18 | if (util.hasProperty(existingDirectories, directoryPath)) { 19 | return true; 20 | } 21 | //TODO: 22 | if (util.directoryExists(directoryPath)) { 23 | existingDirectories[directoryPath] = true; 24 | return true; 25 | } 26 | return false; 27 | } 28 | function ensureDirectoriesExist(directoryPath) { 29 | if (directoryPath.length > util.getRootLength(directoryPath) && !directoryExists(directoryPath)) { 30 | var parentDirectory = util.getDirectoryPath(directoryPath); 31 | ensureDirectoriesExist(parentDirectory); 32 | //TODO: 33 | util.createDirectory(directoryPath); 34 | } 35 | } 36 | function prepareOutputDir(fileName, options) { 37 | if (options.singleFile || !options.dest) { 38 | return fileName; 39 | } 40 | var currentPath = util.getCurrentDirectory(), relativePath = util.normalizePath(_path.relative(currentPath, fileName)), basePath = options.basePath; 41 | if (basePath) { 42 | if (relativePath.substr(0, basePath.length) !== basePath) { 43 | throw new Error(fileName + " is not started basePath"); 44 | } 45 | relativePath = relativePath.substr(basePath.length); 46 | } 47 | return util.normalizePath(_path.resolve(currentPath, options.dest, relativePath)); 48 | } 49 | function prepareSourcePath(sourceFileName, preparedFileName, contents, options) { 50 | if (options.singleFile || !options.dest) { 51 | return contents; 52 | } 53 | if (sourceFileName === preparedFileName) { 54 | return contents; 55 | } 56 | if (!(/\.js\.map$/.test(sourceFileName))) { 57 | return contents; 58 | } 59 | var mapData = JSON.parse(contents), source = mapData.sources[0]; 60 | mapData.sources.length = 0; 61 | var relative = _path.relative(_path.dirname(preparedFileName), sourceFileName); 62 | mapData.sources.push(util.normalizePath(_path.join(_path.dirname(relative), source))); 63 | return JSON.stringify(mapData); 64 | } 65 | function getNewLineChar(options) { 66 | var optValue = options.tsOptions.newLine; 67 | if (optValue === 0 /* CarriageReturnLineFeed */) { 68 | return "\r\n"; 69 | } 70 | else if (optValue === 1 /* LineFeed */) { 71 | return "\n"; 72 | } 73 | return _os.EOL; 74 | } 75 | function createHost(grunt, options, logger) { 76 | var platform = _os.platform(), 77 | // win32\win64 are case insensitive platforms, MacOS (darwin) by default is also case insensitive 78 | useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin", sourceFileCache = {}, newSourceFiles = [], outputFiles = []; 79 | function getCanonicalFileName(fileName) { 80 | // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. 81 | // otherwise use toLowerCase as a canonical form. 82 | return useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); 83 | } 84 | function getSourceFile(fileName, languageVersion, onError) { 85 | logger.verbose("--host.getSourceFile: " + fileName); 86 | var fullName = util.abs(fileName), text = ""; 87 | if (fullName in sourceFileCache) { 88 | var chechedSourceFile = sourceFileCache[fullName], newMtime = _fs.statSync(fullName).mtime.getTime(); 89 | if (chechedSourceFile.mtime !== newMtime) { 90 | delete sourceFileCache[fullName]; 91 | } 92 | else { 93 | logger.verbose(" cached"); 94 | return sourceFileCache[fullName]; 95 | } 96 | } 97 | if (!util.dirOrFileExists(fileName)) { 98 | return; 99 | } 100 | try { 101 | text = util.readFile(fileName, options.tsOptions.charset); 102 | } 103 | catch (e) { 104 | if (onError) { 105 | onError(e.message); 106 | } 107 | text = ""; 108 | } 109 | var result = createSourceFile(fileName, text, languageVersion); 110 | if (result) { 111 | logger.verbose(" readed"); 112 | sourceFileCache[fullName] = result; 113 | } 114 | return result; 115 | } 116 | function writeFile(fileName, data, writeByteOrderMark, onError) { 117 | logger.verbose("--host.writeFile: " + fileName); 118 | var fullName = util.abs(fileName); 119 | // if(!options.singleFile && options.watch && !options.tsOptions.noEmit && newSourceFiles.length){ 120 | // return; 121 | // } 122 | //watch の時に新しいファイルだけ出力をしたいが、判定できないためコメントアウト 123 | // if(!options.singleFile){ 124 | // let tsFile = fullName.replace(/\.js\.map$/, ".ts").replace(/\.js$/, ".ts"); 125 | // if(!(tsFile in newSourceFiles)){ 126 | // tsFile = fullName.replace(/\.d\.ts$/, ".ts"); 127 | // if(!(tsFile in newSourceFiles)) { 128 | // logger.verbose(" canceled"); 129 | // return; 130 | // } 131 | // } 132 | // } 133 | //出力先ディレクトリのパスに変換 134 | if (!!options.keepDirectoryHierarchy) { 135 | try { 136 | var newFileName = prepareOutputDir(fileName, options); 137 | //map ファイルの参照先パスを変換 138 | var targetData = prepareSourcePath(fileName, newFileName, data, options); 139 | logger.verbose(" change file path: " + fileName + " -> " + newFileName); 140 | fileName = newFileName; 141 | data = targetData; 142 | fullName = util.abs(fileName); 143 | } 144 | catch (e) { 145 | console.log(e); 146 | } 147 | } 148 | try { 149 | ensureDirectoriesExist(util.getDirectoryPath(util.normalizePath(fullName))); 150 | //TODO: 151 | util.writeFile(fullName, data, writeByteOrderMark); 152 | outputFiles.push(fullName); 153 | logger.verbose(" write file: " + fullName); 154 | } 155 | catch (e) { 156 | if (onError) 157 | onError(e.message); 158 | } 159 | } 160 | function writeResult(ms) { 161 | var result = { js: [], m: [], d: [], other: [] }, resultMessage, pluralizeFile = function (n) { return (n + " file") + ((n === 1) ? "" : "s"); }; 162 | outputFiles.forEach(function (item) { 163 | if (/\.js$/.test(item)) 164 | result.js.push(item); 165 | else if (/\.js\.map$/.test(item)) 166 | result.m.push(item); 167 | else if (/\.d\.ts$/.test(item)) 168 | result.d.push(item); 169 | else 170 | result.other.push(item); 171 | }); 172 | resultMessage = "js: " + pluralizeFile(result.js.length) 173 | + ", map: " + pluralizeFile(result.m.length) 174 | + ", declaration: " + pluralizeFile(result.d.length) 175 | + " (" + ms + "ms)"; 176 | if (options.singleFile) { 177 | if (result.js.length > 0) { 178 | util.write("File " + (result.js[0])["cyan"] + " created."); 179 | } 180 | util.write(resultMessage); 181 | } 182 | else { 183 | util.write(pluralizeFile(outputFiles.length)["cyan"] + " created. " + resultMessage); 184 | } 185 | } 186 | function reset(fileNames) { 187 | if (util.isUndef(fileNames)) { 188 | sourceFileCache = {}; 189 | } 190 | if (util.isArray(fileNames)) { 191 | fileNames.forEach(function (f) { 192 | var fullName = util.abs(f); 193 | if (fullName in sourceFileCache) { 194 | delete sourceFileCache[fullName]; 195 | } 196 | }); 197 | } 198 | outputFiles.length = 0; 199 | newSourceFiles = []; 200 | } 201 | var newLineChar = getNewLineChar(options); 202 | return { 203 | getSourceFile: getSourceFile, 204 | getDefaultLibFileName: function (options) { 205 | logger.verbose("bin dir = " + util.getBinDir()); 206 | return util.combinePaths(util.getBinDir(), options.target === 2 /* ES6 */ ? "lib.es6.d.ts" : "lib.d.ts"); 207 | }, 208 | writeFile: writeFile, 209 | getCurrentDirectory: function () { return util.getCurrentDirectory(); }, 210 | useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, 211 | getCanonicalFileName: getCanonicalFileName, 212 | getNewLine: function () { return newLineChar; }, 213 | fileExists: function (path) { return util.fileExists(path); }, 214 | readFile: function (fileName) { return util.readFile(fileName); }, 215 | writeResult: writeResult, 216 | reset: reset 217 | }; 218 | } 219 | exports.createHost = createHost; 220 | -------------------------------------------------------------------------------- /tasks/modules/option.js: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | var util = require("./util"); 4 | var ts = require("typescript"); 5 | var _path = require("path"), _fs = require("fs"); 6 | function prepareWatch(opt, files) { 7 | var after = [], before = [], val = opt.watch, getDirNames = function (files) { 8 | return files.map(function (file) { 9 | if (_fs.existsSync(file)) { 10 | if (_fs.statSync(file).isDirectory()) { 11 | return file; 12 | } 13 | } 14 | else { 15 | if (!_path.extname(file)) { 16 | return file; 17 | } 18 | } 19 | return util.normalizePath(_path.resolve(_path.dirname(file))); 20 | }); 21 | }, extractPath = function (files) { 22 | var dirNames = getDirNames(files), result = dirNames.reduce(function (prev, curr) { 23 | if (!prev) { 24 | return curr; 25 | } 26 | var left = util.normalizePath(_path.relative(prev, curr)), right = util.normalizePath(_path.relative(curr, prev)), match = left.match(/^(\.\.(\/)?)+/); 27 | if (match) { 28 | return util.normalizePath(_path.resolve(prev, match[0])); 29 | } 30 | match = right.match(/^(\.\.(\/)?)+/); 31 | if (match) { 32 | return util.normalizePath(_path.resolve(curr, match[0])); 33 | } 34 | return prev; 35 | }, undefined); 36 | if (result) { 37 | return [result]; 38 | } 39 | }; 40 | if (!val) { 41 | return undefined; 42 | } 43 | if (util.isStr(val) || util.isArray(val)) { 44 | return { 45 | path: util.isStr(val) ? [val] : val, 46 | after: [], 47 | before: [], 48 | atBegin: false 49 | }; 50 | } 51 | if (util.isBool(val) && !!val) { 52 | return { 53 | path: extractPath(files), 54 | after: [], 55 | before: [], 56 | atBegin: false 57 | }; 58 | } 59 | if (!val.path) { 60 | val.path = extractPath(files); 61 | if (!val.path) { 62 | //util.writeWarn("Can't auto detect watch directory. Please place one or more files or set the path option."); 63 | return undefined; 64 | } 65 | } 66 | if (val.after && !util.isArray(val.after)) { 67 | after.push(val.after); 68 | } 69 | else if (util.isArray(val.after)) { 70 | after = val.after; 71 | } 72 | if (val.before && !util.isArray(val.before)) { 73 | before.push(val.before); 74 | } 75 | else if (util.isArray(val.before)) { 76 | before = val.before; 77 | } 78 | return { 79 | path: val.path, 80 | after: after, 81 | before: before, 82 | atBegin: !!val.atBegin 83 | }; 84 | } 85 | function checkBasePath(opt) { 86 | if (util.isUndef(opt.basePath)) { 87 | return; 88 | } 89 | var result = ""; 90 | if (util.isStr(opt.basePath)) { 91 | result = opt.basePath; 92 | } 93 | if (!result) { 94 | return undefined; 95 | } 96 | result = util.normalizePath(result); 97 | if (result.lastIndexOf("/") !== result.length - 1) { 98 | result = result + "/"; 99 | } 100 | util.writeWarn("BasePath option has been deprecated. Method for determining an output directory has been changed in the same way as the TSC. " + 101 | "Please re-set output directory with the new rootDir option or use keepDirectoryHierachy option. " + 102 | "However, keepDirectoryHierachy option would not be available long."); 103 | return result; 104 | } 105 | function prepareTarget(opt) { 106 | var result = 0 /* ES3 */; 107 | if (opt.target) { 108 | var temp = (opt.target + "").toLowerCase(); 109 | if (temp === 'es3') { 110 | result = 0 /* ES3 */; 111 | } 112 | else if (temp == 'es5') { 113 | result = 1 /* ES5 */; 114 | } 115 | else if (temp == "es6") { 116 | result = 2 /* ES6 */; 117 | } 118 | } 119 | return result; 120 | } 121 | function prepareModule(opt) { 122 | var result = 0 /* None */; 123 | if (opt.module) { 124 | var temp = (opt.module + "").toLowerCase(); 125 | if (temp === "commonjs" || temp === "node") { 126 | result = 1 /* CommonJS */; 127 | } 128 | else if (temp === "amd") { 129 | result = 2 /* AMD */; 130 | } 131 | else if (temp === "system") { 132 | result = 4 /* System */; 133 | } 134 | else if (temp === "umd") { 135 | result = 3 /* UMD */; 136 | } 137 | } 138 | return result; 139 | } 140 | function prepareNewLine(opt) { 141 | var result = undefined; 142 | if (opt.newLine) { 143 | var temp = (opt.newLine + "").toLowerCase(); 144 | if (temp === "crlf") { 145 | result = 0 /* CarriageReturnLineFeed */; 146 | } 147 | else if (temp === "lf") { 148 | result = 1 /* LineFeed */; 149 | } 150 | } 151 | return result; 152 | } 153 | function boolOrUndef(source, key, def) { 154 | var result = util.isUndef(source[key]) ? undefined : !!source[key]; 155 | if (util.isUndef(result) && !util.isUndef(def)) { 156 | result = def; 157 | } 158 | return result; 159 | } 160 | function prepareGenerateTsConfig(opt) { 161 | var result = false; 162 | if (!opt.generateTsConfig) { 163 | return false; 164 | } 165 | if (util.isBool(opt.generateTsConfig)) { 166 | return !!opt.generateTsConfig; 167 | } 168 | if (util.isStr(opt.generateTsConfig)) { 169 | return opt.generateTsConfig + ""; 170 | } 171 | return result; 172 | } 173 | function prepareJsx(opt) { 174 | var jsx = (opt.jsx + "").toLowerCase(); 175 | return jsx === "react" ? 2 /* React */ : 176 | jsx === "preserve" ? 1 /* Preserve */ : undefined; 177 | } 178 | function createGruntOption(source, grunt, gruntFile, logger) { 179 | var dest = util.normalizePath(gruntFile.dest || ""), singleFile = !!dest && _path.extname(dest) === ".js", targetVersion = prepareTarget(source), basePath = checkBasePath(source), rootDir = util.isStr(source.rootDir) ? source.rootDir : undefined, keepDirectoryHierarchy = boolOrUndef(source, "keepDirectoryHierarchy"); 180 | function getTargetFiles() { 181 | return grunt.file.expand(gruntFile.orig.src); 182 | } 183 | function getReferences() { 184 | var target, binPath = util.getBinDir(); 185 | if (!source.references) { 186 | return []; 187 | } 188 | if (util.isStr(source.references)) { 189 | target = [source.references]; 190 | } 191 | if (util.isArray(source.references)) { 192 | target = source.references.concat(); 193 | } 194 | if (!target) { 195 | return []; 196 | } 197 | target = target.map(function (item) { 198 | if (item === "lib.core.d.ts" || item === "core") { 199 | return util.combinePaths(binPath, targetVersion === 2 /* ES6 */ ? "lib.core.es6.d.ts" : "lib.core.d.ts"); 200 | } 201 | if (item === "lib.dom.d.ts" || item === "dom") { 202 | return util.combinePaths(binPath, "lib.dom.d.ts"); 203 | } 204 | if (item === "lib.scriptHost.d.ts" || item === "scriptHost") { 205 | return util.combinePaths(binPath, "lib.scriptHost.d.ts"); 206 | } 207 | if (item === "lib.webworker.d.ts" || item === "webworker") { 208 | return util.combinePaths(binPath, "lib.webworker.d.ts"); 209 | } 210 | return item; 211 | }); 212 | return grunt.file.expand(target); 213 | } 214 | if (keepDirectoryHierarchy) { 215 | rootDir = undefined; 216 | } 217 | else { 218 | basePath = undefined; 219 | } 220 | var result = { 221 | targetFiles: getTargetFiles, 222 | dest: dest, 223 | singleFile: singleFile, 224 | basePath: basePath, 225 | keepDirectoryHierarchy: keepDirectoryHierarchy, 226 | watch: prepareWatch(source, getTargetFiles()), 227 | references: getReferences, 228 | generateTsConfig: prepareGenerateTsConfig(source), 229 | tsOptions: { 230 | removeComments: boolOrUndef(source, "removeComments"), 231 | sourceMap: boolOrUndef(source, "sourceMap"), 232 | declaration: boolOrUndef(source, "declaration"), 233 | out: singleFile ? dest : undefined, 234 | outDir: singleFile ? undefined : 235 | keepDirectoryHierarchy ? undefined : dest, 236 | noLib: boolOrUndef(source, "noLib"), 237 | noImplicitAny: boolOrUndef(source, "noImplicitAny"), 238 | noResolve: boolOrUndef(source, "noResolve"), 239 | target: targetVersion, 240 | rootDir: rootDir, 241 | module: prepareModule(source), 242 | preserveConstEnums: boolOrUndef(source, "preserveConstEnums"), 243 | noEmitOnError: boolOrUndef(source, "noEmitOnError", true), 244 | suppressImplicitAnyIndexErrors: boolOrUndef(source, "suppressImplicitAnyIndexErrors"), 245 | experimentalDecorators: boolOrUndef(source, "experimentalDecorators"), 246 | emitDecoratorMetadata: boolOrUndef(source, "emitDecoratorMetadata"), 247 | newLine: prepareNewLine(source), 248 | inlineSourceMap: boolOrUndef(source, "inlineSourceMap"), 249 | inlineSources: boolOrUndef(source, "inlineSources"), 250 | noEmitHelpers: boolOrUndef(source, "noEmitHelpers"), 251 | jsx: prepareJsx(source) 252 | } 253 | }; 254 | logger.verbose("--option"); 255 | logger.verbose(JSON.stringify(result, null, " ")); 256 | return result; 257 | } 258 | exports.createGruntOption = createGruntOption; 259 | -------------------------------------------------------------------------------- /tasks/modules/task.js: -------------------------------------------------------------------------------- 1 | var option = require("./option"); 2 | var host = require("./host"); 3 | function prepareStackTrace(error, structuredStackTrace) { 4 | var lines = []; 5 | for (var _i = 0; _i < structuredStackTrace.length; _i++) { 6 | var trace = structuredStackTrace[_i]; 7 | lines.push((trace.getMethodName() || trace.getFunctionName() || "") + "[L" + trace.getLineNumber() + "] "); 8 | } 9 | return lines; 10 | // 11 | // structuredStackTrace[0]; 12 | // console.log(structuredStackTrace); 13 | // 14 | // 15 | // 16 | // return { 17 | // // method name 18 | // name: trace.getMethodName() || trace.getFunctionName() || "", 19 | // // file name 20 | // file: trace.getFileName(), 21 | // // line number 22 | // line: trace.getLineNumber(), 23 | // // column number 24 | // column: trace.getColumnNumber() 25 | // }; 26 | } 27 | function getTrace(caller) { 28 | var err = Error, original = err.prepareStackTrace, error = {}; 29 | err.captureStackTrace(error, caller || getTrace); 30 | err.prepareStackTrace = prepareStackTrace; 31 | var stack = error.stack; 32 | err.prepareStackTrace = original; 33 | return stack; 34 | } 35 | var Task = (function () { 36 | function Task(_grunt, _source, _gruntFile) { 37 | this._grunt = _grunt; 38 | this._source = _source; 39 | this._gruntFile = _gruntFile; 40 | this._initTime = 0; 41 | this._initTime = Date.now(); 42 | } 43 | Task.prototype.getGrunt = function () { 44 | return this._grunt; 45 | }; 46 | Task.prototype.getOptions = function () { 47 | if (!this._options) { 48 | this._options = option.createGruntOption(this._source, this._grunt, this._gruntFile, this); 49 | } 50 | return this._options; 51 | }; 52 | Task.prototype.getHost = function () { 53 | if (!this._host) { 54 | this._host = host.createHost(this._grunt, this.getOptions(), this); 55 | } 56 | return this._host; 57 | }; 58 | Task.prototype.verbose = function (message, stack) { 59 | this._grunt.verbose.writeln((message + " [" + (Date.now() - this._initTime) + "ms]").grey); 60 | if (stack) { 61 | this._grunt.verbose.writeln(getTrace().join("\n").grey); 62 | } 63 | }; 64 | return Task; 65 | })(); 66 | exports.Task = Task; 67 | -------------------------------------------------------------------------------- /tasks/modules/util.js: -------------------------------------------------------------------------------- 1 | /// 2 | var _path = require("path"), _fs = require("fs"), _os = require("os"); 3 | /** 4 | * string 型かどうか 5 | */ 6 | function isStr(val) { 7 | return Object.prototype.toString.call(val) === "[object String]"; 8 | } 9 | exports.isStr = isStr; 10 | /** 11 | * boolean 型かどうか 12 | */ 13 | function isBool(val) { 14 | return Object.prototype.toString.call(val) === "[object Boolean]"; 15 | } 16 | exports.isBool = isBool; 17 | /** 18 | * 配列かどうか 19 | */ 20 | function isArray(val) { 21 | return Object.prototype.toString.call(val) === "[object Array]"; 22 | } 23 | exports.isArray = isArray; 24 | /** 25 | * undefined かどうか 26 | */ 27 | function isUndef(val) { 28 | return typeof val === "undefined"; 29 | } 30 | exports.isUndef = isUndef; 31 | /** 32 | * bin ディレクトリのパス 33 | */ 34 | function getBinDir() { 35 | return _path.dirname(require.resolve("typescript")); 36 | } 37 | exports.getBinDir = getBinDir; 38 | //ts 39 | var hasOwnProperty = Object.prototype.hasOwnProperty; 40 | function hasProperty(value, key) { 41 | return hasOwnProperty.call(value, key); 42 | } 43 | exports.hasProperty = hasProperty; 44 | var colonCode = 0x3A; 45 | var slashCode = 0x2F; 46 | function getRootLength(path) { 47 | if (path.charCodeAt(0) === slashCode) { 48 | if (path.charCodeAt(1) !== slashCode) 49 | return 1; 50 | var p1 = path.indexOf("/", 2); 51 | if (p1 < 0) 52 | return 2; 53 | var p2 = path.indexOf("/", p1 + 1); 54 | if (p2 < 0) 55 | return p1 + 1; 56 | return p2 + 1; 57 | } 58 | if (path.charCodeAt(1) === colonCode) { 59 | if (path.charCodeAt(2) === slashCode) 60 | return 3; 61 | return 2; 62 | } 63 | var idx = path.indexOf("://"); 64 | if (idx !== -1) 65 | return idx + 3; 66 | return 0; 67 | } 68 | exports.getRootLength = getRootLength; 69 | /** 70 | * パスの区切り文字を静音化(バックスラッシュをスラッシュに) 71 | */ 72 | function normalizeSlashes(path) { 73 | return path.replace(/\\/g, "/"); 74 | } 75 | exports.normalizeSlashes = normalizeSlashes; 76 | var directorySeparator = "/"; 77 | function getNormalizedParts(normalizedSlashedPath, rootLength) { 78 | var parts = normalizedSlashedPath.substr(rootLength).split(directorySeparator); 79 | var normalized = []; 80 | for (var _i = 0; _i < parts.length; _i++) { 81 | var part = parts[_i]; 82 | if (part !== ".") { 83 | if (part === ".." && normalized.length > 0 && normalized[normalized.length - 1] !== "..") { 84 | normalized.pop(); 85 | } 86 | else { 87 | if (part) { 88 | normalized.push(part); 89 | } 90 | } 91 | } 92 | } 93 | return normalized; 94 | } 95 | function normalizePath(path) { 96 | var spath = normalizeSlashes(path); 97 | var rootLength = getRootLength(spath); 98 | var normalized = getNormalizedParts(spath, rootLength); 99 | return spath.substr(0, rootLength) + normalized.join(directorySeparator); 100 | } 101 | exports.normalizePath = normalizePath; 102 | function combinePaths(path1, path2) { 103 | if (!(path1 && path1.length)) 104 | return path2; 105 | if (!(path2 && path2.length)) 106 | return path1; 107 | //if (path2.charAt(0) === directorySeparator) return path2; 108 | if (getRootLength(path2) !== 0) 109 | return path2; 110 | if (path1.charAt(path1.length - 1) === directorySeparator) 111 | return path1 + path2; 112 | return path1 + directorySeparator + path2; 113 | } 114 | exports.combinePaths = combinePaths; 115 | function getDirectoryPath(path) { 116 | return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(directorySeparator))); 117 | } 118 | exports.getDirectoryPath = getDirectoryPath; 119 | function readFile(fileName, encoding) { 120 | if (!_fs.existsSync(fileName)) { 121 | return undefined; 122 | } 123 | var buffer = _fs.readFileSync(fileName); 124 | var len = buffer.length; 125 | if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) { 126 | // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js, 127 | // flip all byte pairs and treat as little endian. 128 | len &= ~1; 129 | for (var i = 0; i < len; i += 2) { 130 | var temp = buffer[i]; 131 | buffer[i] = buffer[i + 1]; 132 | buffer[i + 1] = temp; 133 | } 134 | return buffer.toString("utf16le", 2); 135 | } 136 | if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) { 137 | // Little endian UTF-16 byte order mark detected 138 | return buffer.toString("utf16le", 2); 139 | } 140 | if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { 141 | // UTF-8 byte order mark detected 142 | return buffer.toString("utf8", 3); 143 | } 144 | // Default is UTF-8 with no byte order mark 145 | return buffer.toString("utf8"); 146 | } 147 | exports.readFile = readFile; 148 | function writeFile(fileName, data, writeByteOrderMark) { 149 | // If a BOM is required, emit one 150 | if (writeByteOrderMark) { 151 | data = '\uFEFF' + data; 152 | } 153 | _fs.writeFileSync(fileName, data, "utf8"); 154 | } 155 | exports.writeFile = writeFile; 156 | function abs(fileName) { 157 | return normalizePath(_path.resolve(".", normalizePath(fileName))); 158 | } 159 | exports.abs = abs; 160 | function fileExists(path) { 161 | return _fs.existsSync(path); 162 | } 163 | exports.fileExists = fileExists; 164 | function directoryExists(path) { 165 | return _fs.existsSync(path) && _fs.statSync(path).isDirectory(); 166 | } 167 | exports.directoryExists = directoryExists; 168 | function dirOrFileExists(path) { 169 | return _fs.existsSync(path); 170 | } 171 | exports.dirOrFileExists = dirOrFileExists; 172 | function createDirectory(directoryName) { 173 | if (!directoryExists(directoryName)) { 174 | _fs.mkdirSync(directoryName); 175 | } 176 | } 177 | exports.createDirectory = createDirectory; 178 | function createDirectoryRecurse(directoryName) { 179 | if (directoryName.length > getRootLength(directoryName) && !directoryExists(directoryName)) { 180 | var parentDirectory = getDirectoryPath(directoryName); 181 | createDirectoryRecurse(parentDirectory); 182 | //TODO: 183 | createDirectory(directoryName); 184 | } 185 | } 186 | exports.createDirectoryRecurse = createDirectoryRecurse; 187 | function getCurrentDirectory() { 188 | return normalizePath(_path.resolve(".")); 189 | } 190 | exports.getCurrentDirectory = getCurrentDirectory; 191 | function relativePath(from, to) { 192 | return _path.relative(from, to); 193 | } 194 | exports.relativePath = relativePath; 195 | function write(str) { 196 | console.log(str); 197 | } 198 | exports.write = write; 199 | function writeAbort(str) { 200 | console.log((str || "").red); 201 | } 202 | exports.writeAbort = writeAbort; 203 | function writeError(str) { 204 | console.log(">> ".red + str.trim().replace(/\r/g, '').replace(/\n/g, "\n>> ".red)); 205 | } 206 | exports.writeError = writeError; 207 | function writeInfo(str) { 208 | console.log(">> ".cyan + str.trim().replace(/\r/g, '').replace(/\n/g, "\n>> ".cyan)); 209 | } 210 | exports.writeInfo = writeInfo; 211 | function writeWarn(str) { 212 | console.log(">> ".yellow + str.trim().replace(/\r/g, '').replace(/\n/g, "\n>> ".yellow)); 213 | } 214 | exports.writeWarn = writeWarn; 215 | -------------------------------------------------------------------------------- /tasks/modules/watcher.js: -------------------------------------------------------------------------------- 1 | /// 2 | var util = require("./util"); 3 | var _path = require("path"), _fs = require("fs"); 4 | function createWatcher(watchPaths, callback) { 5 | var chokidar = require("chokidar"), watcher, timeoutId, callbacking = false, events = {}; 6 | function start() { 7 | if (watcher) { 8 | return; 9 | } 10 | watcher = chokidar.watch(watchPaths, { ignoreInitial: true, persistent: true, ignorePermissionErrors: true }); 11 | watcher.on("add", function (path, stats) { 12 | add(path, "add", stats); 13 | }).on("change", function (path, stats) { 14 | add(path, "change", stats); 15 | }).on("unlink", function (path, stats) { 16 | add(path, "unlink", stats); 17 | }).on("error", function (error) { 18 | util.writeError(error); 19 | }); 20 | } 21 | function add(path, eventName, stats) { 22 | if (_path.extname(path) !== ".ts") { 23 | return; 24 | } 25 | path = util.normalizePath(path); 26 | if (stats && stats.mtime) { 27 | events[path] = { 28 | mtime: stats.mtime.getTime(), 29 | ev: eventName 30 | }; 31 | } 32 | else { 33 | events[path] = { 34 | mtime: eventName === "unlink" ? 0 : _fs.statSync(path).mtime.getTime(), 35 | ev: eventName 36 | }; 37 | } 38 | util.write(eventName.cyan + " " + path); 39 | executeCallback(); 40 | } 41 | function clone(value) { 42 | var result = {}; 43 | Object.keys(value).forEach(function (item) { 44 | result[item] = value[item]; 45 | }); 46 | return result; 47 | } 48 | function executeCallback() { 49 | if (!Object.keys(events).length) { 50 | return; 51 | } 52 | if (callbacking) { 53 | return; 54 | } 55 | if (timeoutId) { 56 | clearTimeout(timeoutId); 57 | } 58 | timeoutId = setTimeout(function () { 59 | callbacking = true; 60 | var value = clone(events); 61 | events = {}; 62 | try { 63 | callback(value, function () { 64 | callbacking = false; 65 | executeCallback(); 66 | }); 67 | } 68 | catch (e) { 69 | callbacking = false; 70 | } 71 | }, 1000); 72 | } 73 | return { 74 | start: start 75 | }; 76 | } 77 | exports.createWatcher = createWatcher; 78 | -------------------------------------------------------------------------------- /test/errorTest.js: -------------------------------------------------------------------------------- 1 | var grunt = require("grunt"); 2 | var fs = require("fs"); 3 | var path = require("path"); 4 | var spawn = require('child_process').spawn; 5 | 6 | function exec(arg, done){ 7 | var cmd = process.execPath; 8 | var args = process.execArgv.concat(process.argv[1], arg); 9 | 10 | var command = spawn(cmd, args), 11 | results = []; 12 | command.stdout.on("data", function(data){ 13 | //results.push(data.toString()); 14 | var text = trim(data); 15 | results.push.apply(results, text.split("\n")); 16 | }); 17 | command.on("close", function(){ 18 | setTimeout(function(){ 19 | results.shift(); 20 | results.pop(); 21 | results.pop(); 22 | results.pop(); 23 | done(results); 24 | }, 500); 25 | }); 26 | } 27 | 28 | function trim(val){ 29 | return ((val || "") + "").trim(); 30 | } 31 | 32 | 33 | module.exports.errorTypescript = { 34 | errorTypecheck: function (test) { 35 | "use strict"; 36 | 37 | test.expect(1); 38 | 39 | exec(["typescript:errorTypecheck", "--error"], function(results){ 40 | test.equal(">> ".red + "test/fixtures/error-typecheck.ts(1,1): error TS2304: Cannot find name 'foo'.", trim(results[0])); 41 | 42 | //console.log(results[0].trim()); 43 | 44 | test.done(); 45 | 46 | }); 47 | }, 48 | errorSyntax: function (test) { 49 | "use strict"; 50 | test.expect(1); 51 | exec(["typescript:errorSyntax", "--error"], function(results){ 52 | test.equal(">> ".red + "test/fixtures/error-syntax.ts(1,9): error TS1005: ';' expected.", trim(results[0])); 53 | test.done(); 54 | }); 55 | }, 56 | 57 | noLib: function(test){ 58 | "use strict"; 59 | 60 | test.expect(8); 61 | 62 | exec(["typescript:noLib", "--error"], function(results){ 63 | test.equal(">> ".red + "error TS2318: Cannot find global type 'Array'.", trim(results[0])); 64 | test.equal(">> ".red + "error TS2318: Cannot find global type 'Boolean'.", trim(results[1])); 65 | test.equal(">> ".red + "error TS2318: Cannot find global type 'Function'.", trim(results[2])); 66 | test.equal(">> ".red + "error TS2318: Cannot find global type 'IArguments'.", trim(results[3])); 67 | test.equal(">> ".red + "error TS2318: Cannot find global type 'Number'.", trim(results[4])); 68 | test.equal(">> ".red + "error TS2318: Cannot find global type 'Object'.", trim(results[5])); 69 | test.equal(">> ".red + "error TS2318: Cannot find global type 'RegExp'.", trim(results[6])); 70 | test.equal(">> ".red + "error TS2318: Cannot find global type 'String'.", trim(results[7])); 71 | test.done(); 72 | }); 73 | }, 74 | noLibCore: function(test){ 75 | 76 | "use strict"; 77 | 78 | test.expect(1); 79 | 80 | exec(["typescript:noLibCore", "--error"], function(results){ 81 | test.equal(">> ".red + "test/fixtures/noLib.ts(4,10): error TS2304: Cannot find name 'document'.", trim(results[0])); 82 | 83 | test.done(); 84 | }); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /test/fixtures/amd.ts: -------------------------------------------------------------------------------- 1 | export module Foo { 2 | export function bar () : string { 3 | return "foobar!"; 4 | } 5 | } -------------------------------------------------------------------------------- /test/fixtures/async.ts: -------------------------------------------------------------------------------- 1 | function wait(ms: number){ 2 | return new Promise((resolve, reject) => { 3 | setTimeout(() => { 4 | resolve("resolve"); 5 | }, ms); 6 | }) 7 | } 8 | 9 | var result = async () =>{ 10 | return await wait(1000); 11 | }; 12 | console.log(result); -------------------------------------------------------------------------------- /test/fixtures/basepath.ts: -------------------------------------------------------------------------------- 1 | module BasePath { 2 | export function main() { 3 | return "hello basepath"; 4 | } 5 | } 6 | 7 | BasePath.main(); -------------------------------------------------------------------------------- /test/fixtures/comments.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Simple 1 module 3 | */ 4 | module Simple1 { 5 | /** 6 | * main function 7 | * @param name your name 8 | * @returns {string} message 9 | */ 10 | export function main(name:string = "") { 11 | return "hello " + name; 12 | } 13 | } 14 | 15 | Simple1.main(); -------------------------------------------------------------------------------- /test/fixtures/commonjs.ts: -------------------------------------------------------------------------------- 1 | 2 | export module Foo { 3 | export function bar () : string { 4 | return "foobar!"; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /test/fixtures/crlf.ts: -------------------------------------------------------------------------------- 1 | module Simple1 { 2 | export function main() { 3 | return "hello simple 1"; 4 | } 5 | } 6 | Simple1.main(); -------------------------------------------------------------------------------- /test/fixtures/declaration.ts: -------------------------------------------------------------------------------- 1 | module Simple2 { 2 | export function main() { 3 | return "hello simple2"; 4 | } 5 | } 6 | 7 | Simple2.main(); -------------------------------------------------------------------------------- /test/fixtures/decorator.ts: -------------------------------------------------------------------------------- 1 | function classdeco(option: string) { 2 | 3 | return function(target: any): void{ 4 | 5 | }; 6 | }; 7 | 8 | function methodPropDeco(option: string){ 9 | return function(target, key, descriptor): void{ 10 | 11 | } 12 | } 13 | 14 | function propDeco(option: string){ 15 | return function(target, index): void{ 16 | 17 | } 18 | } 19 | 20 | 21 | @classdeco("class") 22 | class Sample { 23 | 24 | @propDeco("prop") 25 | message: string; 26 | 27 | @methodPropDeco("method") 28 | greeting(p: string): void {} 29 | 30 | @methodPropDeco("static") 31 | static sayHello(): void {} 32 | } 33 | -------------------------------------------------------------------------------- /test/fixtures/decorator2.ts: -------------------------------------------------------------------------------- 1 | function classdeco(option: string) { 2 | 3 | return function(target: any): void{ 4 | 5 | }; 6 | }; 7 | 8 | function methodPropDeco(option: string){ 9 | return function(target, key, descriptor): void{ 10 | 11 | } 12 | } 13 | 14 | function propDeco(option: string){ 15 | return function(target, index): void{ 16 | 17 | } 18 | } 19 | 20 | 21 | @classdeco("class") 22 | class Sample { 23 | 24 | @propDeco("prop") 25 | message: string; 26 | 27 | @methodPropDeco("method") 28 | greeting(p: string): void {} 29 | 30 | @methodPropDeco("static") 31 | static sayHello(): void {} 32 | } 33 | -------------------------------------------------------------------------------- /test/fixtures/dest.ts: -------------------------------------------------------------------------------- 1 | module Dest { 2 | export function main() { 3 | return "hello dest"; 4 | } 5 | } 6 | 7 | Dest.main(); -------------------------------------------------------------------------------- /test/fixtures/error-syntax.ts: -------------------------------------------------------------------------------- 1 | moduler test{ 2 | 3 | } -------------------------------------------------------------------------------- /test/fixtures/error-typecheck.ts: -------------------------------------------------------------------------------- 1 | foo("hoge"); -------------------------------------------------------------------------------- /test/fixtures/es5.ts: -------------------------------------------------------------------------------- 1 | module ES5 { 2 | export class Test { 3 | public get greeting() : string { 4 | return "Hello!"; 5 | } 6 | } 7 | } 8 | 9 | var test = new ES5.Test(); 10 | console.log(test.greeting); 11 | -------------------------------------------------------------------------------- /test/fixtures/es6.ts: -------------------------------------------------------------------------------- 1 | module ES6 { 2 | export class Test { 3 | public get greeting() : string { 4 | return "Hello!"; 5 | } 6 | } 7 | } 8 | 9 | (function(){ 10 | 11 | const name = "taro"; 12 | let test = new ES6.Test(); 13 | 14 | let texts: string[] = [test.greeting, name]; 15 | let iter = texts.values(); //(texts[Symbol.iterator])(); 16 | while(true){ 17 | let val = iter.next(); 18 | if(!val.done) break; 19 | } 20 | })(); 21 | -------------------------------------------------------------------------------- /test/fixtures/jsxpreserve.jsx: -------------------------------------------------------------------------------- 1 |
; 2 | -------------------------------------------------------------------------------- /test/fixtures/jsxpreserve.tsx: -------------------------------------------------------------------------------- 1 |
-------------------------------------------------------------------------------- /test/fixtures/jsxreact.tsx: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | import React = __React; 4 | 5 |
-------------------------------------------------------------------------------- /test/fixtures/lf.ts: -------------------------------------------------------------------------------- 1 | module Simple1 { 2 | export function main() { 3 | return "hello simple 1"; 4 | } 5 | } 6 | Simple1.main(); -------------------------------------------------------------------------------- /test/fixtures/noLib.ts: -------------------------------------------------------------------------------- 1 | //core 2 | var num = parseInt("10", 10); 3 | //dom 4 | var el = document.getElementById("foo"); 5 | //scriptHost 6 | //WScript.echo("foo"); 7 | //webworker 8 | //new WorkerNavigator(); 9 | -------------------------------------------------------------------------------- /test/fixtures/ref.ts: -------------------------------------------------------------------------------- 1 | var result = Lib.getName(); 2 | -------------------------------------------------------------------------------- /test/fixtures/simple.ts: -------------------------------------------------------------------------------- 1 | module Simple1 { 2 | export function main() { 3 | return "hello simple 1"; 4 | } 5 | } 6 | Simple1.main(); -------------------------------------------------------------------------------- /test/fixtures/single/dir/single2.ts: -------------------------------------------------------------------------------- 1 | module Single2 { 2 | export function main() { 3 | return "hello single2"; 4 | } 5 | } 6 | 7 | Single2.main(); -------------------------------------------------------------------------------- /test/fixtures/single/single1.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | module Single1 { 4 | export function main() { 5 | return "hello single1"; 6 | } 7 | } 8 | 9 | Single2.main(); 10 | Single1.main(); -------------------------------------------------------------------------------- /test/fixtures/sourcemap.ts: -------------------------------------------------------------------------------- 1 | module Simple3 { 2 | export function main() { 3 | return "hello simple3"; 4 | } 5 | } 6 | 7 | Simple3.main(); -------------------------------------------------------------------------------- /test/fixtures/system.ts: -------------------------------------------------------------------------------- 1 | export module Foo { 2 | export function bar () : string { 3 | return "foobar!"; 4 | } 5 | } -------------------------------------------------------------------------------- /test/fixtures/umd.ts: -------------------------------------------------------------------------------- 1 | export module Foo { 2 | export function bar () : string { 3 | return "foobar!"; 4 | } 5 | } -------------------------------------------------------------------------------- /test/libs/extlib.d.ts: -------------------------------------------------------------------------------- 1 | declare module Lib{ 2 | export function getName(): string; 3 | } 4 | -------------------------------------------------------------------------------- /test/test.js: -------------------------------------------------------------------------------- 1 | var grunt = require("grunt"); 2 | var fs = require("fs"); 3 | var path = require("path"); 4 | 5 | module.exports.typescript = { 6 | simple:function (test) { 7 | "use strict"; 8 | 9 | test.expect(1); 10 | 11 | var actual = grunt.file.read("test/fixtures/simple.js"); 12 | var expected = grunt.file.read("test/expected/simple.js"); 13 | test.equal(expected, actual); 14 | 15 | test.done(); 16 | }, 17 | dest: function(test){ 18 | "use strict"; 19 | 20 | test.expect(1); 21 | 22 | var actual = grunt.file.read("test/temp/dest/test/fixtures/dest.js"); 23 | var expected = grunt.file.read("test/expected/dest.js"); 24 | test.equal(expected, actual); 25 | 26 | test.done(); 27 | }, 28 | basePath: function(test){ 29 | "use strict"; 30 | 31 | test.expect(1); 32 | 33 | var actual = grunt.file.read("test/temp/basepath/basepath.js"); 34 | var expected = grunt.file.read("test/expected/basepath.js"); 35 | test.equal(expected, actual); 36 | 37 | test.done(); 38 | }, 39 | declaration:function (test) { 40 | "use strict"; 41 | 42 | test.expect(2); 43 | 44 | var actual = grunt.file.read("test/fixtures/declaration.js"); 45 | var expected = grunt.file.read("test/expected/declaration.js"); 46 | test.equal(expected, actual); 47 | 48 | actual = grunt.file.read("test/fixtures/declaration.d.ts"); 49 | expected = grunt.file.read("test/expected/declaration.d.ts"); 50 | test.equal(expected, actual); 51 | 52 | test.done(); 53 | }, 54 | sourcemap:function(test){ 55 | "use strict"; 56 | 57 | test.expect(2); 58 | 59 | var actual = grunt.file.read("test/fixtures/sourcemap.js"); 60 | var expected = grunt.file.read("test/expected/sourcemap.js"); 61 | 62 | test.equal(expected, actual, 'incorrect output javascript'); 63 | 64 | actual = grunt.file.read("test/fixtures/sourcemap.js.map"); 65 | expected = grunt.file.read("test/expected/sourcemap.js.map"); 66 | 67 | test.equal(expected, actual, 'incorrect sourcemap'); 68 | 69 | test.done(); 70 | }, 71 | "sourcemap-dest": function(test){ 72 | "use strict"; 73 | 74 | test.expect(2); 75 | 76 | var actual = grunt.file.read("test/temp/sourcemap/sourcemap.js"); 77 | var expected = grunt.file.read("test/expected/sourcemap/sourcemap.js"); 78 | 79 | test.equal(expected, actual, 'incorrect output javascript'); 80 | 81 | actual = grunt.file.read("test/temp/sourcemap/sourcemap.js.map"); 82 | expected = grunt.file.read("test/expected/sourcemap/sourcemap.js.map"); 83 | 84 | test.equal(expected, actual, 'incorrect sourcemap dest'); 85 | 86 | test.done(); 87 | }, 88 | es5:function(test){ 89 | "use strict"; 90 | 91 | test.expect(1); 92 | 93 | var actual = grunt.file.read("test/fixtures/es5.js"); 94 | var expected = grunt.file.read("test/expected/es5.js"); 95 | test.equal(expected, actual); 96 | 97 | test.done(); 98 | }, 99 | es6:function(test){ 100 | "use strict"; 101 | 102 | test.expect(1); 103 | 104 | var actual = grunt.file.read("test/fixtures/es6.js"); 105 | var expected = grunt.file.read("test/expected/es6.js"); 106 | test.equal(expected, actual); 107 | 108 | test.done(); 109 | }, 110 | amd:function(test){ 111 | "use strict"; 112 | 113 | test.expect(1); 114 | 115 | var actual = grunt.file.read("test/fixtures/amd.js"); 116 | var expected = grunt.file.read("test/expected/amd.js"); 117 | test.equal(expected, actual); 118 | 119 | test.done(); 120 | }, 121 | commonjs:function(test){ 122 | "use strict"; 123 | 124 | test.expect(1); 125 | 126 | var actual = grunt.file.read("test/fixtures/commonjs.js"); 127 | var expected = grunt.file.read("test/expected/commonjs.js"); 128 | test.equal(expected, actual); 129 | 130 | test.done(); 131 | }, 132 | umd:function(test){ 133 | "use strict"; 134 | 135 | test.expect(1); 136 | 137 | var actual = grunt.file.read("test/fixtures/umd.js"); 138 | var expected = grunt.file.read("test/expected/umd.js"); 139 | test.equal(expected, actual); 140 | 141 | test.done(); 142 | }, 143 | system:function(test){ 144 | "use strict"; 145 | 146 | test.expect(1); 147 | 148 | var actual = grunt.file.read("test/fixtures/system.js"); 149 | var expected = grunt.file.read("test/expected/system.js"); 150 | test.equal(expected, actual); 151 | 152 | test.done(); 153 | }, 154 | crlf:function(test){ 155 | "use strict"; 156 | 157 | test.expect(1); 158 | 159 | var actual = grunt.file.read("test/fixtures/crlf.js"); 160 | var expected = grunt.file.read("test/expected/crlf.js"); 161 | test.equal(expected, actual); 162 | 163 | test.done(); 164 | }, 165 | lf:function(test){ 166 | "use strict"; 167 | 168 | test.expect(1); 169 | 170 | var actual = grunt.file.read("test/fixtures/crlf.js"); 171 | var expected = grunt.file.read("test/expected/crlf.js"); 172 | test.equal(expected, actual); 173 | 174 | test.done(); 175 | }, 176 | decorator:function(test){ 177 | "use strict"; 178 | 179 | test.expect(1); 180 | 181 | var actual = grunt.file.read("test/fixtures/decorator.js"); 182 | var expected = grunt.file.read("test/expected/decorator.js"); 183 | test.equal(expected, actual); 184 | 185 | test.done(); 186 | }, 187 | decorator2:function(test){ 188 | "use strict"; 189 | 190 | test.expect(1); 191 | 192 | var actual = grunt.file.read("test/fixtures/decorator2.js"); 193 | var expected = grunt.file.read("test/expected/decorator2.js"); 194 | test.equal(expected, actual); 195 | 196 | test.done(); 197 | }, 198 | jsxpreserve:function(test){ 199 | "use strict"; 200 | 201 | test.expect(1); 202 | 203 | var actual = grunt.file.read("test/fixtures/jsxpreserve.jsx"); 204 | var expected = grunt.file.read("test/expected/jsxpreserve.jsx"); 205 | test.equal(expected, actual); 206 | 207 | test.done(); 208 | }, 209 | jsxreact:function(test){ 210 | "use strict"; 211 | 212 | test.expect(1); 213 | 214 | var actual = grunt.file.read("test/fixtures/jsxreact.js"); 215 | var expected = grunt.file.read("test/expected/jsxreact.js"); 216 | test.equal(expected, actual); 217 | 218 | test.done(); 219 | }, 220 | async:function(test){ 221 | "use strict"; 222 | 223 | test.expect(1); 224 | 225 | var actual = grunt.file.read("test/fixtures/async.js"); 226 | var expected = grunt.file.read("test/expected/async.js"); 227 | test.equal(expected, actual); 228 | 229 | test.done(); 230 | }, 231 | single:function(test){ 232 | "use strict"; 233 | 234 | test.expect(1); 235 | var actual = grunt.file.read("test/temp/single.js"); 236 | var expected = grunt.file.read("test/expected/single.js"); 237 | 238 | test.equal(expected, actual); 239 | 240 | test.done(); 241 | }, 242 | comments:function(test){ 243 | "use strict"; 244 | 245 | test.expect(1); 246 | var actual = grunt.file.read("test/temp/comments.js"); 247 | var expected = grunt.file.read("test/expected/comments.js"); 248 | 249 | test.equal(expected, actual); 250 | 251 | test.done(); 252 | }, 253 | "comments true":function(test){ 254 | "use strict"; 255 | 256 | test.expect(1); 257 | var actual = grunt.file.read("test/temp/comments_true.js"); 258 | var expected = grunt.file.read("test/expected/comments_true.js"); 259 | 260 | test.equal(expected, actual); 261 | 262 | test.done(); 263 | }, 264 | "comments false":function(test){ 265 | "use strict"; 266 | 267 | test.expect(1); 268 | var actual = grunt.file.read("test/temp/comments_false.js"); 269 | var expected = grunt.file.read("test/expected/comments_false.js"); 270 | 271 | test.equal(expected, actual); 272 | 273 | test.done(); 274 | } 275 | }; 276 | -------------------------------------------------------------------------------- /test/watch/multi/dest/target1/target1.ts: -------------------------------------------------------------------------------- 1 | module Target1 { 2 | export function main() { 3 | return "hello target 1"; 4 | } 5 | } 6 | Target1.main(); 7 | -------------------------------------------------------------------------------- /test/watch/multi/dest/target2/target2.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | module Target2 { 4 | export function main() { 5 | return "hello target 2"; 6 | } 7 | } 8 | Target1.main(); 9 | Target2.main(); 10 | -------------------------------------------------------------------------------- /test/watch/multi/dest/target3/target3.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | module Target3 { 4 | export function main() { 5 | return "hello target 3"; 6 | } 7 | } 8 | Target1.main(); 9 | Target2.main(); 10 | -------------------------------------------------------------------------------- /test/watch/simple/dest/simple1.ts: -------------------------------------------------------------------------------- 1 | module Simple1 { 2 | export function main() { 3 | return "hello simple 1"; 4 | } 5 | } 6 | Simple1.main(); 7 | -------------------------------------------------------------------------------- /test/watch/simple/dest/simple2.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | module Simple2 { 4 | export function main() { 5 | return "hello simple 1"; 6 | } 7 | } 8 | Simple1.main(); 9 | Simple2.main(); -------------------------------------------------------------------------------- /test/watch/single/dest/single1.ts: -------------------------------------------------------------------------------- 1 | module Single1 { 2 | export function main() { 3 | return "hello single 1"; 4 | } 5 | } 6 | Single1.main(); 7 | -------------------------------------------------------------------------------- /test/watch/single/dest/single2.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | module Single2 { 4 | export function main() { 5 | return "hello single 1"; 6 | } 7 | } 8 | Single1.main(); 9 | Single2.main(); -------------------------------------------------------------------------------- /test/watchTest.js: -------------------------------------------------------------------------------- 1 | var grunt = require("grunt"); 2 | var fs = require("fs"); 3 | var util = require("util"); 4 | var path = require("path"); 5 | var spawn = require('child_process').spawn; 6 | 7 | if (!String.prototype.endsWith) { 8 | Object.defineProperty(String.prototype, 'endsWith', { 9 | value: function (searchString, position) { 10 | var subjectString = this.toString(); 11 | if (position === undefined || position > subjectString.length) { 12 | position = subjectString.length; 13 | } 14 | position -= searchString.length; 15 | var lastIndex = subjectString.indexOf(searchString, position); 16 | return lastIndex !== -1 && lastIndex === position; 17 | } 18 | }); 19 | } 20 | if (!String.prototype.startsWith) { 21 | Object.defineProperty(String.prototype, 'startsWith', { 22 | enumerable: false, 23 | configurable: false, 24 | writable: false, 25 | value: function (searchString, position) { 26 | position = position || 0; 27 | return this.lastIndexOf(searchString, position) === position; 28 | } 29 | }); 30 | } 31 | 32 | var mkdir = function(dir) { 33 | // making directory without exception if exists 34 | try { 35 | fs.mkdirSync(dir, 0755); 36 | } catch(e) { 37 | if(e.code != "EEXIST") { 38 | throw e; 39 | } 40 | } 41 | }; 42 | 43 | var rmdir = function(dir) { 44 | if (path.existsSync(dir)) { 45 | var list = fs.readdirSync(dir); 46 | for(var i = 0; i < list.length; i++) { 47 | var filename = path.join(dir, list[i]); 48 | var stat = fs.statSync(filename); 49 | 50 | if(filename == "." || filename == "..") { 51 | // pass these files 52 | } else if(stat.isDirectory()) { 53 | // rmdir recursively 54 | rmdir(filename); 55 | } else { 56 | // rm fiilename 57 | fs.unlinkSync(filename); 58 | } 59 | } 60 | fs.rmdirSync(dir); 61 | } else { 62 | console.warn("warn: " + dir + " not exists"); 63 | } 64 | }; 65 | 66 | var copyDir = function(src, dest) { 67 | mkdir(dest); 68 | var files = fs.readdirSync(src); 69 | for(var i = 0; i < files.length; i++) { 70 | var current = fs.lstatSync(path.join(src, files[i])); 71 | if(current.isDirectory()) { 72 | copyDir(path.join(src, files[i]), path.join(dest, files[i])); 73 | } else if(current.isSymbolicLink()) { 74 | var symlink = fs.readlinkSync(path.join(src, files[i])); 75 | fs.symlinkSync(symlink, path.join(dest, files[i])); 76 | } else { 77 | copy(path.join(src, files[i]), path.join(dest, files[i])); 78 | } 79 | } 80 | }; 81 | 82 | var copy = function(src, dest) { 83 | var oldFile = fs.createReadStream(src); 84 | var newFile = fs.createWriteStream(dest); 85 | oldFile.pipe(newFile); 86 | }; 87 | 88 | function exec(arg, stdout, done){ 89 | var cmd = process.execPath; 90 | var args = process.execArgv.concat(process.argv[1], arg); 91 | 92 | var command = spawn(cmd, args), 93 | results = []; 94 | command.stdout.on("data", function(data){ 95 | var text = data.toString(); 96 | stdout(text); 97 | results.push(text); 98 | }); 99 | command.on("close", function(){ 100 | if(done){ 101 | done(results); 102 | } 103 | }); 104 | return command; 105 | } 106 | 107 | module.exports.watchTypescript = { 108 | simpleWatch: function (test) { 109 | "use strict"; 110 | 111 | var root = "test/watch/simple/target"; 112 | 113 | copyDir("test/watch/simple/dest", root); 114 | 115 | test.expect(3); 116 | 117 | var checks = [{}, {}, { 118 | stdout: function(text){ 119 | text = text.trim(); 120 | test.ok(text.startsWith("Watching...")); 121 | test.ok(text.endsWith(root)); 122 | }, 123 | action: function(){ 124 | grunt.file.write(root + "/simple1.ts", grunt.file.read(root + "/simple1.ts") + " "); 125 | } 126 | },{ 127 | stdout: function(text){ 128 | text = text.trim(); 129 | test.ok(text.endsWith(root + "/simple1.ts")); 130 | } 131 | },{ 132 | stdout: function(text){ 133 | text = text.trim(); 134 | //test.ok(text.startsWith("2 files")); 135 | } 136 | }]; 137 | 138 | console.log(""); 139 | 140 | var command = exec(["typescript:simpleWatch", "--watch"], function(text){ 141 | var check = checks.shift(); 142 | console.log(text); 143 | if(!check){ 144 | 145 | command.kill(); 146 | return; 147 | } 148 | 149 | if(!!check.stdout){ 150 | check.stdout(text); 151 | } 152 | if(!!check.action){ 153 | setTimeout(function(check){ 154 | check.action(); 155 | }.bind(null, check), 1000); 156 | } 157 | if(!checks.length){ 158 | command.kill(); 159 | } 160 | }, function(results){ 161 | console.log("done"); 162 | //rmdir(root); 163 | test.done(); 164 | }); 165 | 166 | } 167 | } -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "tasks", 4 | "target": "ES5", 5 | "module": "commonjs", 6 | "noEmitOnError": true, 7 | "diagnostics": true, 8 | "noLib": true, 9 | "experimentalDecorators": true 10 | }, 11 | "files": [ 12 | "src/index.ts", 13 | "node_modules/typescript/lib/lib.core.d.ts", 14 | "typings/lib.support.d.ts" 15 | ] 16 | } -------------------------------------------------------------------------------- /typings/bluebird.d.ts: -------------------------------------------------------------------------------- 1 | // Type definitions for bluebird 2.0.0 2 | // Project: https://github.com/petkaantonov/bluebird 3 | // Definitions by: Bart van der Schoor 4 | // Definitions: https://github.com/borisyankov/DefinitelyTyped 5 | 6 | // ES6 model with generics overload was sourced and trans-multiplied from es6-promises.d.ts 7 | // By: Campredon 8 | 9 | // Warning: recommended to use `tsc > v0.9.7` (critical bugs in earlier generic code): 10 | // - https://github.com/borisyankov/DefinitelyTyped/issues/1563 11 | 12 | // Note: replicate changes to all overloads in both definition and test file 13 | // Note: keep both static and instance members inline (so similar) 14 | 15 | // TODO fix remaining TODO annotations in both definition and test 16 | 17 | // TODO verify support to have no return statement in handlers to get a Promise (more overloads?) 18 | 19 | declare class Promise implements Promise.Thenable, Promise.Inspection { 20 | /** 21 | * Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise. 22 | */ 23 | constructor(callback: (resolve: (thenable: Promise.Thenable) => void, reject: (error: any) => void) => void); 24 | constructor(callback: (resolve: (result: R) => void, reject: (error: any) => void) => void); 25 | 26 | /** 27 | * Promises/A+ `.then()` with progress handler. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. 28 | */ 29 | then(onFulfill: (value: R) => Promise.Thenable, onReject: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; 30 | then(onFulfill: (value: R) => Promise.Thenable, onReject?: (error: any) => U, onProgress?: (note: any) => any): Promise; 31 | then(onFulfill: (value: R) => U, onReject: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; 32 | then(onFulfill?: (value: R) => U, onReject?: (error: any) => U, onProgress?: (note: any) => any): Promise; 33 | 34 | /** 35 | * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. 36 | * 37 | * Alias `.caught();` for compatibility with earlier ECMAScript version. 38 | */ 39 | catch(onReject?: (error: any) => Promise.Thenable): Promise; 40 | caught(onReject?: (error: any) => Promise.Thenable): Promise; 41 | 42 | catch(onReject?: (error: any) => U): Promise; 43 | caught(onReject?: (error: any) => U): Promise; 44 | 45 | /** 46 | * This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called. 47 | * 48 | * This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. The return result of the predicate will be used determine whether the error handler should be called. 49 | * 50 | * Alias `.caught();` for compatibility with earlier ECMAScript version. 51 | */ 52 | catch(predicate: (error: any) => boolean, onReject: (error: any) => Promise.Thenable): Promise; 53 | caught(predicate: (error: any) => boolean, onReject: (error: any) => Promise.Thenable): Promise; 54 | 55 | catch(predicate: (error: any) => boolean, onReject: (error: any) => U): Promise; 56 | caught(predicate: (error: any) => boolean, onReject: (error: any) => U): Promise; 57 | 58 | catch(ErrorClass: Function, onReject: (error: any) => Promise.Thenable): Promise; 59 | caught(ErrorClass: Function, onReject: (error: any) => Promise.Thenable): Promise; 60 | 61 | catch(ErrorClass: Function, onReject: (error: any) => U): Promise; 62 | caught(ErrorClass: Function, onReject: (error: any) => U): Promise; 63 | 64 | /** 65 | * Like `.catch` but instead of catching all types of exceptions, it only catches those that don't originate from thrown errors but rather from explicit rejections. 66 | */ 67 | error(onReject: (reason: any) => Promise.Thenable): Promise; 68 | error(onReject: (reason: any) => U): Promise; 69 | 70 | /** 71 | * Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for `.finally()` in that the final value cannot be modified from the handler. 72 | * 73 | * Alias `.lastly();` for compatibility with earlier ECMAScript version. 74 | */ 75 | finally(handler: () => Promise.Thenable): Promise; 76 | finally(handler: () => U): Promise; 77 | 78 | lastly(handler: () => Promise.Thenable): Promise; 79 | lastly(handler: () => U): Promise; 80 | 81 | /** 82 | * Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise. 83 | */ 84 | bind(thisArg: any): Promise; 85 | 86 | /** 87 | * Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error. 88 | */ 89 | done(onFulfilled: (value: R) => Promise.Thenable, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): void; 90 | done(onFulfilled: (value: R) => Promise.Thenable, onRejected?: (error: any) => U, onProgress?: (note: any) => any): void; 91 | done(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): void; 92 | done(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): void; 93 | 94 | /** 95 | * Like `.finally()`, but not called for rejections. 96 | */ 97 | tap(onFulFill: (value: R) => Promise.Thenable): Promise; 98 | tap(onFulfill: (value: R) => U): Promise; 99 | 100 | /** 101 | * Shorthand for `.then(null, null, handler);`. Attach a progress handler that will be called if this promise is progressed. Returns a new promise chained from this promise. 102 | */ 103 | progressed(handler: (note: any) => any): Promise; 104 | 105 | /** 106 | * Same as calling `Promise.delay(this, ms)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. 107 | */ 108 | delay(ms: number): Promise; 109 | 110 | /** 111 | * Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason. However, if this promise is not fulfilled or rejected within `ms` milliseconds, the returned promise is rejected with a `Promise.TimeoutError` instance. 112 | * 113 | * You may specify a custom error message with the `message` parameter. 114 | */ 115 | timeout(ms: number, message?: string): Promise; 116 | 117 | /** 118 | * Register a node-style callback on this promise. When this promise is is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success. 119 | * Returns back this promise instead of creating a new one. If the `callback` argument is not a function, this method does not do anything. 120 | */ 121 | nodeify(callback: (err: any, value?: R) => void): Promise; 122 | nodeify(...sink: any[]): void; 123 | 124 | /** 125 | * Marks this promise as cancellable. Promises by default are not cancellable after v0.11 and must be marked as such for `.cancel()` to have any effect. Marking a promise as cancellable is infectious and you don't need to remark any descendant promise. 126 | */ 127 | cancellable(): Promise; 128 | 129 | /** 130 | * Cancel this promise. The cancellation will propagate to farthest cancellable ancestor promise which is still pending. 131 | * 132 | * That ancestor will then be rejected with a `CancellationError` (get a reference from `Promise.CancellationError`) object as the rejection reason. 133 | * 134 | * In a promise rejection handler you may check for a cancellation by seeing if the reason object has `.name === "Cancel"`. 135 | * 136 | * Promises are by default not cancellable. Use `.cancellable()` to mark a promise as cancellable. 137 | */ 138 | // TODO what to do with this? 139 | cancel(): Promise; 140 | 141 | /** 142 | * Like `.then()`, but cancellation of the the returned promise or any of its descendant will not propagate cancellation to this promise or this promise's ancestors. 143 | */ 144 | fork(onFulfilled: (value: R) => Promise.Thenable, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; 145 | fork(onFulfilled: (value: R) => Promise.Thenable, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise; 146 | fork(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; 147 | fork(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise; 148 | 149 | /** 150 | * Create an uncancellable promise based on this promise. 151 | */ 152 | uncancellable(): Promise; 153 | 154 | /** 155 | * See if this promise can be cancelled. 156 | */ 157 | isCancellable(): boolean; 158 | 159 | /** 160 | * See if this `promise` has been fulfilled. 161 | */ 162 | isFulfilled(): boolean; 163 | 164 | /** 165 | * See if this `promise` has been rejected. 166 | */ 167 | isRejected(): boolean; 168 | 169 | /** 170 | * See if this `promise` is still defer. 171 | */ 172 | isPending(): boolean; 173 | 174 | /** 175 | * See if this `promise` is resolved -> either fulfilled or rejected. 176 | */ 177 | isResolved(): boolean; 178 | 179 | /** 180 | * Get the fulfillment value of the underlying promise. Throws if the promise isn't fulfilled yet. 181 | * 182 | * throws `TypeError` 183 | */ 184 | value(): R; 185 | 186 | /** 187 | * Get the rejection reason for the underlying promise. Throws if the promise isn't rejected yet. 188 | * 189 | * throws `TypeError` 190 | */ 191 | reason(): any; 192 | 193 | /** 194 | * Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of the promise as snapshotted at the time of calling `.inspect()`. 195 | */ 196 | inspect(): Promise.Inspection; 197 | 198 | /** 199 | * This is a convenience method for doing: 200 | * 201 | * 202 | * promise.then(function(obj){ 203 | * return obj[propertyName].call(obj, arg...); 204 | * }); 205 | * 206 | */ 207 | call(propertyName: string, ...args: any[]): Promise; 208 | 209 | /** 210 | * This is a convenience method for doing: 211 | * 212 | * 213 | * promise.then(function(obj){ 214 | * return obj[propertyName]; 215 | * }); 216 | * 217 | */ 218 | // TODO find way to fix get() 219 | // get(propertyName: string): Promise; 220 | 221 | /** 222 | * Convenience method for: 223 | * 224 | * 225 | * .then(function() { 226 | * return value; 227 | * }); 228 | * 229 | * 230 | * in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()` 231 | * 232 | * Alias `.thenReturn();` for compatibility with earlier ECMAScript version. 233 | */ 234 | return(): Promise; 235 | thenReturn(): Promise; 236 | return(value: U): Promise; 237 | thenReturn(value: U): Promise; 238 | 239 | /** 240 | * Convenience method for: 241 | * 242 | * 243 | * .then(function() { 244 | * throw reason; 245 | * }); 246 | * 247 | * Same limitations apply as with `.return()`. 248 | * 249 | * Alias `.thenThrow();` for compatibility with earlier ECMAScript version. 250 | */ 251 | throw(reason: Error): Promise; 252 | thenThrow(reason: Error): Promise; 253 | 254 | /** 255 | * Convert to String. 256 | */ 257 | toString(): string; 258 | 259 | /** 260 | * This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`. 261 | */ 262 | toJSON(): Object; 263 | 264 | /** 265 | * Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers. 266 | */ 267 | // TODO how to model instance.spread()? like Q? 268 | spread(onFulfill: Function, onReject?: (reason: any) => Promise.Thenable): Promise; 269 | spread(onFulfill: Function, onReject?: (reason: any) => U): Promise; 270 | /* 271 | // TODO or something like this? 272 | spread(onFulfill: (...values: W[]) => Promise.Thenable, onReject?: (reason: any) => Promise.Thenable): Promise; 273 | spread(onFulfill: (...values: W[]) => Promise.Thenable, onReject?: (reason: any) => U): Promise; 274 | spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => Promise.Thenable): Promise; 275 | spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => U): Promise; 276 | */ 277 | /** 278 | * Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. 279 | */ 280 | // TODO type inference from array-resolving promise? 281 | all(): Promise; 282 | 283 | /** 284 | * Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. 285 | */ 286 | // TODO how to model instance.props()? 287 | props(): Promise; 288 | 289 | /** 290 | * Same as calling `Promise.settle(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. 291 | */ 292 | // TODO type inference from array-resolving promise? 293 | settle(): Promise[]>; 294 | 295 | /** 296 | * Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. 297 | */ 298 | // TODO type inference from array-resolving promise? 299 | any(): Promise; 300 | 301 | /** 302 | * Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. 303 | */ 304 | // TODO type inference from array-resolving promise? 305 | some(count: number): Promise; 306 | 307 | /** 308 | * Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. 309 | */ 310 | // TODO type inference from array-resolving promise? 311 | race(): Promise; 312 | 313 | /** 314 | * Same as calling `Promise.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. 315 | */ 316 | // TODO type inference from array-resolving promise? 317 | map(mapper: (item: Q, index: number, arrayLength: number) => Promise.Thenable): Promise; 318 | map(mapper: (item: Q, index: number, arrayLength: number) => U): Promise; 319 | 320 | /** 321 | * Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. 322 | */ 323 | // TODO type inference from array-resolving promise? 324 | reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; 325 | reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => U, initialValue?: U): Promise; 326 | 327 | /** 328 | * Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. 329 | */ 330 | // TODO type inference from array-resolving promise? 331 | filter(filterer: (item: U, index: number, arrayLength: number) => Promise.Thenable): Promise; 332 | filter(filterer: (item: U, index: number, arrayLength: number) => boolean): Promise; 333 | 334 | /** 335 | * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. 336 | * 337 | * Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. Otherwise it is passed as is as the first argument for the function call. 338 | * 339 | * Alias for `attempt();` for compatibility with earlier ECMAScript version. 340 | */ 341 | static try(fn: () => Promise.Thenable, args?: any[], ctx?: any): Promise; 342 | static try(fn: () => R, args?: any[], ctx?: any): Promise; 343 | 344 | static attempt(fn: () => Promise.Thenable, args?: any[], ctx?: any): Promise; 345 | static attempt(fn: () => R, args?: any[], ctx?: any): Promise; 346 | 347 | /** 348 | * Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function. 349 | * This method is convenient when a function can sometimes return synchronously or throw synchronously. 350 | */ 351 | static method(fn: Function): Function; 352 | 353 | /** 354 | * Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state. 355 | */ 356 | static resolve(): Promise; 357 | static resolve(value: Promise.Thenable): Promise; 358 | static resolve(value: R): Promise; 359 | 360 | /** 361 | * Create a promise that is rejected with the given `reason`. 362 | */ 363 | static reject(reason: any): Promise; 364 | static reject(reason: any): Promise; 365 | 366 | /** 367 | * Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution). 368 | */ 369 | static defer(): Promise.Resolver; 370 | 371 | /** 372 | * Cast the given `value` to a trusted promise. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable. 373 | */ 374 | static cast(value: Promise.Thenable): Promise; 375 | static cast(value: R): Promise; 376 | 377 | /** 378 | * Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`. 379 | */ 380 | static bind(thisArg: any): Promise; 381 | 382 | /** 383 | * See if `value` is a trusted Promise. 384 | */ 385 | static is(value: any): boolean; 386 | 387 | /** 388 | * Call this right after the library is loaded to enabled long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have alread been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency. 389 | */ 390 | static longStackTraces(): void; 391 | 392 | /** 393 | * Returns a promise that will be fulfilled with `value` (or `undefined`) after given `ms` milliseconds. If `value` is a promise, the delay will start counting down when it is fulfilled and the returned promise will be fulfilled with the fulfillment value of the `value` promise. 394 | */ 395 | // TODO enable more overloads 396 | static delay(value: Promise.Thenable, ms: number): Promise; 397 | static delay(value: R, ms: number): Promise; 398 | static delay(ms: number): Promise; 399 | 400 | /** 401 | * Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument. 402 | * 403 | * If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them. 404 | * 405 | * If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`. 406 | */ 407 | static promisify(func: (callback: (err:any, result: T) => void) => void, receiver?: any): () => Promise; 408 | static promisify(func: (arg1: A1, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1) => Promise; 409 | static promisify(func: (arg1: A1, arg2: A2, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2) => Promise; 410 | static promisify(func: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3) => Promise; 411 | static promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Promise; 412 | static promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Promise; 413 | static promisify(nodeFunction: Function, receiver?: any): Function; 414 | 415 | /** 416 | * Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name postfixed with `Async`. Returns the input object. 417 | * 418 | * Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method. 419 | */ 420 | // TODO how to model promisifyAll? 421 | static promisifyAll(target: Object): Object; 422 | 423 | /** 424 | * Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. 425 | */ 426 | // TODO fix coroutine GeneratorFunction 427 | static coroutine(generatorFunction: Function): Function; 428 | 429 | /** 430 | * Spawn a coroutine which may yield promises to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. 431 | */ 432 | // TODO fix spawn GeneratorFunction 433 | static spawn(generatorFunction: Function): Promise; 434 | 435 | /** 436 | * This is relevant to browser environments with no module loader. 437 | * 438 | * Release control of the `Promise` namespace to whatever it was before this library was loaded. Returns a reference to the library namespace so you can attach it to something else. 439 | */ 440 | static noConflict(): typeof Promise; 441 | 442 | /** 443 | * Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers. 444 | * 445 | * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. 446 | */ 447 | static onPossiblyUnhandledRejection(handler: (reason: any) => any): void; 448 | 449 | /** 450 | * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason. 451 | */ 452 | // TODO enable more overloads 453 | // promise of array with promises of value 454 | static all(values: Promise.Thenable[]>): Promise; 455 | // promise of array with values 456 | static all(values: Promise.Thenable): Promise; 457 | // array with promises of value 458 | static all(values: Promise.Thenable[]): Promise; 459 | // array with values 460 | static all(values: R[]): Promise; 461 | 462 | /** 463 | * Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason. 464 | * 465 | * If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties. 466 | * 467 | * *The original object is not modified.* 468 | */ 469 | // TODO verify this is correct 470 | // trusted promise for object 471 | static props(object: Promise): Promise; 472 | // object 473 | static props(object: Object): Promise; 474 | 475 | /** 476 | * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are either fulfilled or rejected. The fulfillment value is an array of ``PromiseInspection`` instances at respective positions in relation to the input array. 477 | * 478 | * *original: The array is not modified. The input array sparsity is retained in the resulting array.* 479 | */ 480 | // promise of array with promises of value 481 | static settle(values: Promise.Thenable[]>): Promise[]>; 482 | // promise of array with values 483 | static settle(values: Promise.Thenable): Promise[]>; 484 | // array with promises of value 485 | static settle(values: Promise.Thenable[]): Promise[]>; 486 | // array with values 487 | static settle(values: R[]): Promise[]>; 488 | 489 | /** 490 | * Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly. 491 | */ 492 | // promise of array with promises of value 493 | static any(values: Promise.Thenable[]>): Promise; 494 | // promise of array with values 495 | static any(values: Promise.Thenable): Promise; 496 | // array with promises of value 497 | static any(values: Promise.Thenable[]): Promise; 498 | // array with values 499 | static any(values: R[]): Promise; 500 | 501 | /** 502 | * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value. 503 | * 504 | * **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending. 505 | */ 506 | // promise of array with promises of value 507 | static race(values: Promise.Thenable[]>): Promise; 508 | // promise of array with values 509 | static race(values: Promise.Thenable): Promise; 510 | // array with promises of value 511 | static race(values: Promise.Thenable[]): Promise; 512 | // array with values 513 | static race(values: R[]): Promise; 514 | 515 | /** 516 | * Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution. 517 | * 518 | * If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in. 519 | * 520 | * *The original array is not modified.* 521 | */ 522 | // promise of array with promises of value 523 | static some(values: Promise.Thenable[]>, count: number): Promise; 524 | // promise of array with values 525 | static some(values: Promise.Thenable, count: number): Promise; 526 | // array with promises of value 527 | static some(values: Promise.Thenable[], count: number): Promise; 528 | // array with values 529 | static some(values: R[], count: number): Promise; 530 | 531 | /** 532 | * Like `Promise.all()` but instead of having to pass an array, the array is generated from the passed variadic arguments. 533 | */ 534 | // variadic array with promises of value 535 | static join(...values: Promise.Thenable[]): Promise; 536 | // variadic array with values 537 | static join(...values: R[]): Promise; 538 | 539 | /** 540 | * Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. 541 | * 542 | * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. 543 | * 544 | * *The original array is not modified.* 545 | */ 546 | // promise of array with promises of value 547 | static map(values: Promise.Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; 548 | static map(values: Promise.Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => U): Promise; 549 | 550 | // promise of array with values 551 | static map(values: Promise.Thenable, mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; 552 | static map(values: Promise.Thenable, mapper: (item: R, index: number, arrayLength: number) => U): Promise; 553 | 554 | // array with promises of value 555 | static map(values: Promise.Thenable[], mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; 556 | static map(values: Promise.Thenable[], mapper: (item: R, index: number, arrayLength: number) => U): Promise; 557 | 558 | // array with values 559 | static map(values: R[], mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; 560 | static map(values: R[], mapper: (item: R, index: number, arrayLength: number) => U): Promise; 561 | 562 | /** 563 | * Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. 564 | * 565 | * If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. 566 | * 567 | * *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.* 568 | */ 569 | // promise of array with promises of value 570 | static reduce(values: Promise.Thenable[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; 571 | static reduce(values: Promise.Thenable[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; 572 | 573 | // promise of array with values 574 | static reduce(values: Promise.Thenable, reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; 575 | static reduce(values: Promise.Thenable, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; 576 | 577 | // array with promises of value 578 | static reduce(values: Promise.Thenable[], reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; 579 | static reduce(values: Promise.Thenable[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; 580 | 581 | // array with values 582 | static reduce(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; 583 | static reduce(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; 584 | 585 | /** 586 | * Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. 587 | * 588 | * The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result. 589 | * 590 | * *The original array is not modified. 591 | */ 592 | // promise of array with promises of value 593 | static filter(values: Promise.Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; 594 | static filter(values: Promise.Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; 595 | 596 | // promise of array with values 597 | static filter(values: Promise.Thenable, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; 598 | static filter(values: Promise.Thenable, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; 599 | 600 | // array with promises of value 601 | static filter(values: Promise.Thenable[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; 602 | static filter(values: Promise.Thenable[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; 603 | 604 | // array with values 605 | static filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; 606 | static filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; 607 | } 608 | 609 | declare module Promise { 610 | export interface RangeError extends Error { 611 | } 612 | export interface CancellationError extends Error { 613 | } 614 | export interface TimeoutError extends Error { 615 | } 616 | export interface TypeError extends Error { 617 | } 618 | export interface RejectionError extends Error { 619 | } 620 | export interface OperationalError extends Error { 621 | } 622 | 623 | // Ideally, we'd define e.g. "export class RangeError extends Error {}", 624 | // but as Error is defined as an interface (not a class), TypeScript doesn't 625 | // allow extending Error, only implementing it. 626 | // However, if we want to catch() only a specific error type, we need to pass 627 | // a constructor function to it. So, as a workaround, we define them here as such. 628 | export function RangeError(): RangeError; 629 | export function CancellationError(): CancellationError; 630 | export function TimeoutError(): TimeoutError; 631 | export function TypeError(): TypeError; 632 | export function RejectionError(): RejectionError; 633 | export function OperationalError(): OperationalError; 634 | 635 | export interface Thenable { 636 | then(onFulfilled: (value: R) => Thenable, onRejected: (error: any) => Thenable): Thenable; 637 | then(onFulfilled: (value: R) => Thenable, onRejected?: (error: any) => U): Thenable; 638 | then(onFulfilled: (value: R) => U, onRejected: (error: any) => Thenable): Thenable; 639 | then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): Thenable; 640 | } 641 | 642 | export interface Resolver { 643 | /** 644 | * Returns a reference to the controlled promise that can be passed to clients. 645 | */ 646 | promise: Promise; 647 | 648 | /** 649 | * Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state. 650 | */ 651 | resolve(value: R): void; 652 | resolve(): void; 653 | 654 | /** 655 | * Reject the underlying promise with `reason` as the rejection reason. 656 | */ 657 | reject(reason: any): void; 658 | 659 | /** 660 | * Progress the underlying promise with `value` as the progression value. 661 | */ 662 | progress(value: any): void; 663 | 664 | /** 665 | * Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property. The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions. 666 | * 667 | * If the the callback is called with multiple success values, the resolver fullfills its promise with an array of the values. 668 | */ 669 | // TODO specify resolver callback 670 | callback: (err: any, value: R, ...values: R[]) => void; 671 | } 672 | 673 | export interface Inspection { 674 | /** 675 | * See if the underlying promise was fulfilled at the creation time of this inspection object. 676 | */ 677 | isFulfilled(): boolean; 678 | 679 | /** 680 | * See if the underlying promise was rejected at the creation time of this inspection object. 681 | */ 682 | isRejected(): boolean; 683 | 684 | /** 685 | * See if the underlying promise was defer at the creation time of this inspection object. 686 | */ 687 | isPending(): boolean; 688 | 689 | /** 690 | * Get the fulfillment value of the underlying promise. Throws if the promise wasn't fulfilled at the creation time of this inspection object. 691 | * 692 | * throws `TypeError` 693 | */ 694 | value(): R; 695 | 696 | /** 697 | * Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object. 698 | * 699 | * throws `TypeError` 700 | */ 701 | reason(): any; 702 | } 703 | 704 | /** 705 | * Changes how bluebird schedules calls a-synchronously. 706 | * 707 | * @param scheduler Should be a function that asynchronously schedules 708 | * the calling of the passed in function 709 | */ 710 | export function setScheduler(scheduler: (callback: (...args: any[]) => void) => void): void; 711 | } 712 | 713 | declare module 'bluebird' { 714 | export = Promise; 715 | } -------------------------------------------------------------------------------- /typings/lib.support.d.ts: -------------------------------------------------------------------------------- 1 | interface ArrayBuffer { 2 | //byteLength: number; 3 | slice(begin:number, end?:number): ArrayBuffer; 4 | } 5 | 6 | interface ArrayBufferConstructor { 7 | //prototype: ArrayBuffer; 8 | new (byteLength: number): ArrayBuffer; 9 | isView(arg: any): boolean; 10 | } 11 | declare var ArrayBuffer: ArrayBufferConstructor; 12 | 13 | interface Uint8Array { 14 | // BYTES_PER_ELEMENT: number; 15 | // buffer: ArrayBuffer; 16 | // byteLength: number; 17 | // byteOffset: number; 18 | copyWithin(target: number, start: number, end?: number): Uint8Array; 19 | every(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; 20 | fill(value: number, start?: number, end?: number): Uint8Array; 21 | filter(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): Uint8Array; 22 | find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; 23 | findIndex(predicate: (value: number) => boolean, thisArg?: any): number; 24 | forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void; 25 | indexOf(searchElement: number, fromIndex?: number): number; 26 | join(separator?: string): string; 27 | lastIndexOf(searchElement: number, fromIndex?: number): number; 28 | // length: number; 29 | map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; 30 | reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; 31 | reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; 32 | reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; 33 | reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; 34 | reverse(): Uint8Array; 35 | set(index: number, value: number): void; 36 | set(array: Uint8Array, offset?: number): void; 37 | slice(start?: number, end?: number): Uint8Array; 38 | some(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; 39 | sort(compareFn?: (a: number, b: number) => number): Uint8Array; 40 | subarray(begin: number, end?: number): Uint8Array; 41 | toLocaleString(): string; 42 | toString(): string; 43 | //[index: number]: number; 44 | } 45 | 46 | interface Uint8ArrayConstructor { 47 | // prototype: Uint8Array; 48 | new (length: number): Uint8Array; 49 | new (array: Uint8Array): Uint8Array; 50 | new (array: number[]): Uint8Array; 51 | new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; 52 | // BYTES_PER_ELEMENT: number; 53 | of(...items: number[]): Uint8Array; 54 | } 55 | declare var Uint8Array: Uint8ArrayConstructor; 56 | 57 | interface Console { 58 | assert(test?: boolean, message?: string, ...optionalParams: any[]): void; 59 | clear(): void; 60 | count(countTitle?: string): void; 61 | debug(message?: string, ...optionalParams: any[]): void; 62 | dir(value?: any, ...optionalParams: any[]): void; 63 | dirxml(value: any): void; 64 | error(message?: any, ...optionalParams: any[]): void; 65 | group(groupTitle?: string): void; 66 | groupCollapsed(groupTitle?: string): void; 67 | groupEnd(): void; 68 | info(message?: any, ...optionalParams: any[]): void; 69 | log(message?: any, ...optionalParams: any[]): void; 70 | profile(reportName?: string): void; 71 | profileEnd(): void; 72 | time(timerName?: string): void; 73 | timeEnd(timerName?: string): void; 74 | trace(): void; 75 | warn(message?: any, ...optionalParams: any[]): void; 76 | } 77 | 78 | declare var Console: { 79 | prototype: Console; 80 | new(): Console; 81 | } 82 | declare var console: Console; --------------------------------------------------------------------------------