Exemplo n.º 1
0
        public void CompileWithComplexScriptSucceeds()
        {
            string source = @"# Assignment:
number   = 42
opposite = true

# Conditions:
number = -42 if opposite

# Functions:
square = (x) -> x * x

# Arrays:
list = [1, 2, 3, 4, 5]

# Objects:
math =
  root:   Math.sqrt
  square: square
  cube:   (x) -> x * square x

# Splats:
race = (winner, runners...) ->
  print winner, runners

# Existence:
alert 'I knew it!' if elvis?";

            var compiler = new CoffeeScriptCompiler();

            compiler.Compile(source);
        }
Exemplo n.º 2
0
 public void CompileFile_with_valid_CoffeeScript_returns_JavaScript()
 {
     var source = "x = 1";
     var compiler = new CoffeeScriptCompiler();
     var javaScript = compiler.Compile(source, Mock.Of<IFile>());
     javaScript.ShouldEqual("(function() {\n  var x;\n  x = 1;\n}).call(this);\n");
 }
        public void CoffeeScriptFailTest()
        {
            var input = "test.invlid.stuff/^/g!%%";

            using (var fixture = new CoffeeScriptCompiler(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>
        /// Translates a code of assets written on CoffeeScript to JS code
        /// </summary>
        /// <param name="assets">Set of assets with code written on CoffeeScript</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.CoffeeScript ||
                                                  a.AssetTypeCode == Constants.AssetTypeCode.LiterateCoffeeScript).ToList();

            if (assetsToProcessing.Count == 0)
            {
                return(assets);
            }

            CompilationOptions options = CreateCompilationOptions();

            using (var coffeeScriptCompiler = new CoffeeScriptCompiler(_createJsEngineInstance, options))
            {
                foreach (var asset in assetsToProcessing)
                {
                    InnerTranslate(asset, coffeeScriptCompiler);
                }
            }

            return(assets);
        }
Exemplo n.º 5
0
        public void CompileFailsGracefullyOnMono()
        {
            var compiler  = new CoffeeScriptCompiler();
            var exception = Assert.Throws(typeof(NotSupportedException), () => compiler.Compile(""));

            Assert.AreEqual("Coffeescript not yet supported for mono.", exception.Message);
        }
Exemplo n.º 6
0
 public override IProcessResult Process(string filePath, string content)
 {
     using (var compiler = new CoffeeScriptCompiler())
     {
         return(new ProcessResult(compiler.Compile(content)));
     }
 }
Exemplo n.º 7
0
        public void CompileWithSimpleAlertSucceeds()
        {
            var compiler = new CoffeeScriptCompiler();

            string result = compiler.Compile("alert 'test' ");

            Assert.AreEqual("(function() {\n  alert('test');\n}).call(this);\n", result);
        }
        public void CoffeeScriptSmokeTest()
        {
            var input = @"v = x*5 for x in [1...10]";
            var fixture = new CoffeeScriptCompiler();

            var result = fixture.Compile(input);
            Assert.False(String.IsNullOrWhiteSpace(result));
        }
Exemplo n.º 9
0
        public KnapsackHttpHandler_tests()
        {
            var coffeeScriptCompiler = new CoffeeScriptCompiler(File.ReadAllText);

            storage       = IsolatedStorageFile.GetUserStoreForAssembly();
            rootDirectory = Path.GetFullPath(Guid.NewGuid().ToString());

            // Create a fake set of scripts in modules.
            Directory.CreateDirectory(Path.Combine(rootDirectory, "lib"));
            File.WriteAllText(Path.Combine(rootDirectory, "lib", "jquery.js"),
                              "function jQuery(){}");
            File.WriteAllText(Path.Combine(rootDirectory, "lib", "knockout.js"),
                              "function knockout(){}");

            Directory.CreateDirectory(Path.Combine(rootDirectory, "app"));
            File.WriteAllText(Path.Combine(rootDirectory, "app", "widgets.js"),
                              "/// <reference path=\"../lib/jquery.js\"/>\r\n/// <reference path=\"../lib/knockout.js\"/>\r\nfunction widgets(){}");
            File.WriteAllText(Path.Combine(rootDirectory, "app", "main.js"),
                              "/// <reference path=\"widgets.js\"/>\r\nfunction main() {}");
            File.WriteAllText(Path.Combine(rootDirectory, "app", "test.coffee"),
                              "x = 1");

            var builder = new ScriptModuleContainerBuilder(storage, rootDirectory, coffeeScriptCompiler);

            builder.AddModule("lib", null);
            builder.AddModule("app", null);
            scriptModuleContainer = builder.Build();
            scriptModuleContainer.UpdateStorage("scripts.xml");

            var styleBuilder = new StylesheetModuleContainerBuilder(storage, rootDirectory, "/");

            handler = new KnapsackHttpHandler(() => scriptModuleContainer, () => stylesheetModuleContainer, coffeeScriptCompiler);

            httpContext          = new Mock <HttpContextBase>();
            httpRequest          = new Mock <HttpRequestBase>();
            requestHeaders       = new NameValueCollection();
            responseHeaders      = new NameValueCollection();
            httpResponse         = new Mock <HttpResponseBase>();
            responseOutputStream = new MemoryStream();
            cache  = new Mock <HttpCachePolicyBase>();
            server = new Mock <HttpServerUtilityBase>();

            httpRequest.SetupGet(r => r.Headers).Returns(requestHeaders);
            httpResponse.SetupGet(r => r.Headers).Returns(responseHeaders);
            httpResponse.SetupGet(r => r.OutputStream).Returns(responseOutputStream);
            httpResponse.SetupGet(r => r.Cache).Returns(cache.Object);
            httpContext.SetupGet(c => c.Request).Returns(httpRequest.Object);
            httpContext.SetupGet(c => c.Response).Returns(httpResponse.Object);
            httpContext.SetupGet(c => c.Server).Returns(server.Object);

            httpResponse.Setup(r => r.Write(It.IsAny <string>())).Callback <string>(data =>
            {
                var writer = new StreamWriter(responseOutputStream);
                writer.Write(data);
                writer.Flush();
            });
        }
        public void CoffeeScriptSmokeTest()
        {
            var input = @"v = x*5 for x in [1...10]";

            using (var fixture = new CoffeeScriptCompiler(new InstanceProvider <IJavaScriptRuntime>(
                                                              () => new IEJavaScriptRuntime()))) {
                var result = fixture.Compile(input);
                Assert.False(String.IsNullOrWhiteSpace(result));
            }
        }
Exemplo n.º 11
0
 public void CompileFile_with_invalid_CoffeeScript_throws_CompileException()
 {
     var source = "'unclosed string";
     var compiler = new CoffeeScriptCompiler();
     var file = new Mock<IFile>();
     file.SetupGet(f => f.FullPath)
         .Returns("test.coffee");
     var exception = Assert.Throws<CoffeeScriptCompileException>(delegate
     {
         compiler.Compile(source, file.Object);
     });
     exception.SourcePath.ShouldEqual("test.coffee");
 }
        /// <summary>
        /// Translates a code of asset written on CoffeeScript to JS code
        /// </summary>
        /// <param name="asset">Asset with code written on CoffeeScript</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 coffeeScriptCompiler = new CoffeeScriptCompiler(_createJsEngineInstance, options))
            {
                InnerTranslate(asset, coffeeScriptCompiler);
            }

            return(asset);
        }
