public void CanCompileTypeScriptWithSourceMap() { var filePath = PathHelper.GetScript("simple.ts"); var options = new TypeScriptV1CompilerOptions() { SourceMap = true }; var compiler = new TypeScriptCompiler(); var result = compiler.Compile(new[] { filePath }, options); Assert.IsTrue(result.IsSuccess); var outFile = PathHelper.GetScript("simple.js"); var outMap = PathHelper.GetScript("simple.js.map"); var resultSource = File.ReadAllText(outFile); var resultMap = File.ReadAllText(outMap); var expectedResult = "\r\n// Module\r\nvar Shapes;\r\n(function (Shapes) {\r\n // Class\r\n var Point = (function () {\r\n // Constructor\r\n function Point(x, y) {\r\n this.x = x;\r\n this.y = y;\r\n }\r\n // Instance member\r\n Point.prototype.getDist = function () {\r\n return Math.sqrt(this.x * this.x + this.y * this.y);\r\n };\r\n\r\n Point.origin = new Point(0, 0);\r\n return Point;\r\n })();\r\n Shapes.Point = Point;\r\n})(Shapes || (Shapes = {}));\r\n\r\n// Local variables\r\nvar p = new Shapes.Point(3, 4);\r\nvar dist = p.getDist();\r\n//# sourceMappingURL=simple.js.map\r\n"; var expectedMap = "{\"version\":3,\"file\":\"simple.js\",\"sourceRoot\":\"\",\"sources\":[\"simple.ts\"],\"names\":[\"Shapes\",\"Shapes.Point\",\"Shapes.Point.constructor\",\"Shapes.Point.getDist\"],\"mappings\":\";AAKA,SAAS;AACT,IAAO,MAAM;AAaZ,CAbD,UAAO,MAAM;IAETA,QAAQA;IACRA;QAEIC,cADcA;QACdA,eAAaA,CAAgBA,EAAEA,CAAgBA;YAAlCC,MAAQA,GAADA,CAACA;AAAQA,YAAEA,MAAQA,GAADA,CAACA;AAAQA,QAAIA,CAACA;QAGpDD,kBADYA;kCACZA;YAAYE,OAAOA,IAAIA,CAACA,IAAIA,CAACA,IAAIA,CAACA,CAACA,GAAGA,IAAIA,CAACA,CAACA,GAAGA,IAAIA,CAACA,CAACA,GAAGA,IAAIA,CAACA,CAACA,CAACA;QAAEA,CAACA;;QAGlEF,eAAgBA,IAAIA,KAAKA,CAACA,CAACA,EAAEA,CAACA,CAACA;QACnCA,aAACA;IAADA,CAACA,IAAAD;IATDA,qBASCA;AACLA,CAACA,2BAAA;;AAED,kBAAkB;AAClB,IAAI,CAAC,GAAW,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;AACtC,IAAI,IAAI,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC\"}"; Assert.AreEqual(expectedResult, resultSource); Assert.AreEqual(expectedMap, resultMap); // Clean up File.Delete(outFile); File.Delete(outMap); }
public void TryParseDiagnostics_WithInvalidData_ReturnsExpectedResult() { string input = $"abcde(8,4) : test : test"; bool parsed = TypeScriptCompiler.TryParseDiagnostic(input, out Diagnostic diagnostic); Assert.False(parsed); }
public void CoffeeScriptFailTest() { var input = "test.invlid.stuff/^/g!%%"; using (var fixture = new TypeScriptCompiler(new InstanceProvider <IJavaScriptRuntime>( () => new IEJavaScriptRuntime()))) { bool shouldDie = false; try { var result = fixture.Compile(input); if (result.StartsWith("ENGINE FAULT")) { shouldDie = true; } else { Console.WriteLine(result); } } catch (Exception ex) { Console.WriteLine("Ex: " + ex.Message); shouldDie = true; } Assert.True(shouldDie); } }
/// <summary> /// This function is the callback used to execute the command when the menu item is clicked. /// See the constructor to see how the menu item is associated with this function using /// OleMenuCommandService service and MenuCommand class. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event args.</param> private void MenuItemCallback(object sender, EventArgs e) { try { IVsHierarchy hierarchy = null; uint itemid = VSConstants.VSITEMID_NIL; if (!TsWspHelpers.IsSingleProjectItemSelection(out hierarchy, out itemid)) { return; } var vsProject = (IVsProject)hierarchy; // get the name of the item string itemFullPath = null; if (ErrorHandler.Failed(vsProject.GetMkDocument(itemid, out itemFullPath))) { return; } TypeScriptCompiler.Compile(itemFullPath); } catch (Exception ex) { Logger.Log(ex); } }
public TypeScriptProject(IPackage package, string projectPath) { this.package = package ?? throw new ArgumentNullException(nameof(package)); ProjectPath = projectPath ?? throw new ArgumentNullException(nameof(projectPath)); this.compiler = new TypeScriptCompiler(projectPath); }
/// <summary> /// Translates a code of assets written on TypeScript to JS code /// </summary> /// <param name="assets">Set of assets with code written on TypeScript</param> /// <returns>Set of assets with translated code</returns> public IList <IAsset> Translate(IList <IAsset> assets) { if (assets == null) { throw new ArgumentException(CoreStrings.Common_ValueIsEmpty, "assets"); } if (assets.Count == 0) { return(assets); } var assetsToProcessing = assets.Where(a => a.AssetTypeCode == Constants.AssetTypeCode.TypeScript).ToList(); if (assetsToProcessing.Count == 0) { return(assets); } CompilationOptions options = CreateCompilationOptions(); using (var typeScriptCompiler = new TypeScriptCompiler(_createJsEngineInstance, _virtualFileManager, options)) { foreach (var asset in assetsToProcessing) { InnerTranslate(asset, typeScriptCompiler); } } return(assets); }
public void CanCompileMultipleTypeScript() { var filePath1 = PathHelper.GetScript("A.ts"); var filePath2 = PathHelper.GetScript("Q.ts"); var options = new TypeScriptV1CompilerOptions() { Target = TypeScriptCompilerTarget.ES5 }; var compiler = new TypeScriptCompiler(); var result = compiler.Compile(new[] { filePath1, filePath2 }, options); Assert.IsTrue(result.IsSuccess); var outFile1 = PathHelper.GetScript("A.js"); var outFile2 = PathHelper.GetScript("Q.js"); var resultSource1 = File.ReadAllText(outFile1); var resultSource2 = File.ReadAllText(outFile2); var expectedResult1 = "var A;\r\n(function (A) {\r\n var Foo = (function () {\r\n function Foo() {\r\n }\r\n Foo.prototype.bar = function () {\r\n alert(\"Foo\");\r\n };\r\n return Foo;\r\n })();\r\n A.Foo = Foo;\r\n})(A || (A = {}));\r\n"; var expectedResult2 = "var Q;\r\n(function (Q) {\r\n var Bar = (function () {\r\n function Bar() {\r\n }\r\n Bar.prototype.bar = function () {\r\n alert(\"bar\");\r\n };\r\n\r\n Object.defineProperty(Bar.prototype, \"getter\", {\r\n get: function () {\r\n return \"123\";\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n return Bar;\r\n })();\r\n Q.Bar = Bar;\r\n})(Q || (Q = {}));\r\n"; Assert.AreEqual(expectedResult1, resultSource1); Assert.AreEqual(expectedResult2, resultSource2); // Clean up File.Delete(outFile1); File.Delete(outFile2); }
private void InnerTranslate(IAsset asset, TypeScriptCompiler typeScriptCompiler) { string newContent; string assetUrl = asset.Url; IList <string> dependencies; try { CompilationResult result = typeScriptCompiler.Compile(assetUrl); newContent = result.CompiledContent; dependencies = result.IncludedFilePaths; } catch (TypeScriptCompilationException e) { throw new AssetTranslationException( string.Format(CoreStrings.Translators_TranslationSyntaxError, INPUT_CODE_TYPE, OUTPUT_CODE_TYPE, assetUrl, e.Message)); } catch (Exception e) { throw new AssetTranslationException( string.Format(CoreStrings.Translators_TranslationFailed, INPUT_CODE_TYPE, OUTPUT_CODE_TYPE, assetUrl, e.Message)); } asset.Content = newContent; asset.VirtualPathDependencies = dependencies; }
private void DocumentSaved(object sender, TextDocumentFileActionEventArgs e) { if (e.FileActionType == FileActionTypes.ContentSavedToDisk) { string sourceFile = e.FilePath; TypeScriptCompiler.Compile(sourceFile); } }
public static string GetSignature(TypeScriptCompiler compiler, MethodDeclaration methodDeclaration, string methodNameSuffix = "") { var modifiers = GetModifiers(compiler, methodDeclaration); var methodName = methodDeclaration.Name.Data; var methodArguments = GetArguments(compiler, methodDeclaration); var returnType = GetReturnType(compiler, methodDeclaration); var arrayDepth = GetArrayDepth(methodDeclaration); return string.Format("{0}{1}{2}({3}): {4}{5}", modifiers, methodName, methodNameSuffix, methodArguments, returnType, arrayDepth); }
public void CoffeeScriptSmokeTest() { var input = @"var foo:number = 5;"; using (var fixture = new TypeScriptCompiler(new InstanceProvider <IJavaScriptRuntime>( () => new IEJavaScriptRuntime()))) { var result = fixture.Compile(input); Assert.False(String.IsNullOrWhiteSpace(result)); } }
public void TypeScriptSmokeTest() { var code = @"var foo:number = 5;"; var input = @"{""someFile.ts"":""" + code + @"""}"; using (var fixture = new TypeScriptCompiler(new Lazy <IJavaScriptRuntime>(() => new IEJavaScriptRuntime()))) { var result = fixture.Compile(input); Assert.False(String.IsNullOrWhiteSpace(result)); } }
public void CompilerResultContainsError() { var filePath = PathHelper.GetScript("error.ts"); var options = new TypeScriptV1CompilerOptions() { }; var compiler = new TypeScriptCompiler(); var result = compiler.Compile(new[] { filePath }, options); Assert.IsFalse(result.IsSuccess); Assert.IsFalse(String.IsNullOrEmpty(result.Error)); }
public void TryParseDiagnostics_ReturnsExpectedResult() { string filename = "index.ts"; int line = 8; int column = 5; string level = "error"; string code = "TS2304"; string message = "Cannot find name 'something'"; string input = $"{filename}({line},{column}): {level} {code}: {message}"; bool parsed = TypeScriptCompiler.TryParseDiagnostic(input, out Diagnostic diagnostic); Assert.True(parsed); Assert.Equal(code, diagnostic.Id); Assert.Equal(DiagnosticSeverity.Error, diagnostic.Severity); Assert.Equal(filename, diagnostic.Location.GetLineSpan().Path); Assert.Equal(input, diagnostic.ToString()); }
/// <summary> /// Translates a code of asset written on TypeScript to JS code /// </summary> /// <param name="asset">Asset with code written on TypeScript</param> /// <returns>Asset with translated code</returns> public IAsset Translate(IAsset asset) { if (asset == null) { throw new ArgumentException(CoreStrings.Common_ValueIsEmpty, "asset"); } CompilationOptions options = CreateCompilationOptions(); using (var typeScriptCompiler = new TypeScriptCompiler(_createJsEngineInstance, _virtualFileManager, options)) { InnerTranslate(asset, typeScriptCompiler); } return(asset); }
private static async Task MainAsync() { //Create a new Compiler instance (it has yet to be initialized) var compiler = new TypeScriptCompiler(); Console.WriteLine("Compiling compiler..."); //InitializeCompilerAsync() loads the compiler from a resource //and compiles it. This is relatively resource expensive; it can //take a few seconds to compile the TypeScript compiler and //quite a few MB of RAM. //Right now, NTypeScript uses JurassicJS as its engine, because //Jurassic compiles to IL code. //Once the compiler is compiled, the compiler can be used to compile //TypeScript. await compiler.InitializeCompilerAsync(); string helloWorldScript = @" class RandomProgram { sayHello() { console.log(""Hello, World!""); } } let myProgram = new RandomProgram(); myProgram.sayHello(); "; Console.WriteLine("Compiling Hello World script..."); //This will compile the script with the compiler that was //compiled earlier. This isn't too resource intensive, but //takes about the same amount of time as the normal TypeScript //compiler running in Node.JS var transpiledHelloWorldScript = await compiler.CompileAsync(helloWorldScript); Console.WriteLine(transpiledHelloWorldScript); //Run the script var jsExecutor = new JavaScriptExecutor(); jsExecutor.EnableConsoleApi(); await jsExecutor.ExecuteAsync(transpiledHelloWorldScript); }
/// <summary> /// Translates a code of asset written on TypeScript to JS code /// </summary> /// <param name="asset">Asset with code written on TypeScript</param> /// <returns>Asset with translated code</returns> public IAsset Translate(IAsset asset) { if (asset == null) { throw new ArgumentNullException( nameof(asset), string.Format(CoreStrings.Common_ArgumentIsNull, nameof(asset)) ); } CompilationOptions options = CreateCompilationOptions(); using (var typeScriptCompiler = new TypeScriptCompiler(_createJsEngineInstance, _virtualFileManager, options)) { InnerTranslate(asset, typeScriptCompiler); } return(asset); }
/// <summary> /// Processes a single item. /// </summary> /// <param name="input">The input to process.</param> /// <returns>The output of the process.</returns> public override IAssetFile Process(IAssetFile input) { try { // !!!!!!!! // NOT USED // !!!!!!!! // Only processes .ts files if (input.Extension != ".ts") { return(input); } // Measure var watch = new Stopwatch(); watch.Start(); // compiles a TS file var output = TypeScriptCompiler.Compile(input.Content.AsString()); // We've compiled watch.Stop(); // Compiled successfully Tracing.Info("TypeScript", "Compiled " + input.RelativeName + ", " + watch.ElapsedMilliseconds + " ms."); // Return processed output return(AssetOutputFile.Create( from: input, content: output, extension: "js" )); } catch (Exception ex) { // We didn't manage to create anything Tracing.Error("TypeScript", ex); return(null); } }
public void CanCompileTypeScript() { var filePath = PathHelper.GetScript("simple.ts"); var options = new TypeScriptV1CompilerOptions() { }; var compiler = new TypeScriptCompiler(); var result = compiler.Compile(new[] { filePath }, options); Assert.IsTrue(result.IsSuccess); var outFile = PathHelper.GetScript("simple.js"); var resultSource = File.ReadAllText(PathHelper.GetScript(outFile)); var expectedResult = "\r\n// Module\r\nvar Shapes;\r\n(function (Shapes) {\r\n // Class\r\n var Point = (function () {\r\n // Constructor\r\n function Point(x, y) {\r\n this.x = x;\r\n this.y = y;\r\n }\r\n // Instance member\r\n Point.prototype.getDist = function () {\r\n return Math.sqrt(this.x * this.x + this.y * this.y);\r\n };\r\n\r\n Point.origin = new Point(0, 0);\r\n return Point;\r\n })();\r\n Shapes.Point = Point;\r\n})(Shapes || (Shapes = {}));\r\n\r\n// Local variables\r\nvar p = new Shapes.Point(3, 4);\r\nvar dist = p.getDist();\r\n"; Assert.AreEqual(expectedResult, resultSource); // Clean up File.Delete(outFile); }
private static string GetModifiers(TypeScriptCompiler compiler, MethodDeclaration methodDeclaration) { var modifiers = new List<string>(); var methodDetail = GetMethodDetail(compiler, methodDeclaration); modifiers.Add( methodDetail.NeedsExtending() || methodDetail.GetDependantMethods().Any() || (methodDeclaration.Modifiers != null && methodDeclaration.Modifiers.All(x => x.Data != Keywords.Private)) ? Keywords.Public : Keywords.Private); if (methodDeclaration.Modifiers != null && methodDeclaration.Modifiers.Any(x => x.Data == Keywords.Static)) { modifiers.Add(Keywords.Static); } return modifiers.Aggregate((x, y) => x + " " + y) + " "; }
/// <summary> /// Translates a code of assets written on TypeScript to JS-code /// </summary> /// <param name="assets">Set of assets with code written on TypeScript</param> /// <returns>Set of assets with translated code</returns> public IList<IAsset> Translate(IList<IAsset> assets) { if (assets == null) { throw new ArgumentException(CoreStrings.Common_ValueIsEmpty, "assets"); } if (assets.Count == 0) { return assets; } var assetsToProcessing = assets.Where(a => a.AssetTypeCode == Constants.AssetTypeCode.TypeScript).ToList(); if (assetsToProcessing.Count == 0) { return assets; } lock (_translationSynchronizer) { CompilationOptions options = CreateCompilationOptions(); var typeScriptCompiler = new TypeScriptCompiler(_createJsEngineInstance, options); ClearTsScriptCache(); try { foreach (var asset in assetsToProcessing) { InnerTranslate(asset, typeScriptCompiler); } } finally { typeScriptCompiler.Dispose(); ClearTsScriptCache(); } } return assets; }
/// <summary> /// Translates a code of asset written on TypeScript to JS-code /// </summary> /// <param name="asset">Asset with code written on TypeScript</param> /// <returns>Asset with translated code</returns> public IAsset Translate(IAsset asset) { if (asset == null) { throw new ArgumentException(CoreStrings.Common_ValueIsEmpty, "asset"); } lock (_translationSynchronizer) { CompilationOptions options = CreateCompilationOptions(); var typeScriptCompiler = new TypeScriptCompiler(_createJsEngineInstance, options); ClearTsScriptCache(); try { InnerTranslate(asset, typeScriptCompiler); } finally { typeScriptCompiler.Dispose(); ClearTsScriptCache(); } } return asset; }
private void InnerTranslate(IAsset asset, TypeScriptCompiler typeScriptCompiler) { string newContent; string assetUrl = asset.Url; var dependencies = new DependencyCollection(); try { TsScript script = GetTsScript(asset); FillDependencies(assetUrl, script, dependencies); newContent = typeScriptCompiler.Compile(script.Content, script.Url, dependencies); newContent = RemoveReferenceComments(newContent); } catch (TypeScriptCompilingException e) { throw new AssetTranslationException( string.Format(CoreStrings.Translators_TranslationSyntaxError, INPUT_CODE_TYPE, OUTPUT_CODE_TYPE, assetUrl, e.Message)); } catch (Exception e) { throw new AssetTranslationException( string.Format(CoreStrings.Translators_TranslationFailed, INPUT_CODE_TYPE, OUTPUT_CODE_TYPE, assetUrl, e.Message)); } asset.Content = newContent; asset.VirtualPathDependencies = dependencies .Where(d => d.IsObservable) .Select(d => d.Url) .Distinct() .ToList() ; }
private static string GetArguments(TypeScriptCompiler compiler, MethodDeclaration methodDeclaration) { return methodDeclaration.Arguments == null || methodDeclaration.Arguments.Count == 0 ? string.Empty : methodDeclaration.Arguments .Select(x => compiler.GetMethodArgumentString(x)) .Aggregate((x, y) => x + ", " + y); }
public MethodDeclarationCompiler(ICompiler compiler, MethodDeclaration methodDeclaration) { _compiler = (TypeScriptCompiler)compiler; _methodDeclaration = methodDeclaration; }
private static string GetReturnType(TypeScriptCompiler compiler, MethodDeclaration methodDeclaration) { return methodDeclaration.ReturnType == null ? string.Empty : compiler.GetTypeString(methodDeclaration.ReturnType, "MethodDeclarationCompiler -> GetReturnType"); }
public void RunTests(IEnumerable <Microsoft.VisualStudio.TestPlatform.ObjectModel.TestCase> tests, IRunContext runContext, IFrameworkHandle frameworkHandle) { var olock = new Object(); var cache = new Dictionary <string, string>(); Parallel.ForEach(tests, test => { var result = new TestResult(test); // full path to temporary file string filePath = Path.ChangeExtension(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + DateTime.Now.ToString("HH-mm-ss-fff")), ".js"); try { lock (olock) { if (!cache.ContainsKey(test.CodeFilePath)) { TypeScriptCompiler.Compile(test.CodeFilePath, new TypeScriptCompiler.Options(outPath: filePath)); cache.Add(test.CodeFilePath, filePath); } else { filePath = cache[test.CodeFilePath]; } } var testResult = new JSRunner.TestResult(); var scriptFilePath = filePath + Guid.NewGuid().ToString("N") + "exec.js"; using (var fs = new FileStream(scriptFilePath, FileMode.Create)) { using (var sw = new StreamWriter(fs)) { sw.WriteLine("try{"); sw.Write(File.ReadAllText(filePath)); var className = test.FullyQualifiedName.Substring(0, test.FullyQualifiedName.LastIndexOf(".")); var methodName = test.FullyQualifiedName.Substring(test.FullyQualifiedName.LastIndexOf(".") + 1); sw.WriteLine("var ____TSTestExecutor____ = new " + className + "();____TSTestExecutor____." + methodName + "();"); sw.WriteLine("phantom.exit(0)}catch(ex){console.log(ex);phantom.exit(-1)}"); sw.Flush(); } } testResult = JSRunner.Run(scriptFilePath); result.Outcome = testResult.Outcome; if (result.Outcome != TestOutcome.Passed) { result.ErrorMessage = testResult.Output; } try { File.Delete(scriptFilePath); } catch { } } catch (InvalidTypeScriptFileException ex) { result.Outcome = TestOutcome.Failed; result.ErrorMessage = ex.Message; } catch (Exception ex) { result.Outcome = TestOutcome.Failed; result.ErrorMessage = ex.Message + ex.StackTrace; } frameworkHandle.RecordResult(result); }); foreach (KeyValuePair <string, string> item in cache) { try { File.Delete(item.Value); } catch { } } }