'use strict';

const exec = require('child_process').execSync;
const glob = require('glob').sync;
const fse = require('fs-extra');
const path = require('path');

const buildConfig = require('../build.json');

// We run the Typescript Compiler from the node modules because we want to be consistent
// with the compiler version.
const TSC_BIN = './node_modules/typescript/bin/tsc';
const PROJECT_ROOT = path.join(__dirname, '..');
const OUTPUT_DIRECTORY = path.resolve(PROJECT_ROOT, buildConfig.outDir);

buildConfig.copyFiles.forEach(pattern => {
  let files = glob(pattern, { cwd: PROJECT_ROOT });

  files.forEach(file => {
    fse.copySync(path.join(PROJECT_ROOT, file), path.join(OUTPUT_DIRECTORY, file));
  });
});

// Retrieve all source files.
let sourceFiles = buildConfig.tsFiles
  .map(pattern => glob(pattern, { cwd: PROJECT_ROOT }))
  .reduce((array, item) => array.concat(item), []);

try {
  exec(`node ${TSC_BIN} --declaration ${sourceFiles.join(' ')} --outDir ${OUTPUT_DIRECTORY}`, {
    cwd: PROJECT_ROOT
  });

  console.log("Build: Successfully compiled the TypeScript files into ES5.");
} catch (e) {
  console.error("Error: An error occurred while compiling the TypeScript files into ES5.");
  throw e;
}

@@ -14,57 +14,8 @@
 %0D%0A%0D%0A
-const exec = require('child_process').execSync;%0D%0A
 cons
@@ -110,16 +110,51 @@
 path');%0D
+%0Aconst ts = require('typescript');%0D
 %0A%0D%0Aconst
@@ -909,233 +909,694 @@
 %0D%0A%0D%0A
-try %7B%0D%0A  exec(%60node $%7BTSC_BIN%7D --declaration $%7BsourceFiles.join(' ')%7D --outDir $%7BOUTPUT_DIRECTORY%7D%60, %7B%0D%0A    cwd: PROJECT_ROOT%0D%0A  %7D);%0D%0A%0D%0A  console.log(%22Build: Successfully compiled the TypeScript files into ES5.%22
+/**%0D%0A * TypeScript Compilation with Language Service.%0D%0A */%0D%0Alet tsProject = ts.convertCompilerOptionsFromJson(require('../tsconfig.json').compilerOptions);%0D%0Alet tsProgram = ts.createProgram(sourceFiles, tsProject.options);%0D%0Alet emitResult = tsProgram.emit();%0D%0A%0D%0Alet compileErrors = ts.getPreEmitDiagnostics(tsProgram).concat(emitResult.diagnostics);%0D%0A%0D%0AcompileErrors.forEach(diagnostic =%3E %7B%0D%0A  let lineResults = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);%0D%0A  let errorMessage = ts.flattenDiagnosticMessageText(diagnostic.messageText, '%5Cn'
 );%0D%0A
-%7D catch (e
+  console.error(%60$%7Bdiagnostic.file.fileName%7D@$%7BlineResults.line + 1%7D: $%7BerrorMessage%7D%60);%0D%0A%7D);%0D%0A%0D%0Aif (emitResult.emitSkipped
 ) %7B%0D
@@ -1616,14 +1616,14 @@
 ror(
-%22Error
+'Build
 : An
@@ -1662,50 +1662,109 @@
 the 
-TypeScript files into ES5.%22);%0D%0A  throw e
+project.');%0D%0A  process.exit(1);%0D%0A%7D else %7B%0D%0A  console.log(%60Build: Successfully compiled the project.%60)
 ;%0D%0A%7D
-%0D%0A

use typescript language service to compile project (#12)