Exemplo n.º 13
0
        public CompileResults Compile(string inPath, string outPath)
        {
            CoffeeScriptCompiler compiler = new CoffeeScriptCompiler(new SassAndCoffee.Core.InstanceProvider <IJavaScriptRuntime>(() => new IEJavaScriptRuntime()));

            using (StreamReader sr = new StreamReader(inPath))
            {
                string content = sr.ReadToEnd();
                string output  = compiler.Compile(content);
                using (StreamWriter sw = new StreamWriter(outPath))
                {
                    sw.WriteLine(OrangeBits.GetHeader(inPath));
                    sw.Write(output);
                }
            }
            return(null);
        }
        public void CoffeeScriptFailTest()
        {
            var input = "@#)$(@#)(@#_$)(@_)@ !!@_@@@ window.alert \"foo\" if 3>2 else if else if";
            var fixture = new CoffeeScriptCompiler();

            bool shouldDie = true;

            try {
                var result = fixture.Compile(input);
                Console.WriteLine(result);
            } catch(Exception ex) {
                Console.WriteLine("Ex: " + ex.Message);
                shouldDie = false;
            }

            Assert.False(shouldDie);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Translates a code of asset written on CoffeeScript to JS code
        /// </summary>
        /// <param name="asset">Asset with code written on CoffeeScript</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 coffeeScriptCompiler = new CoffeeScriptCompiler(_createJsEngineInstance, options))
            {
                InnerTranslate(asset, coffeeScriptCompiler);
            }

            return(asset);
        }
Exemplo n.º 16
0
        public void Can_Compile_CoffeeScript()
        {
            // Arrange
            var runtime = new SassAndCoffeeRuntime();
            var compiler = new CoffeeScriptCompiler(runtime);
            var reference = new Reference
                {
                    Extension = ".coffee",
                    Content = "t = 4"
                };
            var result = "var t;\n\nt = 4;\n";

            // Act
            compiler.Compile(ref reference);

            // Assert
            reference.Extension.ShouldBe(".js");
            reference.Content.ShouldBe(result);
        }
Exemplo n.º 17
0
        public void Can_Compile_CoffeeScript_WithoutBare()
        {
            // Arrange
            var runtime = new SassAndCoffeeRuntime();
            var compiler = new CoffeeScriptCompiler(runtime);
            compiler.Bare = false;
            var reference = new Reference
            {
                Extension = ".coffee",
                Content = "t = 4"
            };
            var result = "(function() {\n  var t;\n\n  t = 4;\n\n}).call(this);\n";

            // Act
            compiler.Compile(ref reference);

            // Assert
            reference.Extension.ShouldBe(".js");
            reference.Content.ShouldBe(result);
        }
Exemplo n.º 18
0
        public void Process(BundleContext context, BundleResponse response)
        {
            var coffee = new CoffeeScriptCompiler(new InstanceProvider <IJavaScriptRuntime>(() => new IEJavaScriptRuntime()));

            response.ContentType = "text/javascript";
            response.Content     = string.Empty;

            foreach (var fileInfo in response.Files)
            {
                if (fileInfo.Extension.Equals(".coffee", StringComparison.Ordinal))
                {
                    var result = coffee.Compile(File.ReadAllText(fileInfo.FullName));

                    response.Content += result;
                }
                else if (fileInfo.Extension.Equals(".js", StringComparison.Ordinal))
                {
                    response.Content += File.ReadAllText(fileInfo.FullName);
                }
            }
        }
        private void InnerTranslate(IAsset asset, CoffeeScriptCompiler coffeeScriptCompiler)
        {
            string newContent;
            string assetUrl = asset.Url;

            try
            {
                newContent = coffeeScriptCompiler.Compile(asset.Content, assetUrl);
            }
            catch (CoffeeScriptCompilationException 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;
        }
Exemplo n.º 20
0
        public string GetOutput(string input)
        {
            var compiler = new CoffeeScriptCompiler(new InstanceProvider <IJavaScriptRuntime>(() => new IEJavaScriptRuntime()));

            return(compiler.Compile(input));
        }
Exemplo n.º 21
0
        public void meepmeep()
        {
            var compiler = new CoffeeScriptCompiler(new InstanceProvider <IJavaScriptRuntime>(() => new IEJavaScriptRuntime()));

            Assert.Pass(compiler.Compile("smoke = (x) -> x * x"));
        }
		/// <summary>
		/// Translates a code of asset written on CoffeeScript to JS-code
		/// </summary>
		/// <param name="asset">Asset with code written on CoffeeScript</param>
		/// <returns>Asset with translated code</returns>
		public IAsset Translate(IAsset asset)
		{
			if (asset == null)
			{
				throw new ArgumentException(CoreStrings.Common_ValueIsEmpty, "asset");
			}

			using (var coffeeScriptCompiler = new CoffeeScriptCompiler(_createJsEngineInstance))
			{
				InnerTranslate(asset, coffeeScriptCompiler);
			}

			return asset;
		}
 public SassCoffeeCompiler(CoffeeScriptCompiler coffeeScriptCompiler)
 {
     _coffeeScriptCompiler = coffeeScriptCompiler;
 }
		/// <summary>
		/// Translates a code of assets written on CoffeeScript to JS-code
		/// </summary>
		/// <param name="assets">Set of assets with code written on CoffeeScript</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.CoffeeScript
				|| a.AssetTypeCode == Constants.AssetTypeCode.LiterateCoffeeScript).ToList();
			if (assetsToProcessing.Count == 0)
			{
				return assets;
			}

			using (var coffeeScriptCompiler = new CoffeeScriptCompiler(_createJsEngineInstance))
			{
				foreach (var asset in assetsToProcessing)
				{
					InnerTranslate(asset, coffeeScriptCompiler);
				}
			}

			return assets;
		}
Exemplo n.º 25
0
        public string Process(string filePath, string content)
        {
            var compiler = new CoffeeScriptCompiler();

            return(compiler.Compile(content));
        }
Exemplo n.º 26
0
        /// <summary>
        /// Transforms the content of the given string.
        /// </summary>
        /// <param name="input">The input string to transform.</param>
        /// <param name="path">The path to the given input string to transform.</param>
        /// <param name="cruncher">The cruncher that is running the transform.</param>
        /// <returns>The transformed string.</returns>
        public string Transform(string input, string path, CruncherBase cruncher)
        {
            CoffeeScriptCompiler coffeeScriptCompiler = new CoffeeScriptCompiler();

            return(coffeeScriptCompiler.Compile(input));
        }
		private void InnerTranslate(IAsset asset, CoffeeScriptCompiler coffeeScriptCompiler)
		{
			string newContent;
			string assetVirtualPath = asset.VirtualPath;
			bool isLiterate = (asset.AssetTypeCode == Constants.AssetTypeCode.LiterateCoffeeScript);
			CompilationOptions options = CreateCompilationOptions(isLiterate);

			try
			{
				newContent = coffeeScriptCompiler.Compile(asset.Content, assetVirtualPath, options);
			}
			catch (CoffeeScriptCompilingException e)
			{
				throw new AssetTranslationException(
					string.Format(CoreStrings.Translators_TranslationSyntaxError,
						INPUT_CODE_TYPE, OUTPUT_CODE_TYPE, assetVirtualPath, e.Message));
			}
			catch (Exception e)
			{
				throw new AssetTranslationException(
					string.Format(CoreStrings.Translators_TranslationFailed,
						INPUT_CODE_TYPE, OUTPUT_CODE_TYPE, assetVirtualPath, e.Message));
			}

			asset.Content = newContent;
		}