├── nuget
├── .version
├── BaristaLabs.BaristaCore.Extensions.nuspec
├── BaristaCore.AspNetCore.nuspec
├── BaristaCore.nuspec
└── BaristaLabs.BaristaCore.Common.nuspec
├── util
└── ChakraWrapperGeneratorCLI
│ ├── Templates
│ ├── settings.json
│ ├── ChakraTypedInterface.hbs
│ ├── ChakraTypedSafeImplementation.hbs
│ ├── LibChakraCore.hbs
│ └── ChakraTypedSafeImplementation_Logging.hbs
│ ├── CodeGen
│ ├── PlatformTarget.cs
│ ├── ParameterDirection.cs
│ └── ExternParameter.cs
│ ├── README.md
│ ├── Properties
│ └── launchSettings.json
│ └── ChakraWrapperGeneratorCLI.csproj
├── Logo.png
├── src
├── BaristaLabs.BaristaCore.Portafilter
│ ├── host.json
│ ├── README.md
│ ├── Properties
│ │ └── PublishProfiles
│ │ │ └── portafilter - Web Deploy.pubxml
│ ├── BaristaLabs.BaristaCore.Portafilter.csproj
│ └── BaristaFunction.cs
├── BaristaLabs.BaristaCore.Extensions
│ ├── TypeScript
│ │ ├── NewLineKind.cs
│ │ ├── ModuleResolutionKind.cs
│ │ ├── JsxEmit.cs
│ │ ├── ModuleKind.cs
│ │ ├── ScriptTarget.cs
│ │ ├── TranspileOutput.cs
│ │ └── TranspileOptions.cs
│ ├── ModuleLoaders
│ │ └── ResourceKind.cs
│ ├── Modules
│ │ ├── BlobModule.cs
│ │ ├── ReactModule.cs
│ │ ├── UuidModule.cs
│ │ ├── TypeScriptModule.cs
│ │ ├── MomentModule.cs
│ │ ├── LodashModule.cs
│ │ ├── HandlebarsModule.cs
│ │ ├── ReactDomModule.cs
│ │ ├── ReactDomServerModule.cs
│ │ ├── RawBlobModule.cs
│ │ └── FetchModule.cs
│ ├── Fetch
│ │ └── IBody.cs
│ ├── DummyProxy.cs
│ ├── EmbeddedResourceHelper.cs
│ ├── README.md
│ ├── Extensions
│ │ └── BaristaContextExtensions.cs
│ └── SerializedScriptService.cs
├── BaristaLabs.BaristaCore.Common
│ ├── BaristaDelegates.cs
│ ├── JavaScript
│ │ ├── Enums
│ │ │ ├── JavaScriptParseModuleSourceFlags.cs
│ │ │ ├── JavaScriptPromiseState.cs
│ │ │ ├── JavaScriptPropertyIdType.cs
│ │ │ ├── JavaScriptMemoryEventType.cs
│ │ │ ├── JavaScriptDiagBreakOnExceptionAttributes.cs
│ │ │ ├── JavaScriptParseScriptAttributes.cs
│ │ │ ├── JavaScriptDiagStepType.cs
│ │ │ ├── JavaScriptModuleHostInfoKind.cs
│ │ │ ├── JavaScriptDiagDebugEventType.cs
│ │ │ └── JavaScriptRuntimeAttributes.cs
│ │ ├── Engines
│ │ │ └── LinuxChakraEngine.cs
│ │ ├── Interfaces
│ │ │ ├── IJavaScriptEngineFactory.cs
│ │ │ ├── IJavaScriptEngine.cs
│ │ │ ├── IDebugWindowsJavaScriptEngine.cs
│ │ │ └── IScriptSource.cs
│ │ ├── Callbacks
│ │ │ ├── JavaScriptBeforeCollectCallback.cs
│ │ │ ├── JavaScriptObjectFinalizeCallback.cs
│ │ │ ├── JavaScriptSerializedScriptUnloadCallback.cs
│ │ │ ├── JavaScriptBackgroundWorkItemCallback.cs
│ │ │ ├── JavaScriptObjectBeforeCollectCallback.cs
│ │ │ ├── JavaScriptSerializedLoadScriptCallback.cs
│ │ │ ├── JavaScriptDiagDebugEventCallback.cs
│ │ │ ├── JavaScriptSerializedScriptLoadSourceCallback.cs
│ │ │ ├── JavaScriptPromiseContinuationCallback.cs
│ │ │ ├── JavaScriptMemoryAllocationCallback.cs
│ │ │ ├── JavaScriptThreadServiceCallback.cs
│ │ │ ├── JavaScriptNotifyModuleReadyCallback.cs
│ │ │ ├── JavaScriptFetchImportedModuleFromScriptCallback.cs
│ │ │ ├── JavaScriptFetchImportedModuleCallback.cs
│ │ │ └── JavaScriptPromiseRejectionTrackerCallback.cs
│ │ ├── SafeHandles
│ │ │ ├── JavaScriptPropertyIdSafeHandle.cs
│ │ │ ├── JavaScriptModuleRecord.cs
│ │ │ ├── JavaScriptValueSafeHandle.cs
│ │ │ ├── JavaScriptContextSafeHandle.cs
│ │ │ ├── JavaScriptWeakReferenceSafeHandle.cs
│ │ │ ├── JavaScriptRuntimeSafeHandle.cs
│ │ │ └── JavaScriptSharedArrayBufferSafeHandle.cs
│ │ ├── ChakraCoreFactory.cs
│ │ ├── JavaScriptNativeFunction.cs
│ │ ├── EventArgs
│ │ │ └── JavaScriptMemoryEventArgs.cs
│ │ ├── JavaScriptEnhancedNativeFunction.cs
│ │ └── Internal
│ │ │ └── Helpers.cs
│ ├── Interfaces
│ │ ├── IBaristaScriptModule.cs
│ │ ├── IBaristaValueFactoryBuilder.cs
│ │ ├── IBaristaTypeConversionStrategy.cs
│ │ ├── IPromiseTaskQueue.cs
│ │ ├── IBaristaRuntimeFactory.cs
│ │ ├── IBaristaContextFactory.cs
│ │ ├── IBaristaModule.cs
│ │ ├── IJsonConverter.cs
│ │ ├── IBaristaModuleRecordFactory.cs
│ │ ├── IBaristaConversionStrategy.cs
│ │ └── IBaristaObject.cs
│ ├── ModuleLoaders
│ │ ├── IBaristaModuleLoader.cs
│ │ └── InMemoryModuleLoader.cs
│ ├── BaristaModuleMissingAttributeException.cs
│ ├── BuiltIns
│ │ ├── JsString.cs
│ │ ├── JsSymbol.cs
│ │ ├── JsNull.cs
│ │ ├── JsUndefined.cs
│ │ ├── JsError.cs
│ │ ├── JsDataView.cs
│ │ ├── JsArrayBuffer.cs
│ │ ├── JsBoolean.cs
│ │ ├── JsTypedArrayType.cs
│ │ ├── JsJSON.cs
│ │ ├── JsPropertyDescriptor.cs
│ │ ├── JsExternalArrayBuffer.cs
│ │ ├── JsNumber.cs
│ │ ├── JsValueType.cs
│ │ ├── JsExternalObject.cs
│ │ ├── JsArray.cs
│ │ ├── JsIterator.cs
│ │ └── JsSymbolConstructor.cs
│ ├── Attributes
│ │ ├── BaristaIgnoreAttribute.cs
│ │ └── BaristaObjectAttribute.cs
│ ├── BaristaObjectBeforeCollectEventArgs.cs
│ ├── Tasks
│ │ ├── ThreadPerTaskScheduler.cs
│ │ └── CurrentThreadTaskScheduler.cs
│ ├── PromiseTaskQueue.cs
│ ├── BaristaValueFactoryBuilder.cs
│ ├── Extensions
│ │ ├── IBaristaModuleExtensions.cs
│ │ ├── StringExtensions.cs
│ │ ├── TaskExtensions.cs
│ │ └── TypeExtensions.cs
│ ├── PlatformApis.cs
│ ├── Exceptions
│ │ ├── JsFatalException.cs
│ │ ├── JsUsageException.cs
│ │ └── JsEngineException.cs
│ ├── BaristaLabs.BaristaCore.Common.csproj
│ ├── Modules
│ │ ├── BaristaScriptModule.cs
│ │ ├── RawTextModule.cs
│ │ └── JsonModule.cs
│ ├── Utils
│ │ └── BaristaModuleTypeLoader.cs
│ └── Undefined.cs
├── BaristaServer
│ ├── appsettings.Development.json
│ ├── appsettings.json
│ ├── Dockerfile
│ ├── Program.cs
│ ├── Properties
│ │ └── launchSettings.json
│ ├── BaristaServer.csproj
│ ├── Controllers
│ │ └── ValuesController.cs
│ └── Startup.cs
├── BaristaLabs.BaristaCore.Fiddle
│ ├── Http
│ │ └── BaristaFiddleApplicationBuilderExtensions.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ └── BaristaLabs.BaristaCore.Fiddle.csproj
└── BaristaLabs.BaristaCore.AspNetCore.Common
│ ├── Middleware
│ ├── BrewKeys.cs
│ └── 4.ServeMiddleware.cs
│ ├── BaristaLabs.BaristaCore.AspNetCore.Common.csproj
│ ├── BrewOrder.cs
│ ├── Extensions
│ └── ApplicationBuilderExtensions.cs
│ ├── BaristaContextModule.cs
│ ├── IBaristaPipeline.cs
│ └── BaristaPipeline.cs
├── docs
└── BaristaCore.vsdx
├── test
├── BaristaLabs.BaristaCore.Tests
│ ├── xunit.runner.json
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── ModuleLoaders
│ │ └── HelloWorldModule.cs
│ ├── JsonNetConverter.cs
│ ├── JavaScriptReference_Facts.cs
│ └── JavaScriptPropertyId_Facts.cs
├── BaristaLabs.BaristaCore.Extensions.Tests
│ ├── xunit.runner.json
│ ├── Lodash_Facts.cs
│ ├── Uuid_Facts.cs
│ ├── React_Facts.cs
│ ├── Moment_Facts.cs
│ ├── Handlebars_Facts.cs
│ └── BaristaLabs.BaristaCore.Extensions.Tests.csproj
└── BaristaLabs.BaristaCore.MyTestModule
│ ├── ThisIsNotAnAssemblyTest.dll
│ ├── MyTestModule.cs
│ ├── BaristaLabs.BaristaCore.MyTestModule.csproj
│ └── DisposableTestModule.cs
├── docker-compose.override.yml
├── docker-compose.yml
├── .dockerignore
├── docker-compose.ci.build.yml
├── .vscode
├── tasks.json
└── launch.json
├── benchmarks
└── BaristaLabs.BaristaCore.Benchmarks
│ ├── BaristaLabs.BaristaCore.Benchmarks.csproj
│ └── Program.cs
├── docker-compose.dcproj
├── LICENSE
├── appveyor.yml
├── package.ps1
└── .travis.yml
/nuget/.version:
--------------------------------------------------------------------------------
1 | 1.0.4-beta02
--------------------------------------------------------------------------------
/util/ChakraWrapperGeneratorCLI/Templates/settings.json:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/BaristaLabs/BaristaCore/HEAD/Logo.png
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Portafilter/host.json:
--------------------------------------------------------------------------------
1 | {
2 | "functions": [ "BaristaFunction" ]
3 | }
--------------------------------------------------------------------------------
/docs/BaristaCore.vsdx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/BaristaLabs/BaristaCore/HEAD/docs/BaristaCore.vsdx
--------------------------------------------------------------------------------
/test/BaristaLabs.BaristaCore.Tests/xunit.runner.json:
--------------------------------------------------------------------------------
1 | {
2 | "diagnosticMessages": true,
3 | "shadowCopy": false
4 | }
--------------------------------------------------------------------------------
/test/BaristaLabs.BaristaCore.Extensions.Tests/xunit.runner.json:
--------------------------------------------------------------------------------
1 | {
2 | "diagnosticMessages": true,
3 | "shadowCopy": false
4 | }
--------------------------------------------------------------------------------
/test/BaristaLabs.BaristaCore.MyTestModule/ThisIsNotAnAssemblyTest.dll:
--------------------------------------------------------------------------------
1 | Yeah, this isn't an assembly, used to test failing module loading.
--------------------------------------------------------------------------------
/test/BaristaLabs.BaristaCore.Tests/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using Xunit;
2 |
3 | [assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly)]
--------------------------------------------------------------------------------
/docker-compose.override.yml:
--------------------------------------------------------------------------------
1 | version: '3'
2 |
3 | services:
4 | baristaserver:
5 | environment:
6 | - ASPNETCORE_ENVIRONMENT=Development
7 | ports:
8 | - "80"
9 |
--------------------------------------------------------------------------------
/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: '3'
2 |
3 | services:
4 | baristaserver:
5 | image: baristaserver
6 | build:
7 | context: .
8 | dockerfile: src/BaristaServer/Dockerfile
9 |
--------------------------------------------------------------------------------
/.dockerignore:
--------------------------------------------------------------------------------
1 | .dockerignore
2 | .env
3 | .git
4 | .gitignore
5 | .vs
6 | .vscode
7 | docker-compose.yml
8 | docker-compose.*.yml
9 | */bin
10 | */obj
11 | !obj/Docker/publish/*
12 | !obj/Docker/empty/
13 |
--------------------------------------------------------------------------------
/util/ChakraWrapperGeneratorCLI/CodeGen/PlatformTarget.cs:
--------------------------------------------------------------------------------
1 | namespace ChakraWrapperGeneratorCLI.CodeGen
2 | {
3 | public enum PlatformTarget
4 | {
5 | Common,
6 | WindowsOnly
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/TypeScript/NewLineKind.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.TypeScript
2 | {
3 | public enum NewLineKind
4 | {
5 | CarriageReturnLineFeed = 0,
6 | LineFeed = 1,
7 | }
8 | }
--------------------------------------------------------------------------------
/util/ChakraWrapperGeneratorCLI/CodeGen/ParameterDirection.cs:
--------------------------------------------------------------------------------
1 | namespace ChakraWrapperGeneratorCLI.CodeGen
2 | {
3 | public enum ParameterDirection
4 | {
5 | In,
6 | Out,
7 | Ref
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/util/ChakraWrapperGeneratorCLI/README.md:
--------------------------------------------------------------------------------
1 | Utility that generates class files based on an Xml-based definition of the ChakraCore interface.
2 |
3 | The Xml Chakra definition can be generated from the ChakraSharp project or created manually.
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/BaristaDelegates.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | public delegate JsValue BaristaFunctionDelegate(JsObject calleeObj, bool isConstructCall, JsObject thisObj, object[] nativeArgs);
4 | }
5 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/TypeScript/ModuleResolutionKind.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.TypeScript
2 | {
3 | public enum ModuleResolutionKind
4 | {
5 | Classic = 1,
6 | NodeJs = 2,
7 | }
8 | }
--------------------------------------------------------------------------------
/util/ChakraWrapperGeneratorCLI/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "profiles": {
3 | "ChakraWrapperGeneratorCLI": {
4 | "commandName": "Project",
5 | "commandLineArgs": "$(SolutionDir)\\\\ChakraExternDefinitions.xml"
6 | }
7 | }
8 | }
--------------------------------------------------------------------------------
/src/BaristaServer/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "IncludeScopes": false,
4 | "LogLevel": {
5 | "Default": "Debug",
6 | "System": "Information",
7 | "Microsoft": "Information"
8 | }
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/TypeScript/JsxEmit.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.TypeScript
2 | {
3 | public enum JsxEmit
4 | {
5 | None = 0,
6 | Preserve = 1,
7 | React = 2,
8 | ReactNative = 3,
9 | }
10 | }
--------------------------------------------------------------------------------
/src/BaristaServer/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "IncludeScopes": false,
4 | "Debug": {
5 | "LogLevel": {
6 | "Default": "Warning"
7 | }
8 | },
9 | "Console": {
10 | "LogLevel": {
11 | "Default": "Warning"
12 | }
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/ModuleLoaders/ResourceKind.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.ModuleLoaders
2 | {
3 | public enum ResourceKind
4 | {
5 | Binary,
6 | Text,
7 | Json,
8 | JavaScript,
9 | TypeScript,
10 | Jsx,
11 | Tsx,
12 | }
13 | }
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/TypeScript/ModuleKind.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.TypeScript
2 | {
3 | public enum ModuleKind
4 | {
5 | None = 0,
6 | CommonJS = 1,
7 | AMD = 2,
8 | UMD = 3,
9 | System = 4,
10 | ES2015 = 5,
11 | ESNext = 6,
12 | }
13 | }
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Enums/JavaScriptParseModuleSourceFlags.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 |
5 | [Flags]
6 | public enum JavaScriptParseModuleSourceFlags
7 | {
8 | DataIsUTF16LE = 0x00000000,
9 | DataIsUTF8 = 0x00000001
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/TypeScript/ScriptTarget.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.TypeScript
2 | {
3 | public enum ScriptTarget
4 | {
5 | ES3 = 0,
6 | ES5 = 1,
7 | ES2015 = 2,
8 | ES2016 = 3,
9 | ES2017 = 4,
10 | ESNext = 5,
11 | Latest = 5,
12 | }
13 | }
--------------------------------------------------------------------------------
/docker-compose.ci.build.yml:
--------------------------------------------------------------------------------
1 | version: '3'
2 |
3 | services:
4 | ci-build:
5 | image: microsoft/aspnetcore-build:1.0-2.0
6 | volumes:
7 | - .:/src
8 | working_dir: /src
9 | command: /bin/bash -c "dotnet restore ./BaristaLabs.BaristaCore.sln && dotnet publish ./BaristaLabs.BaristaCore.sln -c Release -o ./obj/Docker/publish"
10 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Engines/LinuxChakraEngine.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using Internal;
4 |
5 | using System;
6 | using System.Runtime.InteropServices;
7 |
8 | [System.Diagnostics.DebuggerNonUserCode]
9 | public sealed class LinuxChakraEngine : ChakraEngineBase
10 | {
11 | }
12 | }
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Interfaces/IBaristaScriptModule.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | ///
4 | /// Decorator interface that indicates a module that returns a script file that should be parsed and executed.
5 | ///
6 | public interface IBaristaScriptModule : IBaristaModule
7 | {
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Interfaces/IJavaScriptEngineFactory.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | ///
4 | /// Represents a factory for creating JavaScript Engines.
5 | ///
6 | public interface IJavaScriptEngineFactory
7 | {
8 | IJavaScriptEngine CreateJavaScriptEngine();
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Enums/JavaScriptPromiseState.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | ///
4 | /// The possible states for a Promise object.
5 | ///
6 | public enum JavaScriptPromiseState
7 | {
8 | Pending = 0,
9 | Fulfilled = 1,
10 | Rejected = 2
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Interfaces/IJavaScriptEngine.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | ///
4 | /// Represents a platform-independent JavaScript Engine.
5 | ///
6 | public interface IJavaScriptEngine : ICoreJavaScriptEngine, ICommonJavaScriptEngine, IDebugJavaScriptEngine
7 | {
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Interfaces/IDebugWindowsJavaScriptEngine.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using Internal;
4 |
5 | using System;
6 | using System.Runtime.InteropServices;
7 |
8 | ///
9 | /// ChakraDebug.h interface
10 | ///
11 | public interface IDebugWindowsJavaScriptEngine
12 | {
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0.0",
3 | "tasks": [
4 | {
5 | "taskName": "build",
6 | "command": "dotnet",
7 | "type": "process",
8 | "args": [
9 | "build",
10 | "${workspaceFolder}/src/BaristaServer/BaristaServer.csproj"
11 | ],
12 | "problemMatcher": "$msCompile"
13 | }
14 | ]
15 | }
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/ModuleLoaders/IBaristaModuleLoader.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.ModuleLoaders
2 | {
3 | using System.Threading.Tasks;
4 |
5 | ///
6 | /// Represents a service that returns Barista Modules provided a module name.
7 | ///
8 | public interface IBaristaModuleLoader
9 | {
10 | Task GetModule(string name);
11 | }
12 | }
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Fiddle/Http/BaristaFiddleApplicationBuilderExtensions.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaFiddle.Http
2 | {
3 | using Microsoft.AspNetCore.Builder;
4 |
5 | public static class BaristaFiddleApplicationBuilderExtensions
6 | {
7 | public static IApplicationBuilder UseBaristaFiddle(this IApplicationBuilder app)
8 | {
9 | return app;
10 | }
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.AspNetCore.Common/Middleware/BrewKeys.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.AspNetCore.Middleware
2 | {
3 | public static class BrewKeys
4 | {
5 | public static object BrewOrderKey = new object();
6 | public static object BrewModuleLoader = new object();
7 | public static object BrewContext = new object();
8 | public static object BrewResult = new object();
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Callbacks/JavaScriptBeforeCollectCallback.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 |
5 | ///
6 | /// A callback called before collection.
7 | ///
8 | /// The state passed to SetBeforeCollectCallback.
9 | public delegate void JavaScriptBeforeCollectCallback(IntPtr callbackState);
10 | }
11 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Interfaces/IBaristaValueFactoryBuilder.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | public interface IBaristaValueFactoryBuilder
4 | {
5 | ///
6 | /// Creates a new IBaristaValueFactory associated with the specified context.
7 | ///
8 | ///
9 | IBaristaValueFactory CreateValueFactory(BaristaContext context);
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Interfaces/IBaristaTypeConversionStrategy.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using System;
4 |
5 | ///
6 | /// Represents an object that builds a JavaScript prototype from a .Net Type.
7 | ///
8 | public interface IBaristaTypeConversionStrategy
9 | {
10 | bool TryCreatePrototypeFunction(BaristaContext context, Type typeToConvert, out JsFunction value);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/benchmarks/BaristaLabs.BaristaCore.Benchmarks/BaristaLabs.BaristaCore.Benchmarks.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp2.2
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/BaristaModuleMissingAttributeException.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using System;
4 |
5 | public class BaristaModuleMissingAttributeException : Exception
6 | {
7 | public BaristaModuleMissingAttributeException(string message = "A type that implements IBaristaModule is expected to be decorated with an BaristaModuleAttribute.")
8 | :base(message)
9 | {
10 | }
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Callbacks/JavaScriptObjectFinalizeCallback.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 |
5 | ///
6 | /// A finalization callback.
7 | ///
8 | ///
9 | /// The external data that was passed in when creating the object being finalized.
10 | ///
11 | public delegate void JavaScriptObjectFinalizeCallback(IntPtr data);
12 | }
13 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Interfaces/IPromiseTaskQueue.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | ///
4 | /// Represents an object that enqueues promises for future resolution.
5 | ///
6 | public interface IPromiseTaskQueue
7 | {
8 | int Count
9 | {
10 | get;
11 | }
12 |
13 | void Clear();
14 |
15 | void Enqueue(JsFunction promise);
16 |
17 | JsFunction Dequeue();
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/TypeScript/TranspileOutput.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.TypeScript
2 | {
3 | public class TranspileOutput
4 | {
5 | public string OutputText
6 | {
7 | get;
8 | set;
9 | }
10 |
11 | //public Diagnostics[] Diagnostic
12 | //{
13 | // get;
14 | // set;
15 | //}
16 |
17 | public string SourceMapText
18 | {
19 | get;
20 | set;
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/BuiltIns/JsString.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using BaristaLabs.BaristaCore.JavaScript;
4 |
5 | public sealed class JsString : JsObject
6 | {
7 | public JsString(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle valueHandle)
8 | : base(engine, context, valueHandle)
9 | {
10 | }
11 |
12 | public override JsValueType Type
13 | {
14 | get { return JsValueType.String; }
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/BuiltIns/JsSymbol.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using BaristaLabs.BaristaCore.JavaScript;
4 |
5 | public sealed class JsSymbol : JsObject
6 | {
7 | public JsSymbol(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle valueHandle)
8 | : base(engine, context, valueHandle)
9 | {
10 | }
11 |
12 | public override JsValueType Type
13 | {
14 | get { return JsValueType.Symbol; }
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Attributes/BaristaIgnoreAttribute.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using System;
4 |
5 | ///
6 | /// Instructs the BaristaTypeConversionStrategy not to project the public field, property or method.
7 | ///
8 | [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method | AttributeTargets.Event, AllowMultiple = false)]
9 | public sealed class BaristaIgnoreAttribute : Attribute
10 | {
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/test/BaristaLabs.BaristaCore.MyTestModule/MyTestModule.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.MyTestModule
2 | {
3 | using System.Diagnostics.CodeAnalysis;
4 |
5 | [BaristaModule("MyTestModule", "This is a test, this is only a test.")]
6 | [ExcludeFromCodeCoverage]
7 | public class MyTestModule : IBaristaModule
8 | {
9 | public JsValue ExportDefault(BaristaContext context, BaristaModuleRecord referencingModule)
10 | {
11 | return context.CreateString("The maze isn't meant for you.");
12 | }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/test/BaristaLabs.BaristaCore.Tests/ModuleLoaders/HelloWorldModule.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Tests.ModuleLoaders
2 | {
3 | using System.Diagnostics.CodeAnalysis;
4 |
5 | [ExcludeFromCodeCoverage]
6 | [BaristaModule("hello_world", "Only the best module ever.")]
7 | public sealed class HelloWorldModule : IBaristaModule
8 | {
9 | public JsValue ExportDefault(BaristaContext context, BaristaModuleRecord referencingModule)
10 | {
11 | return context.CreateString("Hello, World!");
12 | }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Enums/JavaScriptPropertyIdType.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | ///
4 | /// Type enumeration of a JavaScript property
5 | ///
6 | public enum JavaScriptPropertyIdType
7 | {
8 | ///
9 | /// Type enumeration of a JavaScript string property
10 | ///
11 | String,
12 | ///
13 | /// Type enumeration of a JavaScript symbol property
14 | ///
15 | Symbol
16 | };
17 | }
18 |
--------------------------------------------------------------------------------
/test/BaristaLabs.BaristaCore.Tests/JsonNetConverter.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Tests
2 | {
3 | using Newtonsoft.Json;
4 |
5 | ///
6 | /// Represents a converter that uses Json.Net
7 | ///
8 | public class JsonNetConverter : IJsonConverter
9 | {
10 | public object Parse(string json)
11 | {
12 | return JsonConvert.DeserializeObject(json);
13 | }
14 |
15 | public string Stringify(object obj)
16 | {
17 | return JsonConvert.SerializeObject(obj);
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/SafeHandles/JavaScriptPropertyIdSafeHandle.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | ///
4 | /// Represents a handle to a JavaScript PropertyId
5 | ///
6 | public sealed class JavaScriptPropertyIdSafeHandle : JavaScriptReference
7 | {
8 | ///
9 | /// Gets an invalid Property Id.
10 | ///
11 | public static readonly JavaScriptPropertyIdSafeHandle Invalid = new JavaScriptPropertyIdSafeHandle();
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Interfaces/IBaristaRuntimeFactory.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using BaristaLabs.BaristaCore.JavaScript;
4 | using System;
5 |
6 | public interface IBaristaRuntimeFactory : IDisposable
7 | {
8 | ///
9 | /// Gets the number runtimes currently being managed by the factory.
10 | ///
11 | int Count
12 | {
13 | get;
14 | }
15 |
16 | BaristaRuntime CreateRuntime(JavaScriptRuntimeAttributes attributes = JavaScriptRuntimeAttributes.None);
17 | }
18 | }
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/Modules/BlobModule.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Modules
2 | {
3 | ///
4 | /// Module that provides the blob type.
5 | ///
6 | [BaristaModule("barista-blob", "Provides a Blob implementation")]
7 | public class BlobModule : IBaristaModule
8 | {
9 | public JsValue ExportDefault(BaristaContext context, BaristaModuleRecord referencingModule)
10 | {
11 | context.Converter.TryFromObject(context, typeof(Blob), out JsValue value);
12 | return value;
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/BaristaServer/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM microsoft/dotnet:2.1-runtime-alpine AS base
2 | WORKDIR /app
3 | EXPOSE 80
4 |
5 | FROM microsoft/dotnet:2.1-sdk-alpine AS build
6 | WORKDIR /app
7 | COPY ./BaristaServer.csproj src/BaristaServer/
8 | RUN dotnet restore src/BaristaServer/BaristaServer.csproj
9 | COPY . .
10 | WORKDIR /app/src/BaristaServer
11 | RUN dotnet build BaristaServer.csproj -c Release -o /app
12 |
13 | FROM build AS publish
14 | RUN dotnet publish BaristaServer.csproj -c Release -o /app
15 |
16 | FROM base AS final
17 | WORKDIR /app
18 | COPY --from=publish /app .
19 | ENTRYPOINT ["dotnet", "BaristaServer.dll"]
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Interfaces/IBaristaContextFactory.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using System;
4 |
5 | ///
6 | /// Represents a factory that creates Barista Context instances.
7 | ///
8 | public interface IBaristaContextFactory : IDisposable
9 | {
10 | ///
11 | /// Returns a new context associated with the specified runtime.
12 | ///
13 | ///
14 | ///
15 | BaristaContext CreateContext(BaristaRuntime runtime);
16 | }
17 | }
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Callbacks/JavaScriptSerializedScriptUnloadCallback.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | ///
4 | /// Called by the runtime when it is finished with all resources related to the script execution.
5 | /// The caller should free the source if loaded, the byte code, and the context at this time.
6 | ///
7 | /// The context passed to Js[Parse|Run]SerializedScriptWithCallback
8 | public delegate void JavaScriptSerializedScriptUnloadCallback(JavaScriptSourceContext sourceContext);
9 | }
10 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/BuiltIns/JsNull.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using BaristaLabs.BaristaCore.JavaScript;
4 |
5 | ///
6 | /// Represents a JavaScript 'null'
7 | ///
8 | public sealed class JsNull : JsValue
9 | {
10 | public JsNull(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle valueHandle)
11 | : base(engine, context, valueHandle)
12 | {
13 | }
14 |
15 | public override JsValueType Type
16 | {
17 | get { return JsValueType.Null; }
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/BuiltIns/JsUndefined.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using BaristaLabs.BaristaCore.JavaScript;
4 |
5 | ///
6 | /// Represents a JavaScript 'undefined'
7 | ///
8 | public sealed class JsUndefined : JsValue
9 | {
10 | public JsUndefined(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle handle)
11 | : base(engine, context, handle)
12 | {
13 | }
14 |
15 | public override JsValueType Type
16 | {
17 | get { return JsValueType.Undefined; }
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/BaristaObjectBeforeCollectEventArgs.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using System;
4 |
5 | public class BaristaObjectBeforeCollectEventArgs : EventArgs
6 | {
7 | public BaristaObjectBeforeCollectEventArgs(IntPtr handle, IntPtr callbackState)
8 | {
9 | Handle = handle;
10 | CallbackState = callbackState;
11 | }
12 |
13 | public IntPtr Handle
14 | {
15 | get;
16 | set;
17 | }
18 |
19 | public IntPtr CallbackState
20 | {
21 | get;
22 | set;
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Callbacks/JavaScriptBackgroundWorkItemCallback.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 |
5 | ///
6 | /// A background work item callback.
7 | ///
8 | ///
9 | /// This is passed to the host's thread service (if provided) to allow the host to
10 | /// invoke the work item callback on the background thread of its choice.
11 | ///
12 | /// Data argument passed to the thread service.
13 | public delegate void JavaScriptBackgroundWorkItemCallback(IntPtr callbackData);
14 | }
15 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Callbacks/JavaScriptObjectBeforeCollectCallback.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 |
5 | ///
6 | /// A callback called before collecting an object.
7 | ///
8 | ///
9 | /// Use JsSetObjectBeforeCollectCallback to register this callback.
10 | ///
11 | /// The object to be collected.
12 | /// The state passed to JsSetObjectBeforeCollectCallback.
13 | public delegate void JavaScriptObjectBeforeCollectCallback(IntPtr @ref, IntPtr callbackState);
14 | }
15 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Enums/JavaScriptMemoryEventType.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | ///
4 | /// Allocation callback event type.
5 | ///
6 | public enum JavaScriptMemoryEventType
7 | {
8 | ///
9 | /// Indicates a request for memory allocation.
10 | ///
11 | Allocate = 0,
12 |
13 | ///
14 | /// Indicates a memory freeing event.
15 | ///
16 | Free = 1,
17 |
18 | ///
19 | /// Indicates a failed allocation event.
20 | ///
21 | Failure = 2
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Enums/JavaScriptDiagBreakOnExceptionAttributes.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | ///
4 | /// Break on Exception attributes.
5 | ///
6 | public enum JavaScriptDiagBreakOnExceptionAttributes
7 | {
8 | ///
9 | /// Don't break on any exception.
10 | ///
11 | None = 0x0,
12 | ///
13 | /// Break on uncaught exception.
14 | ///
15 | Uncaught = 0x1,
16 | ///
17 | /// Break on first chance exception.
18 | ///
19 | FirstChance = 0x2
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/BaristaServer/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Threading.Tasks;
6 | using Microsoft.AspNetCore;
7 | using Microsoft.AspNetCore.Hosting;
8 | using Microsoft.Extensions.Configuration;
9 | using Microsoft.Extensions.Logging;
10 |
11 | namespace BaristaServer
12 | {
13 | public class Program
14 | {
15 | public static void Main(string[] args)
16 | {
17 | BuildWebHost(args).Run();
18 | }
19 |
20 | public static IWebHost BuildWebHost(string[] args) =>
21 | WebHost.CreateDefaultBuilder(args)
22 | .UseStartup()
23 | .Build();
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Callbacks/JavaScriptSerializedLoadScriptCallback.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 |
5 | ///
6 | /// Called by the runtime to load the source code of the serialized script.
7 | ///
8 | /// The context passed to Js[Parse|Run]SerializedScriptCallback
9 | /// The script returned.
10 | ///
11 | /// true if the operation succeeded, false otherwise.
12 | ///
13 | public delegate bool JavaScriptSerializedLoadScriptCallback(JavaScriptSourceContext sourceContext, out IntPtr value, out JavaScriptParseScriptAttributes parseAttributes);
14 | }
15 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Interfaces/IBaristaModule.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | ///
4 | /// Represents a BaristaModule that is used by Barista scripts to provide functionality.
5 | ///
6 | public interface IBaristaModule
7 | {
8 | ///
9 | /// Gets the default export of the module given the specified scope and referencing module.
10 | ///
11 | /// The current BaristaContext
12 | /// The module that is requesting the module.
13 | ///
14 | JsValue ExportDefault(BaristaContext context, BaristaModuleRecord referencingModule);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/BuiltIns/JsError.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using BaristaLabs.BaristaCore.JavaScript;
4 |
5 | public class JsError : JsObject
6 | {
7 | public JsError(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle valueHandle)
8 | : base(engine, context, valueHandle)
9 | {
10 | }
11 |
12 | public override JsValueType Type
13 | {
14 | get { return JsValueType.Error; }
15 | }
16 |
17 | public string Message
18 | {
19 | get
20 | {
21 | var result = GetProperty("message");
22 | return result.ToString();
23 | }
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Interfaces/IJsonConverter.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | ///
4 | /// Represents an object that can convert to and from JSON natively.
5 | ///
6 | public interface IJsonConverter
7 | {
8 | ///
9 | /// Converts the specified object into a JSON formatted string.
10 | ///
11 | ///
12 | ///
13 | string Stringify(object obj);
14 |
15 | ///
16 | /// Parses the specified JSON formatted string into an object.
17 | ///
18 | ///
19 | ///
20 | object Parse(string json);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Callbacks/JavaScriptDiagDebugEventCallback.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 |
5 | ///
6 | /// User implemented callback routine for debug events.
7 | ///
8 | ///
9 | /// Use JsDiagStartDebugging to register the callback.
10 | ///
11 | /// The type of JsDiagDebugEvent event.
12 | /// Additional data related to the debug event.
13 | /// The state passed to JsDiagStartDebugging.
14 | public delegate bool JavaScriptDiagDebugEventCallback(JavaScriptDiagDebugEventType debugEvent, IntPtr eventData, IntPtr callbackState);
15 | }
16 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/SafeHandles/JavaScriptModuleRecord.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 |
5 | ///
6 | /// Represents a Chakra Engine Module Record Safe Handle
7 | ///
8 | public sealed class JavaScriptModuleRecord : JavaScriptReference
9 | {
10 | public JavaScriptModuleRecord()
11 | : base()
12 | {
13 | }
14 |
15 | public JavaScriptModuleRecord(IntPtr ptr)
16 | : base(ptr)
17 | {
18 | }
19 |
20 | ///
21 | /// Gets an invalid Module Record.
22 | ///
23 | public static readonly JavaScriptModuleRecord Invalid = new JavaScriptModuleRecord();
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/SafeHandles/JavaScriptValueSafeHandle.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 |
5 | ///
6 | /// Represents a handle to a JavaScript Value
7 | ///
8 | public sealed class JavaScriptValueSafeHandle : JavaScriptReference
9 | {
10 | public JavaScriptValueSafeHandle()
11 | : base()
12 | {
13 | }
14 |
15 | public JavaScriptValueSafeHandle(IntPtr handle)
16 | : base(handle)
17 | {
18 | }
19 |
20 | ///
21 | /// Gets an invalid value.
22 | ///
23 | public static readonly JavaScriptValueSafeHandle Invalid = new JavaScriptValueSafeHandle();
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Tasks/ThreadPerTaskScheduler.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Tasks
2 | {
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Threading;
6 | using System.Threading.Tasks;
7 |
8 | public class ThreadPerTaskScheduler : TaskScheduler
9 | {
10 | protected override IEnumerable GetScheduledTasks()
11 | {
12 | return Enumerable.Empty();
13 | }
14 |
15 | protected override void QueueTask(Task task)
16 | {
17 | new Thread(() => TryExecuteTask(task)) { IsBackground = true }.Start();
18 | }
19 |
20 | protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
21 | {
22 | return false;
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/Fetch/IBody.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using System.Threading.Tasks;
4 |
5 | public interface IBody
6 | {
7 | bool BodyUsed
8 | {
9 | get;
10 | }
11 |
12 | [BaristaProperty(Configurable = false, Writable = false)]
13 | Task ArrayBuffer();
14 |
15 | [BaristaProperty(Configurable = false, Writable = false)]
16 | Task Blob();
17 |
18 | [BaristaProperty(Configurable = false, Writable = false)]
19 | Task FormData();
20 |
21 | [BaristaProperty(Configurable = false, Writable = false)]
22 | Task Json();
23 |
24 | [BaristaProperty(Configurable = false, Writable = false)]
25 | Task Text();
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/ChakraCoreFactory.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 | using System.Diagnostics.CodeAnalysis;
5 |
6 | [ExcludeFromCodeCoverage]
7 | public class ChakraCoreFactory : IJavaScriptEngineFactory
8 | {
9 | public IJavaScriptEngine CreateJavaScriptEngine()
10 | {
11 | if (PlatformApis.IsWindows)
12 | {
13 | return new WindowsChakraEngine();
14 | }
15 | else if (PlatformApis.IsDarwin || PlatformApis.IsLinux)
16 | {
17 | return new LinuxChakraEngine();
18 | }
19 |
20 | throw new PlatformNotSupportedException("ChakraCore is currently only supported on Windows, macOS and Linux.");
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/SafeHandles/JavaScriptContextSafeHandle.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 |
5 | ///
6 | /// Represents a handle to a JavaScript Context
7 | ///
8 | public sealed class JavaScriptContextSafeHandle : JavaScriptReference
9 | {
10 | public JavaScriptContextSafeHandle()
11 | : base()
12 | {
13 | }
14 |
15 | public JavaScriptContextSafeHandle(IntPtr ptr)
16 | : base(ptr)
17 | {
18 | }
19 |
20 | ///
21 | /// Gets an invalid context.
22 | ///
23 | public static readonly JavaScriptContextSafeHandle Invalid = new JavaScriptContextSafeHandle();
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/BaristaServer/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "iisSettings": {
3 | "windowsAuthentication": false,
4 | "anonymousAuthentication": true,
5 | "iisExpress": {
6 | "applicationUrl": "http://localhost:65329/",
7 | "sslPort": 0
8 | }
9 | },
10 | "profiles": {
11 | "IIS Express": {
12 | "commandName": "IISExpress",
13 | "launchBrowser": true,
14 | "launchUrl": "api/values",
15 | "environmentVariables": {
16 | "ASPNETCORE_ENVIRONMENT": "Development"
17 | }
18 | },
19 | "BaristaServer": {
20 | "commandName": "Project",
21 | "launchBrowser": true,
22 | "launchUrl": "api/values",
23 | "environmentVariables": {
24 | "ASPNETCORE_ENVIRONMENT": "Development"
25 | },
26 | "applicationUrl": "http://localhost:65330/"
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/docker-compose.dcproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 2.0
5 | Linux
6 | 366c1979-9aca-45a7-b7cd-f66fee79ba5e
7 | True
8 | http://localhost:{ServicePort}/api/values
9 | baristaserver
10 |
11 |
12 |
13 | docker-compose.yml
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/SafeHandles/JavaScriptWeakReferenceSafeHandle.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | ///
4 | /// Represents a JavaScript Weak Reference. Weak References are not released if invalid.
5 | ///
6 | public sealed class JavaScriptWeakReferenceSafeHandle : JavaScriptReference
7 | {
8 | protected override void Dispose(bool disposing)
9 | {
10 | //Do not call the base implementation as we have no references to free.
11 | //base.Dispose(disposing);
12 | }
13 |
14 | ///
15 | /// Gets an invalid weak reference.
16 | ///
17 | public static readonly JavaScriptWeakReferenceSafeHandle Invalid = new JavaScriptWeakReferenceSafeHandle();
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Interfaces/IBaristaModuleRecordFactory.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using BaristaLabs.BaristaCore.JavaScript;
4 | using BaristaLabs.BaristaCore.ModuleLoaders;
5 | using System;
6 |
7 | public interface IBaristaModuleRecordFactory : IDisposable
8 | {
9 |
10 | BaristaModuleRecord GetBaristaModuleRecord(JavaScriptModuleRecord moduleRecord);
11 |
12 | BaristaModuleRecord CreateBaristaModuleRecord(BaristaContext context, string moduleName, BaristaModuleRecord parentModule = null, bool setAsHost = false, IBaristaModuleLoader moduleLoader = null);
13 |
14 | BaristaModuleRecord CreateBaristaModuleRecord(BaristaContext context, JavaScriptValueSafeHandle specifier, BaristaModuleRecord parentModule = null, bool setAsHost = false, IBaristaModuleLoader moduleLoader = null);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/DummyProxy.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using System;
4 | using System.Net;
5 |
6 | ///
7 | /// Represents a dummy proxy used by RestClient
8 | ///
9 | internal class DummyProxy : IWebProxy
10 | {
11 | private static DummyProxy s_defaultDummyProxy = new DummyProxy();
12 |
13 | public ICredentials Credentials
14 | {
15 | get;
16 | set;
17 | }
18 |
19 | public Uri GetProxy(Uri destination)
20 | {
21 | return null;
22 | }
23 |
24 | public bool IsBypassed(Uri host)
25 | {
26 | return true;
27 | }
28 |
29 | public static DummyProxy GetDefaultProxy()
30 | {
31 | return s_defaultDummyProxy;
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Enums/JavaScriptParseScriptAttributes.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 |
5 | ///
6 | /// Attribute mask for JsParseScriptWithAttributes
7 | ///
8 | [Flags]
9 | public enum JavaScriptParseScriptAttributes
10 | {
11 | ///
12 | /// Default attribute
13 | ///
14 | None = 0x0,
15 | ///
16 | /// Specified script is internal and non-user code. Hidden from debugger
17 | ///
18 | LibraryCode = 0x1,
19 | ///
20 | /// ChakraCore assumes ExternalArrayBuffer is Utf8 by default.
21 | /// This one needs to be set for Utf16
22 | ///
23 | ArrayBufferIsUtf16Encoded = 0x2,
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/PromiseTaskQueue.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using System.Collections.Generic;
4 |
5 | ///
6 | /// Represents a simple implementation of a Promise Task Queue
7 | ///
8 | public class PromiseTaskQueue : IPromiseTaskQueue
9 | {
10 | private Queue m_taskQueue = new Queue();
11 |
12 | public int Count
13 | {
14 | get { return m_taskQueue.Count; }
15 | }
16 |
17 | public void Clear()
18 | {
19 | m_taskQueue.Clear();
20 | }
21 |
22 | public JsFunction Dequeue()
23 | {
24 | return m_taskQueue.Dequeue();
25 | }
26 |
27 | public void Enqueue(JsFunction promise)
28 | {
29 | m_taskQueue.Enqueue(promise);
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/Modules/ReactModule.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Modules
2 | {
3 | //https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.production.min.js
4 | [BaristaModule("react", "Allows for server-side rendering in Barista via React", Version = "16.2")]
5 | public class ReactModule : IBaristaModule
6 | {
7 | private const string ResourceName = "BaristaLabs.BaristaCore.Scripts.react.production.min.js";
8 |
9 | public JsValue ExportDefault(BaristaContext context, BaristaModuleRecord referencingModule)
10 | {
11 | var buffer = SerializedScriptService.GetSerializedScript(ResourceName, context);
12 | var fnScript = context.ParseSerializedScript(buffer, () => EmbeddedResourceHelper.LoadResource(ResourceName), "[react]");
13 | return fnScript.Call();
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/Modules/UuidModule.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Modules
2 | {
3 | //https://cdnjs.cloudflare.com/ajax/libs/node-uuid/1.4.8/uuid.min.js
4 | [BaristaModule("uuid", "Rigorous implementation of RFC4122 (v1 and v4) UUIDs.", Version = "1.4.8")]
5 | public class UuidModule : IBaristaModule
6 | {
7 | private const string ResourceName = "BaristaLabs.BaristaCore.Scripts.uuid.min.js";
8 |
9 | public JsValue ExportDefault(BaristaContext context, BaristaModuleRecord referencingModule)
10 | {
11 | var buffer = SerializedScriptService.GetSerializedScript(ResourceName, context, mapWindowToGlobal: true);
12 | var fnScript = context.ParseSerializedScript(buffer, () => EmbeddedResourceHelper.LoadResource(ResourceName), "[uuid]");
13 | return fnScript.Call();
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/Modules/TypeScriptModule.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Modules
2 | {
3 | using BaristaLabs.BaristaCore.TypeScript;
4 |
5 | //https://cdnjs.cloudflare.com/ajax/libs/typescript/2.6.2/typescript.min.js
6 | [BaristaModule("typescript", "TypeScript is a language for application scale JavaScript development", Version = "2.6.2")]
7 | public class TypeScriptModule : IBaristaModule
8 | {
9 | public JsValue ExportDefault(BaristaContext context, BaristaModuleRecord referencingModule)
10 | {
11 | var tsBuffer = TypeScriptTranspiler.GetSerializedTypeScriptCompiler(context);
12 | var fnTypeScript = context.ParseSerializedScript(tsBuffer, () => EmbeddedResourceHelper.LoadResource(TypeScriptTranspiler.ResourceName), "[typescript]");
13 | return fnTypeScript.Call();
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/Modules/MomentModule.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Modules
2 | {
3 | //https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js
4 | [BaristaModule("moment", "Parse, validate, manipulate, and display dates", Version = "2.20.1")]
5 | public class MomentModule : IBaristaModule
6 | {
7 | private const string ResourceName = "BaristaLabs.BaristaCore.Scripts.moment.min.js";
8 |
9 | public JsValue ExportDefault(BaristaContext context, BaristaModuleRecord referencingModule)
10 | {
11 | var buffer = SerializedScriptService.GetSerializedScript(ResourceName, context);
12 | var fnScript = context.ParseSerializedScript(buffer, () => EmbeddedResourceHelper.LoadResource(ResourceName), "[moment]");
13 | var jsMoment = fnScript.Call();
14 | return jsMoment;
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/BuiltIns/JsDataView.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using BaristaLabs.BaristaCore.JavaScript;
4 | using System.Runtime.InteropServices;
5 |
6 | public class JsDataView : JsObject
7 | {
8 | public JsDataView(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle valueHandle)
9 | : base(engine, context, valueHandle)
10 | {
11 | }
12 |
13 | public override JsValueType Type
14 | {
15 | get { return JsValueType.DataView; }
16 | }
17 |
18 | public byte[] GetDataViewStorage()
19 | {
20 | var ptrBuffer = Engine.JsGetDataViewStorage(Handle, out uint bufferLength);
21 | byte[] buffer = new byte[bufferLength];
22 | Marshal.Copy(ptrBuffer, buffer, 0, (int)bufferLength);
23 | return buffer;
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Callbacks/JavaScriptSerializedScriptLoadSourceCallback.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System.Runtime.InteropServices;
4 | using System.Text;
5 |
6 | ///
7 | /// Called by the runtime to load the source code of the serialized script.
8 | /// The caller must keep the script buffer valid until the JsSerializedScriptUnloadCallback.
9 | ///
10 | /// The context passed to Js[Parse|Run]SerializedScriptWithCallback
11 | /// The script returned.
12 | ///
13 | /// true if the operation succeeded, false otherwise.
14 | ///
15 | public delegate bool JavaScriptSerializedScriptLoadSourceCallback(JavaScriptSourceContext sourceContext, [MarshalAs(UnmanagedType.LPWStr)] out StringBuilder scriptBuffer);
16 | }
17 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/BuiltIns/JsArrayBuffer.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using BaristaLabs.BaristaCore.JavaScript;
4 | using System.Runtime.InteropServices;
5 |
6 | public class JsArrayBuffer : JsObject
7 | {
8 | public JsArrayBuffer(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle valueHandle)
9 | : base(engine, context, valueHandle)
10 | {
11 | }
12 |
13 | public override JsValueType Type
14 | {
15 | get { return JsValueType.ArrayBuffer; }
16 | }
17 |
18 | public byte[] GetArrayBufferStorage()
19 | {
20 | var ptrBuffer = Engine.JsGetArrayBufferStorage(Handle, out uint bufferLength);
21 | byte[] buffer = new byte[bufferLength];
22 | Marshal.Copy(ptrBuffer, buffer, 0, (int)bufferLength);
23 | return buffer;
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Fiddle/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyConfiguration("")]
9 | [assembly: AssemblyCompany("")]
10 | [assembly: AssemblyProduct("BaristaLabs.BaristaFiddle")]
11 | [assembly: AssemblyTrademark("")]
12 |
13 | // Setting ComVisible to false makes the types in this assembly not visible
14 | // to COM components. If you need to access a type in this assembly from
15 | // COM, set the ComVisible attribute to true on that type.
16 | [assembly: ComVisible(false)]
17 |
18 | // The following GUID is for the ID of the typelib if this project is exposed to COM
19 | [assembly: Guid("d39a215a-c493-4a4e-a1f5-508228bbbf89")]
20 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/BuiltIns/JsBoolean.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using BaristaLabs.BaristaCore.JavaScript;
4 | using System;
5 |
6 | public sealed class JsBoolean : JsObject
7 | {
8 | public JsBoolean(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle valueHandle)
9 | : base(engine, context, valueHandle)
10 | {
11 | }
12 |
13 | public override JsValueType Type
14 | {
15 | get { return JsValueType.Boolean; }
16 | }
17 |
18 | public override bool ToBoolean()
19 | {
20 | if (IsDisposed)
21 | throw new ObjectDisposedException(nameof(JsValue));
22 |
23 | return Engine.JsBooleanToBool(Handle);
24 | }
25 |
26 | public static implicit operator bool(JsBoolean jsBool)
27 | {
28 | return jsBool.ToBoolean();
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Callbacks/JavaScriptPromiseContinuationCallback.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 |
5 | ///
6 | /// A promise continuation callback.
7 | ///
8 | ///
9 | /// The host can specify a promise continuation callback in JsSetPromiseContinuationCallback. If
10 | /// a script creates a task to be run later, then the promise continuation callback will be called with
11 | /// the task and the task should be put in a FIFO queue, to be run when the current script is
12 | /// done executing.
13 | ///
14 | /// The task, represented as a JavaScript function.
15 | /// The data argument to be passed to the callback.
16 | public delegate void JavaScriptPromiseContinuationCallback(IntPtr task, IntPtr callbackState);
17 | }
18 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/Modules/LodashModule.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Modules
2 | {
3 | //https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js
4 | [BaristaModule("lodash", "A utility library delivering consistency, customization, performance, & extras.", Version = "4.17.4")]
5 | public class LodashModule : IBaristaModule
6 | {
7 | private const string ResourceName = "BaristaLabs.BaristaCore.Scripts.lodash.min.js";
8 |
9 | public JsValue ExportDefault(BaristaContext context, BaristaModuleRecord referencingModule)
10 | {
11 | var buffer = SerializedScriptService.GetSerializedScript(ResourceName, context, mapWindowToGlobal: true);
12 | var fnScript = context.ParseSerializedScript(buffer, () => EmbeddedResourceHelper.LoadResource(ResourceName), "[eval lodash]");
13 | var jsLodash = fnScript.Call();
14 | return jsLodash;
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/BaristaValueFactoryBuilder.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using System;
4 | using BaristaLabs.BaristaCore.JavaScript;
5 | using Microsoft.Extensions.DependencyInjection;
6 |
7 | public class BaristaValueFactoryBuilder : IBaristaValueFactoryBuilder
8 | {
9 | private readonly IServiceProvider m_serviceProvider;
10 |
11 | public BaristaValueFactoryBuilder(IServiceProvider provider)
12 | {
13 | m_serviceProvider = provider ?? throw new ArgumentNullException(nameof(provider));
14 | }
15 |
16 | public IBaristaValueFactory CreateValueFactory(BaristaContext context)
17 | {
18 | if (context == null)
19 | throw new ArgumentNullException(nameof(context));
20 |
21 | var jsEngine = m_serviceProvider.GetRequiredService();
22 | return new BaristaValueFactory(jsEngine, context);
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Callbacks/JavaScriptMemoryAllocationCallback.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 |
5 | ///
6 | /// User implemented callback routine for memory allocation events
7 | ///
8 | /// The state passed to SetRuntimeMemoryAllocationCallback.
9 | /// The type of type allocation event.
10 | /// The size of the allocation.
11 | ///
12 | /// For the Allocate event, returning true allows the runtime to continue with
13 | /// allocation. Returning false indicates the allocation request is rejected. The return value
14 | /// is ignored for other allocation events.
15 | ///
16 | public delegate bool JavaScriptMemoryAllocationCallback(IntPtr callbackState, JavaScriptMemoryEventType allocationEvent, UIntPtr allocationSize);
17 | }
18 |
--------------------------------------------------------------------------------
/util/ChakraWrapperGeneratorCLI/Templates/ChakraTypedInterface.hbs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using Internal;
4 |
5 | using System;
6 | using System.Runtime.InteropServices;
7 |
8 | ///
9 | /// {{SourceName}} interface
10 | ///
11 | public interface {{InterfaceName}}
12 | {
13 | {{#each InterfaceExterns}}
14 | ///
15 | /// {{Summary}}
16 | ///
17 | {{#if Remarks }}
18 | ///
19 | {{breaklines Remarks}}
20 | ///
21 | {{/if}}
22 | {{#each Parameters}}
23 | ///
24 | {{breaklines Description}}
25 | ///
26 | {{/each}}
27 | {{#unless ReturnParameter.IsVoid}}
28 | ///
29 | {{breaklines ReturnParameter.Description}}
30 | ///
31 | {{/unless}}
32 | {{ReturnParameter.Type}} {{Name}}({{Signature}});
33 |
34 | {{/each}}
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/Modules/HandlebarsModule.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Modules
2 | {
3 | //https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.js
4 | [BaristaModule("handlebars", "Handlebars provides the power necessary to let you build semantic templates effectively with no frustration", Version = "4.0.11")]
5 | public class HandlebarsModule : IBaristaModule
6 | {
7 | private const string ResourceName = "BaristaLabs.BaristaCore.Scripts.handlebars.min.js";
8 |
9 | public JsValue ExportDefault(BaristaContext context, BaristaModuleRecord referencingModule)
10 | {
11 | var buffer = SerializedScriptService.GetSerializedScript(ResourceName, context, mapWindowToGlobal: true);
12 | var fnScript = context.ParseSerializedScript(buffer, () => EmbeddedResourceHelper.LoadResource(ResourceName), "[handlebars]");
13 | var jsHandlebars = fnScript.Call();
14 | return jsHandlebars;
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Extensions/IBaristaModuleExtensions.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Extensions
2 | {
3 | using BaristaLabs.BaristaCore.Modules;
4 |
5 | public static class IBaristaModuleExtensions
6 | {
7 | public static string GetModuleName(this IBaristaModule module)
8 | {
9 | string name;
10 | switch (module)
11 | {
12 | case BaristaScriptModule scriptModule:
13 | name = scriptModule.Name;
14 | break;
15 | case BaristaResourceScriptModule resourceScriptModule:
16 | name = resourceScriptModule.Name;
17 | break;
18 | default:
19 | var baristaModuleAttribute = BaristaModuleAttribute.GetBaristaModuleAttributeFromType(module.GetType());
20 | name = baristaModuleAttribute.Name;
21 | break;
22 | }
23 |
24 | return name;
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/JavaScriptNativeFunction.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 | using System.Runtime.InteropServices;
5 |
6 | ///
7 | /// A function callback.
8 | ///
9 | ///
10 | /// A Function object that represents the function being invoked.
11 | ///
12 | /// Indicates whether this is a regular call or a 'new' call.
13 | /// The arguments to the call.
14 | /// The number of arguments.
15 | /// Callback data, if any.
16 | /// The result of the call, if any.
17 | public delegate IntPtr JavaScriptNativeFunction(IntPtr callee, bool isConstructCall, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.SysUInt, SizeParamIndex = 3)] IntPtr[] arguments, ushort argumentCount, IntPtr callbackData);
18 | }
19 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/Modules/ReactDomModule.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Modules
2 | {
3 | //https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.production.min.js
4 | [BaristaModule("react-dom", "The entry point of the DOM-related rendering paths. It is intended to be paired with the isomorphic React, which is shipped as react to npm.", Version = "16.2")]
5 | public class ReactDomModule : IBaristaModule
6 | {
7 | private const string ResourceName = "BaristaLabs.BaristaCore.Scripts.react-dom.production.min.js";
8 |
9 | public JsValue ExportDefault(BaristaContext context, BaristaModuleRecord referencingModule)
10 | {
11 | var buffer = SerializedScriptService.GetSerializedScript(ResourceName, context);
12 | var fnScript = context.ParseSerializedScript(buffer, () => EmbeddedResourceHelper.LoadResource(ResourceName), "[react-dom]");
13 | var jsReact = fnScript.Call();
14 | return jsReact;
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Interfaces/IScriptSource.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System.Threading.Tasks;
4 |
5 | ///
6 | /// Represents a source where scripts are persisted.
7 | ///
8 | public interface IScriptSource
9 | {
10 | ///
11 | /// Gets an integer identifier describing the script source.
12 | ///
13 | ///
14 | /// Used to identify the script source instance during debugging.
15 | ///
16 | int Cookie
17 | {
18 | get;
19 | }
20 |
21 | ///
22 | /// Gets the description of the script source.
23 | ///
24 | string Description
25 | {
26 | get;
27 | }
28 |
29 | ///
30 | /// Returns the script from the source.
31 | ///
32 | ///
33 | Task GetScriptAsync();
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.AspNetCore.Common/BaristaLabs.BaristaCore.AspNetCore.Common.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | BaristaLabs.BaristaCore.AspNetCore
6 | BaristaLabs.BaristaCore.AspNetCore
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/test/BaristaLabs.BaristaCore.MyTestModule/BaristaLabs.BaristaCore.MyTestModule.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp2.2
5 |
6 |
7 |
8 | AnyCPU
9 | latest
10 |
11 |
12 |
13 | AnyCPU
14 | latest
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 | PreserveNewest
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Fiddle/BaristaLabs.BaristaCore.Fiddle.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | BaristaLabs.BaristaCore.Fiddle
6 | BaristaLabs.BaristaCore.Fiddle
7 | false
8 | false
9 | false
10 | AnyCPU;x64
11 |
12 |
13 |
14 | latest
15 |
16 |
17 |
18 | latest
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Callbacks/JavaScriptThreadServiceCallback.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 |
5 | ///
6 | /// A thread service callback.
7 | ///
8 | ///
9 | /// The host can specify a background thread service when creating a runtime. If
10 | /// specified, then background work items will be passed to the host using this callback. The
11 | /// host is expected to either begin executing the background work item immediately and return
12 | /// true or return false and the runtime will handle the work item in-thread.
13 | ///
14 | /// The callback for the background work item.
15 | /// The data argument to be passed to the callback.
16 | /// Whether the thread service will execute the callback.
17 | public delegate bool JavaScriptThreadServiceCallback(JavaScriptBackgroundWorkItemCallback callbackFunction, IntPtr callbackData);
18 | }
19 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Extensions/StringExtensions.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Extensions
2 | {
3 | using System.Text.RegularExpressions;
4 |
5 | public static class StringExtensions
6 | {
7 | ///
8 | /// By default, pascalize converts strings to UpperCamelCase also removing underscores
9 | ///
10 | ///
11 | ///
12 | public static string Pascalize(this string input)
13 | {
14 | return Regex.Replace(input, "(?:^|_)(.)", match => match.Groups[1].Value.ToUpper());
15 | }
16 |
17 | ///
18 | /// Same as Pascalize except that the first character is lower case
19 | ///
20 | ///
21 | ///
22 | public static string Camelize(this string input)
23 | {
24 | var word = Pascalize(input);
25 | return word.Length > 0 ? word.Substring(0, 1).ToLower() + word.Substring(1) : word;
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/BaristaServer/BaristaServer.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp2.2
5 | ..\..\docker-compose.dcproj
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Enums/JavaScriptDiagStepType.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | ///
4 | /// Stepping types.
5 | ///
6 | public enum JavaScriptDiagStepType
7 | {
8 | ///
9 | /// Perform a step operation to next statement.
10 | ///
11 | StepIn = 0,
12 | ///
13 | /// Perform a step out from the current function.
14 | ///
15 | StepOut = 1,
16 | ///
17 | /// Perform a single step over after a debug break if the next statement is a function call, else behaves as a stepin.
18 | ///
19 | StepOver = 2,
20 | ///
21 | /// Perform a single step back to the previous statement (only applicable in TTD mode).
22 | ///
23 | StepBack = 3,
24 | ///
25 | /// Perform a reverse continue operation (only applicable in TTD mode).
26 | ///
27 | ReverseContinue = 4
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2016 BaristaLabs, LLC
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Callbacks/JavaScriptNotifyModuleReadyCallback.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 |
5 | ///
6 | /// User implemented callback to get notification when the module is ready.
7 | ///
8 | ///
9 | /// Notify the host after ModuleDeclarationInstantiation step (15.2.1.1.6.4) is finished. If there was error in the process, exceptionVar
10 | /// holds the exception. Otherwise the referencingModule is ready and the host should schedule execution afterwards.
11 | ///
12 | /// The referencing script that calls import()
13 | /// If nullptr, the module is successfully initialized and host should queue the execution job
14 | /// otherwise it's the exception object.
15 | ///
16 | /// true if the operation succeeded, false otherwise.
17 | ///
18 | public delegate bool JavaScriptNotifyModuleReadyCallback(IntPtr referencingModule, IntPtr exceptionVar);
19 | }
20 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/EventArgs/JavaScriptMemoryEventArgs.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 |
5 | public sealed class JavaScriptMemoryEventArgs
6 | {
7 | private bool m_cancelled;
8 |
9 | public JavaScriptMemoryEventArgs(UIntPtr amount, JavaScriptMemoryEventType type)
10 | {
11 | Amount = amount;
12 | Type = type;
13 | }
14 |
15 | public UIntPtr Amount
16 | {
17 | get;
18 | private set;
19 | }
20 |
21 | public JavaScriptMemoryEventType Type
22 | {
23 | get;
24 | private set;
25 | }
26 |
27 | public bool Cancel
28 | {
29 | get { return m_cancelled; }
30 | set
31 | {
32 | // once one event listener cancels, it's cancelled.
33 | m_cancelled |= value;
34 | }
35 | }
36 |
37 | public bool IsCancelable
38 | {
39 | get { return Type == JavaScriptMemoryEventType.Allocate; }
40 | }
41 | }
42 | }
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Interfaces/IBaristaConversionStrategy.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | ///
4 | /// Represents an implementation of a strategy to convert .Net class members to JavaScript values and vice versa.
5 | ///
6 | ///
7 | /// Used when an non object is returned by a module
8 | ///
9 | public interface IBaristaConversionStrategy
10 | {
11 | ///
12 | /// Converts the specified .Net object into a JavaScript value.
13 | ///
14 | ///
15 | ///
16 | ///
17 | bool TryFromObject(BaristaContext context, object obj, out JsValue value);
18 |
19 | ///
20 | /// Converts the specified value into a .Net object.
21 | ///
22 | ///
23 | ///
24 | ///
25 | bool TryToObject(BaristaContext context, JsValue value, out object obj);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/BaristaServer/Controllers/ValuesController.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using Microsoft.AspNetCore.Mvc;
6 |
7 | namespace BaristaServer.Controllers
8 | {
9 | [Route("api/[controller]")]
10 | public class ValuesController : Controller
11 | {
12 | // GET api/values
13 | [HttpGet]
14 | public IEnumerable Get()
15 | {
16 | return new string[] { "value1", "value2" };
17 | }
18 |
19 | // GET api/values/5
20 | [HttpGet("{id}")]
21 | public string Get(int id)
22 | {
23 | return "value";
24 | }
25 |
26 | // POST api/values
27 | [HttpPost]
28 | public void Post([FromBody]string value)
29 | {
30 | }
31 |
32 | // PUT api/values/5
33 | [HttpPut("{id}")]
34 | public void Put(int id, [FromBody]string value)
35 | {
36 | }
37 |
38 | // DELETE api/values/5
39 | [HttpDelete("{id}")]
40 | public void Delete(int id)
41 | {
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/util/ChakraWrapperGeneratorCLI/Templates/ChakraTypedSafeImplementation.hbs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using Internal;
4 |
5 | using System;
6 | using System.Runtime.InteropServices;
7 |
8 | [System.Diagnostics.DebuggerNonUserCode]
9 | {{AccessModifier}} class {{ClassName}} : {{Interfaces}}
10 | {
11 | {{#each Externs}}
12 | public {{InterfaceExtern.ReturnParameter.Type}} {{InterfaceExtern.Name}}({{InterfaceExtern.Signature}})
13 | {
14 | Errors.ThrowIfError(LibChakraCore.{{Name}}({{CallSignature}}));
15 | {{#each OutValueSafeHandles}}
16 | {{Name}}.NativeFunctionSource = nameof(LibChakraCore.{{../Name}});
17 | {{#unless IsWeakSafeHandle }}
18 | if ({{Name}} != {{Type}}.Invalid)
19 | {
20 | Errors.ThrowIfError(LibChakraCore.JsAddRef({{Name}}, out uint valueRefCount));
21 | }
22 | {{/unless}}
23 | {{/each}}
24 | {{#unless InterfaceExtern.ReturnParameter.IsVoid}}
25 | return {{InterfaceExtern.ReturnParameter.Name}};
26 | {{/unless}}
27 | }
28 |
29 | {{/#each}}
30 | }
31 | }
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/Modules/ReactDomServerModule.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Modules
2 | {
3 | //The script needs to be built by creating an empty project, npm install react-dom envify and using browserify as follows:
4 | //browserify -r react-dom/server -g [ envify --NODE_ENV production ] --standalone react-dom-server | uglifyjs > react-dom-server.browser.production.min.js
5 | [BaristaModule("react-dom-server", "Eenables you to render react components to static markup.", Version = "16.2")]
6 | public class ReactDomServerModule : IBaristaModule
7 | {
8 | private const string ResourceName = "BaristaLabs.BaristaCore.Scripts.react-dom-server.browser.production.min.js";
9 |
10 | public JsValue ExportDefault(BaristaContext context, BaristaModuleRecord referencingModule)
11 | {
12 | var buffer = SerializedScriptService.GetSerializedScript(ResourceName, context);
13 | var fnScript = context.ParseSerializedScript(buffer, () => EmbeddedResourceHelper.LoadResource(ResourceName), "[react-dom-server]");
14 | var jsReact = fnScript.Call();
15 | return jsReact;
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/SafeHandles/JavaScriptRuntimeSafeHandle.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using Internal;
4 | using System.Diagnostics;
5 |
6 | ///
7 | /// Represents a handle to a JavaScript Runtime
8 | ///
9 | public sealed class JavaScriptRuntimeSafeHandle : JavaScriptReference
10 | {
11 | protected override void Dispose(bool disposing)
12 | {
13 | if (disposing && !IsClosed)
14 | {
15 | //Ensure that a context is not active, otherwise the runtime will throw a "Runtime In Use" exception.
16 | LibChakraCore.JsSetCurrentContext(JavaScriptContextSafeHandle.Invalid);
17 | LibChakraCore.JsDisposeRuntime(handle);
18 | }
19 |
20 | //Do not call the base implementation as we have no references to free.
21 | //base.Dispose(disposing);
22 | }
23 |
24 | ///
25 | /// Gets an invalid runtime.
26 | ///
27 | public static readonly JavaScriptRuntimeSafeHandle Invalid = new JavaScriptRuntimeSafeHandle();
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/EmbeddedResourceHelper.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using System.IO;
4 | using System.Reflection;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | internal static class EmbeddedResourceHelper
9 | {
10 | public static async Task LoadResourceAsync(T type, string name)
11 | {
12 | var assembly = typeof(T).Assembly;
13 | var resourceStream = assembly.GetManifestResourceStream(name);
14 | using (var reader = new StreamReader(resourceStream, Encoding.UTF8))
15 | {
16 | return await reader.ReadToEndAsync();
17 | }
18 | }
19 |
20 | public static string LoadResource(string name, Assembly assembly = null)
21 | {
22 | if (assembly == null)
23 | assembly = Assembly.GetAssembly(typeof(EmbeddedResourceHelper));
24 |
25 | var resourceStream = assembly.GetManifestResourceStream(name);
26 | using (var reader = new StreamReader(resourceStream, Encoding.UTF8))
27 | {
28 | return reader.ReadToEnd();
29 | }
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/README.md:
--------------------------------------------------------------------------------
1 | BaristaLabs.BaristaCore.Extensions
2 | --------
3 |
4 | Provides commonly used modules, module loaders, and more to BaristaCore
5 |
6 | ##### Module Loaders
7 |
8 | - WebResourceModuleLoader: Allows web resources accessible via http to be used.
9 |
10 | ##### Modules
11 |
12 | - ```barista-blob``` - Provides a implementation of the Blob object.
13 | - ```barista-console``` - Provides console.log functionality that writes to the currently configured log.
14 | - ```barista-fetch``` - Provides a fetch implementation
15 | - ```barista-mailkit``` - Adds the ability to send SMTP messages
16 | - ```barista-xml2js``` - Converts Json to and from Xml
17 |
18 | - ```handlebars``` - Exposes the excellent Handlebars library
19 | - ```lodash``` - Exposes lodash
20 | - ```moment``` - Exposes moment
21 | - ```react``` - Allows SSR via React
22 | - ```react-dom-server``` - Allows SSR via React
23 | - ```typescript``` - Exposes the typescript library for transpiling Typescript to JavaScript
24 | - ```uuid``` - Exposes the uuid library for generating uuids
25 |
26 | ##### Context Extensions
27 |
28 | - ExecuteTypeScriptModule - Adds the ability to automatically transpile and execute TypeScript
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Callbacks/JavaScriptFetchImportedModuleFromScriptCallback.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 |
5 | ///
6 | /// User implemented callback to get notification when the module is ready.
7 | ///
8 | ///
9 | /// Notify the host after ModuleDeclarationInstantiation step (15.2.1.1.6.4) is finished. If there was error in the process, exceptionVar
10 | /// holds the exception. Otherwise the referencingModule is ready and the host should schedule execution afterwards.
11 | ///
12 | /// The referencing module that have finished running ModuleDeclarationInstantiation step.
13 | /// If nullptr, the module is successfully initialized and host should queue the execution job
14 | /// otherwise it's the exception object.
15 | ///
16 | /// true if the operation succeeded, false otherwise.
17 | ///
18 | public delegate bool JavaScriptFetchImportedModuleFromScriptCallback(IntPtr referencingSourceContext, IntPtr specifier, out IntPtr dependentModuleRecord);
19 | }
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/BuiltIns/JsTypedArrayType.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | ///
4 | /// The type of a typed JavaScript array.
5 | ///
6 | public enum JsTypedArrayType
7 | {
8 | ///
9 | /// An int8 array.
10 | ///
11 | Int8,
12 | ///
13 | /// An uint8 array.
14 | ///
15 | Uint8,
16 | ///
17 | /// An uint8 clamped array.
18 | ///
19 | Uint8Clamped,
20 | ///
21 | /// An int16 array.
22 | ///
23 | Int16,
24 | ///
25 | /// An uint16 array.
26 | ///
27 | Uint16,
28 | ///
29 | /// An int32 array.
30 | ///
31 | Int32,
32 | ///
33 | /// An uint32 array.
34 | ///
35 | Uint32,
36 | ///
37 | /// A float32 array.
38 | ///
39 | Float32,
40 | ///
41 | /// A float64 array.
42 | ///
43 | Float64
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Portafilter/README.md:
--------------------------------------------------------------------------------
1 | Portafilter
2 | -----
3 |
4 | This is a Azure Functions host of BaristaCore.
5 |
6 | Caveat: Despite running perfectly locally, when deployed to Azure Functions (as of now) despite
7 | having x64 enabled on the application configuration page, Azure Functions loads dotnet core in x86
8 |
9 | wtf.
10 |
11 | ---
12 | https://github.com/Azure/Azure-Functions/issues/651 to track, but,
13 | given the issue queue is growing, and since there's no way of knowing...
14 |
15 | Round the world and home again
16 | That’s the sailor’s way
17 | Faster faster, faster faster
18 |
19 | There’s no earthly way of knowing
20 | Which direction we are going
21 | There’s no knowing where we’re rowing
22 | Or which way the river’s flowing
23 |
24 | Is it raining, is it snowing
25 | Is a hurricane a-blowing
26 |
27 | Not a speck of light is showing
28 | So the danger must be growing
29 | Are the fires of Hell a-glowing
30 | Is the grisly reaper mowing
31 |
32 | Yes, the danger must be growing
33 | For the rowers keep on rowing
34 | And they’re certainly not showing
35 | Any signs that they are slowing
36 |
37 | – ‘Wondrous Boat Ride’, from Willy Wonka and the Chocolate Factory (1971)
38 |
39 |
40 | ---
41 | AWS Lambda doesn't support dotnet core 2.0 yet. So we're stuck for now.
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/Extensions/BaristaContextExtensions.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Extensions
2 | {
3 | using BaristaLabs.BaristaCore.ModuleLoaders;
4 | using BaristaLabs.BaristaCore.TypeScript;
5 |
6 | public static class BaristaContextExtensions
7 | {
8 | public static JsValue EvaluateTypeScriptModule(this BaristaContext context, string script, IBaristaModuleLoader moduleLoader = null, bool isTsx = false)
9 | {
10 | var transpileTask = TypeScriptTranspiler.Default.Transpile(script, isTsx ? "main.tsx" : "main.ts");
11 | var transpilerOutput = transpileTask.GetAwaiter().GetResult();
12 |
13 | return context.EvaluateModule(transpilerOutput.OutputText, moduleLoader);
14 | }
15 |
16 | public static T EvaluateTypeScriptModule(this BaristaContext context, string script, IBaristaModuleLoader moduleLoader = null, bool isTsx = false)
17 | where T : JsValue
18 | {
19 | var transpileTask = TypeScriptTranspiler.Default.Transpile(script, isTsx ? "main.tsx" : "main.ts");
20 | var transpilerOutput = transpileTask.GetAwaiter().GetResult();
21 |
22 | return context.EvaluateModule(transpilerOutput.OutputText, moduleLoader);
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Interfaces/IBaristaObject.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using BaristaLabs.BaristaCore.JavaScript;
4 | using System;
5 |
6 | ///
7 | /// Represents an object that acts as a flyweight to a JavaScript reference.
8 | ///
9 | ///
10 | /// IBaristaObjects are treated as flyweight objects -- that is, their lifecycle can exist independently of actual JavaScript objects created by the runtime.
11 | ///
12 | ///
13 | public interface IBaristaObject: IDisposable
14 | where T : JavaScriptReference
15 | {
16 | ///
17 | /// Event that is raised prior to the underlying runtime collecting the object.
18 | ///
19 | event EventHandler BeforeCollect;
20 |
21 | ///
22 | /// Gets the underlying JavaScript Reference
23 | ///
24 | T Handle
25 | {
26 | get;
27 | }
28 |
29 | ///
30 | /// Gets a value that indicates if this reference has been disposed.
31 | ///
32 | bool IsDisposed
33 | {
34 | get;
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Attributes/BaristaObjectAttribute.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using System;
4 |
5 | ///
6 | /// Instructs the BaristaTypeConversionStrategy how to project the object.
7 | ///
8 | [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
9 | public class BaristaObjectAttribute : Attribute
10 | {
11 | private readonly string m_name;
12 |
13 | public BaristaObjectAttribute(string name)
14 | {
15 | if (string.IsNullOrWhiteSpace(name))
16 | throw new ArgumentNullException(nameof(name));
17 |
18 | m_name = name;
19 | }
20 |
21 | ///
22 | /// Gets the name of the object.
23 | ///
24 | public string Name
25 | {
26 | get { return m_name; }
27 | }
28 |
29 | public static string GetBaristaObjectNameFromType(Type type)
30 | {
31 | var attributes = type.GetCustomAttributes(typeof(BaristaObjectAttribute), false);
32 | if (attributes.Length == 1 && attributes[0] is BaristaObjectAttribute attr)
33 | {
34 | return attr.Name;
35 | }
36 | return type.Name;
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/BaristaServer/Startup.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaServer
2 | {
3 | using BaristaLabs.BaristaCore.AspNetCore;
4 | using BaristaLabs.BaristaCore.Extensions;
5 | using Microsoft.AspNetCore.Builder;
6 | using Microsoft.AspNetCore.Hosting;
7 | using Microsoft.Extensions.Configuration;
8 | using Microsoft.Extensions.DependencyInjection;
9 |
10 | public class Startup
11 | {
12 | public Startup(IConfiguration configuration)
13 | {
14 | Configuration = configuration;
15 | }
16 |
17 | public IConfiguration Configuration { get; }
18 |
19 | // This method gets called by the runtime. Use this method to add services to the container.
20 | public void ConfigureServices(IServiceCollection services)
21 | {
22 | services.AddBaristaCore();
23 |
24 | services.AddMvc();
25 | }
26 |
27 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
28 | public void Configure(IApplicationBuilder app, IHostingEnvironment env)
29 | {
30 | if (env.IsDevelopment())
31 | {
32 | app.UseDeveloperExceptionPage();
33 | }
34 |
35 | app.UseBaristaCore();
36 |
37 | app.UseMvc();
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Callbacks/JavaScriptFetchImportedModuleCallback.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 |
5 | ///
6 | /// User implemented callback to fetch additional imported modules.
7 | ///
8 | ///
9 | /// Notify the host to fetch the dependent module. This is the "import" part before HostResolveImportedModule in ES6 spec.
10 | /// This notifies the host that the referencing module has the specified module dependency, and the host need to retrieve the module back.
11 | ///
12 | /// The referencing module that is requesting the dependency modules.
13 | /// The specifier coming from the module source code.
14 | /// The ModuleRecord of the dependent module. If the module was requested before from other source, return the
15 | /// existing ModuleRecord, otherwise return a newly created ModuleRecord.
16 | ///
17 | /// true if the operation succeeded, false otherwise.
18 | ///
19 | public delegate bool JavaScriptFetchImportedModuleCallback(IntPtr referencingModule, IntPtr specifier, out IntPtr dependentModuleRecord);
20 | }
21 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/SafeHandles/JavaScriptSharedArrayBufferSafeHandle.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 |
5 | ///
6 | /// Represents a safe handle to a Shared Array Buffer that can be used between contexts.
7 | ///
8 | ///
9 | /// SharedArrayBuffers must be explicitly freed with Release
10 | ///
11 | public sealed class JavaScriptSharedArrayBufferSafeHandle : JavaScriptReference
12 | {
13 | public JavaScriptSharedArrayBufferSafeHandle()
14 | : base()
15 | {
16 | }
17 |
18 | public JavaScriptSharedArrayBufferSafeHandle(IntPtr ptr)
19 | : base(ptr)
20 | {
21 | }
22 |
23 | protected override void Dispose(bool disposing)
24 | {
25 | //LibChakraCore.JsReleaseSharedArrayBufferContentHandle(this);
26 |
27 | //Do not call the base implementation as we have no references to free.
28 | //base.Dispose(disposing);
29 | }
30 |
31 | ///
32 | /// Gets an invalid weak reference.
33 | ///
34 | public static readonly JavaScriptSharedArrayBufferSafeHandle Invalid = new JavaScriptSharedArrayBufferSafeHandle();
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/appveyor.yml:
--------------------------------------------------------------------------------
1 | version: 1.0.{build}
2 | image: Visual Studio 2017
3 | configuration:
4 | - Release
5 | platform: Any CPU
6 | environment:
7 | FRAMEWORK: netcoreapp2.2
8 | DOTNET_CLI_TELEMETRY_OPTOUT: 1
9 | COVERALLS_REPO_TOKEN: 7c1iHfH8bvABxL9ePXzvukfeVYM2txph8
10 | DOTNET_INSTALL_DIR: C:\Program Files\dotnet
11 | init:
12 | - ps: $Env:LABEL = "CI" + $Env:APPVEYOR_BUILD_NUMBER.PadLeft(5, "0")
13 | install:
14 | before_build:
15 | - cmd: set
16 | - cmd: dotnet --info
17 | build_script:
18 | - cmd: dotnet build -c %CONFIGURATION% -f %FRAMEWORK% test\BaristaLabs.BaristaCore.Tests\
19 | - cmd: dotnet build -c %CONFIGURATION% -f %FRAMEWORK% test\BaristaLabs.BaristaCore.Extensions.Tests\
20 | test_script:
21 | - cmd: dotnet test -c %CONFIGURATION% -f %FRAMEWORK% test\BaristaLabs.BaristaCore.Tests\ -p:CollectCoverage=true -p:CoverletOutputFormat=\"cobertura,opencover\" -p:Exclude=[xunit.*]* --no-build
22 | - cmd: dotnet test -c %CONFIGURATION% -f %FRAMEWORK% test\BaristaLabs.BaristaCore.Extensions.Tests\ -p:CollectCoverage=true -p:CoverletOutputFormat=\"cobertura,opencover\" -p:Exclude=[xunit.*]* --no-build
23 | after_test:
24 | - cmd: dotnet tool install -g coveralls.net --version 1.0.0
25 | - cmd: csmacnz.Coveralls --opencover -i ./test/BaristaLabs.BaristaCore.Tests/coverage.opencover.xml --useRelativePaths
26 | cache:
27 | - '%USERPROFILE%\.nuget\packages'
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.AspNetCore.Common/BrewOrder.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.AspNetCore
2 | {
3 | using BaristaLabs.BaristaCore.ModuleLoaders;
4 |
5 | public class BrewOrder
6 | {
7 | public BrewOrder()
8 | {
9 | Language = ResourceKind.JavaScript;
10 | }
11 |
12 | ///
13 | /// Gets or sets the base url that will be used for web resource module loaders.
14 | ///
15 | public string BaseUrl
16 | {
17 | get;
18 | set;
19 | }
20 |
21 | ///
22 | /// Gets or sets the path associated with the request.
23 | ///
24 | public string Path
25 | {
26 | get;
27 | set;
28 | }
29 |
30 | ///
31 | /// Gets or sets the code that will be executed
32 | ///
33 | public string Code
34 | {
35 | get;
36 | set;
37 | }
38 |
39 | ///
40 | /// Gets or sets the language of the code.
41 | ///
42 | public ResourceKind Language
43 | {
44 | get;
45 | set;
46 | }
47 |
48 | public bool IsCodeSet
49 | {
50 | get;
51 | set;
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/BuiltIns/JsJSON.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using BaristaLabs.BaristaCore.JavaScript;
4 | using System;
5 |
6 | ///
7 | /// Represents the built-in JSON Object.
8 | ///
9 | public class JsJSON : JsObject
10 | {
11 | public JsJSON(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle valueHandle)
12 | : base(engine, context, valueHandle)
13 | {
14 |
15 | }
16 |
17 | public string Stringify(JsValue value, JsValue replacer = null, JsValue space = null)
18 | {
19 | if (value == null)
20 | throw new ArgumentNullException(nameof(value));
21 |
22 | var fnStringify = GetProperty("stringify");
23 | var resultHandle = fnStringify.Call(this, value, replacer, space);
24 | if (resultHandle == null)
25 | return null;
26 |
27 | return resultHandle.ToString();
28 | }
29 |
30 | public JsValue Parse(JsValue value, JsValue reviver = null)
31 | {
32 | if (value == null)
33 | throw new ArgumentNullException(nameof(value));
34 |
35 | var fnParse = GetProperty("parse");
36 | return fnParse.Call(fnParse, value, reviver);
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/JavaScriptEnhancedNativeFunction.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 | using System.Runtime.InteropServices;
5 |
6 | ///
7 | /// A structure containing information about a native function callback.
8 | ///
9 | public struct JavaScriptNativeFunctionInfo
10 | {
11 | public IntPtr thisArg;
12 | public IntPtr newTargetArg;
13 | public bool isConstructCall;
14 | }
15 |
16 | ///
17 | /// A function callback.
18 | ///
19 | ///
20 | /// A function object that represents the function being invoked.
21 | ///
22 | /// The arguments to the call.
23 | /// The number of arguments.
24 | /// Additional information about this function call.
25 | ///
26 | /// The state passed to JsCreateFunction.
27 | ///
28 | /// The result of the call, if any.
29 | public delegate IntPtr JavaScriptEnhancedNativeFunction(IntPtr callee, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.SysUInt, SizeParamIndex = 3)] IntPtr[] arguments, ushort argumentCount, JavaScriptNativeFunctionInfo info, IntPtr callbackState);
30 | }
31 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/PlatformApis.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using System;
4 | using System.Diagnostics.CodeAnalysis;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 | using System.Threading;
8 |
9 | [ExcludeFromCodeCoverage]
10 | public static class PlatformApis
11 | {
12 | static PlatformApis()
13 | {
14 | IsWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
15 | IsDarwin = RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
16 | IsLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
17 | }
18 |
19 | public static bool IsWindows
20 | {
21 | get;
22 | }
23 |
24 | public static bool IsDarwin
25 | {
26 | get;
27 | }
28 |
29 | public static bool IsLinux
30 | {
31 | get;
32 | }
33 |
34 | [MethodImpl(MethodImplOptions.AggressiveInlining)]
35 | public static long VolatileRead(ref long value)
36 | {
37 | if (IntPtr.Size == 8)
38 | {
39 | return Volatile.Read(ref value);
40 | }
41 | else
42 | {
43 | //Avoid torn long reads on 32-bit
44 | return Interlocked.Read(ref value);
45 | }
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/TypeScript/TranspileOptions.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.TypeScript
2 | {
3 | using System.Collections.Generic;
4 |
5 | public class TranspileOptions
6 | {
7 | public TranspileOptions()
8 | {
9 | CompilerOptions = new CompilerOptions();
10 | RenamedDependencies = new Dictionary();
11 | }
12 |
13 | ///
14 | /// Gets or sets the script that will be transpiled to JavaScript.
15 | ///
16 | public string Script
17 | {
18 | get;
19 | set;
20 | }
21 |
22 | public CompilerOptions CompilerOptions
23 | {
24 | get;
25 | set;
26 | }
27 |
28 | public string FileName
29 | {
30 | get;
31 | set;
32 | }
33 |
34 | public bool? ReportDiagnostics
35 | {
36 | get;
37 | set;
38 | }
39 |
40 | public string ModuleName
41 | {
42 | get;
43 | set;
44 | }
45 |
46 | public IDictionary RenamedDependencies
47 | {
48 | get;
49 | set;
50 | }
51 |
52 | //public CustomTransformers Transformers
53 | //{
54 | // get;
55 | // set;
56 | //}
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/util/ChakraWrapperGeneratorCLI/Templates/LibChakraCore.hbs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript.Internal
2 | {
3 | using System;
4 | using System.Runtime.InteropServices;
5 |
6 | ///
7 | /// Represents the Unmanaged ChakraCore Library
8 | ///
9 |
10 | //FIXME: Commenting this out until MS can get their shit together RE:https://github.com/dotnet/project-system/issues/2733
11 | /*#if !DEBUG
12 | [System.Diagnostics.DebuggerNonUserCode]
13 | #endif*/
14 | public static class LibChakraCore
15 | {
16 | private const string DllName = "{{DllName}}";
17 |
18 | {{#each Externs}}
19 | ///
20 | /// {{Summary}}
21 | ///
22 | {{#if Remarks}}
23 | ///
24 | {{breaklines Remarks}}
25 | ///
26 | {{/if}}
27 | {{#each Parameters}}
28 | ///
29 | {{breaklines Description}}
30 | ///
31 | {{/each}}
32 | {{#if ReturnParameter.Type}}
33 | ///
34 | {{breaklines ReturnParameter.Description}}
35 | ///
36 | {{/if}}
37 | [DllImport(DllName, EntryPoint = "{{Name}}", CallingConvention = CallingConvention.Cdecl{{#if DllImportEx}}{{DllImportEx}}{{/if}})]
38 | public static extern JsErrorCode {{Name}}({{Signature}});
39 |
40 | {{/each}}
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.AspNetCore.Common/Extensions/ApplicationBuilderExtensions.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.AspNetCore
2 | {
3 | using BaristaLabs.BaristaCore.AspNetCore.Middleware;
4 | using Microsoft.AspNetCore.Builder;
5 |
6 | ///
7 | /// Extension methods for to add BaristaCore to the request execution pipeline.
8 | ///
9 | public static class ApplicationBuilderExtensions
10 | {
11 | ///
12 | /// Adds BaristaCore to the request execution pipeline.
13 | ///
14 | ///
15 | ///
16 | ///
17 | public static IApplicationBuilder UseBaristaCore(this IApplicationBuilder app, string baristaEvalPath = null)
18 | {
19 | if (string.IsNullOrWhiteSpace(baristaEvalPath))
20 | baristaEvalPath = "/api/barista";
21 |
22 | app.Map(baristaEvalPath, (innerApp) =>
23 | {
24 | innerApp.UseMiddleware();
25 | innerApp.UseMiddleware();
26 | innerApp.UseMiddleware();
27 | innerApp.UseMiddleware();
28 | });
29 |
30 | return app;
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Enums/JavaScriptModuleHostInfoKind.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | ///
4 | /// The types of host info that can be set on a module record with JsSetModuleHostInfo.
5 | ///
6 | ///
7 | /// For more information see JsSetModuleHostInfo.
8 | ///
9 | public enum JavaScriptModuleHostInfoKind
10 | {
11 | ///
12 | /// An exception object - e.g. if the module file cannot be found.
13 | ///
14 | Exception = 0x01,
15 | ///
16 | /// Host defined info.
17 | ///
18 | HostDefined = 0x02,
19 | ///
20 | /// Callback for receiving notification when module is ready.
21 | ///
22 | NotifyModuleReadyCallback = 0x3,
23 | ///
24 | /// Callback for receiving notification to fetch a dependent module.
25 | ///
26 | FetchImportedModuleCallback = 0x4,
27 | ///
28 | /// Callback for receiving notification for calls to ```import()```
29 | ///
30 | FetchImportedModuleFromScriptCallback = 0x5,
31 | ///
32 | /// URL for use in error stack traces and debugging.
33 | ///
34 | Url = 0x6
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/SerializedScriptService.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using System;
4 | using System.Collections.Concurrent;
5 |
6 | ///
7 | /// Represents a service that maintains a collection of serialized scripts.
8 | ///
9 | public static class SerializedScriptService
10 | {
11 | private static ConcurrentDictionary s_serializedScripts = new ConcurrentDictionary();
12 |
13 | public static byte[] GetSerializedScript(string resourceName, BaristaContext context, bool mapWindowToGlobal = false)
14 | {
15 | if (context == null)
16 | throw new ArgumentNullException(nameof(context));
17 |
18 | return s_serializedScripts.GetOrAdd(resourceName, new Func((name) =>
19 | {
20 | var script = EmbeddedResourceHelper.LoadResource(name);
21 |
22 | string mapWindowToGlobalString = mapWindowToGlobal ? "const window = global;" : null;
23 |
24 | var scriptWithModuleWrapper = $@"(() => {{
25 | 'use strict';
26 | {mapWindowToGlobalString}
27 | const module = {{
28 | exports: {{}}
29 | }};
30 | let exports = module.exports;
31 | {script}
32 | return module.exports;
33 | }})();";
34 |
35 | return context.SerializeScript(scriptWithModuleWrapper);
36 | }));
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/util/ChakraWrapperGeneratorCLI/CodeGen/ExternParameter.cs:
--------------------------------------------------------------------------------
1 | namespace ChakraWrapperGeneratorCLI.CodeGen
2 | {
3 | public class ExternParameter
4 | {
5 | public ExternParameter()
6 | {
7 | this.Direction = ParameterDirection.In;
8 | }
9 |
10 | public string Type
11 | {
12 | get;
13 | set;
14 | }
15 |
16 | public string Name
17 | {
18 | get;
19 | set;
20 | }
21 |
22 | public string Description
23 | {
24 | get;
25 | set;
26 | }
27 |
28 | public bool IsVoid
29 | {
30 | get
31 | {
32 | return Type == "void";
33 | }
34 | }
35 |
36 | ///
37 | /// Gets a valud that indicates if the safe handle is "weak" and should not participate in reference counting.
38 | ///
39 | public bool IsWeakSafeHandle
40 | {
41 | get
42 | {
43 | return
44 | Type == "JavaScriptRuntimeSafeHandle" ||
45 | Type == "JavaScriptWeakReferenceSafeHandle" ||
46 | Type == "JavaScriptSharedArrayBufferSafeHandle";
47 | }
48 | }
49 |
50 | public ParameterDirection Direction
51 | {
52 | get;
53 | set;
54 | }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/util/ChakraWrapperGeneratorCLI/Templates/ChakraTypedSafeImplementation_Logging.hbs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using BaristaLabs.BaristaCore.Logging;
4 | using Internal;
5 |
6 | using System;
7 | using System.Runtime.InteropServices;
8 |
9 | [System.Diagnostics.DebuggerNonUserCode]
10 | {{AccessModifier}} class {{ClassName}} : {{Interfaces}}
11 | {
12 | private static readonly ILog Logger = LogProvider.For<{{ClassName}}>();
13 |
14 | {{#each Externs}}
15 | public {{InterfaceExtern.ReturnParameter.Type}} {{InterfaceExtern.Name}}({{InterfaceExtern.Signature}})
16 | {
17 | Logger.Info("Entering {methodName}", "{{InterfaceExtern.Name}}");
18 | Errors.ThrowIfError(LibChakraCore.{{Name}}({{CallSignature}}));
19 | {{#each OutValueSafeHandles}}
20 | {{Name}}.NativeFunctionSource = nameof(LibChakraCore.{{../Name}});
21 | {{#unless IsWeakSafeHandle }}
22 | if ({{Name}} != {{Type}}.Invalid)
23 | {
24 | Errors.ThrowIfError(LibChakraCore.JsAddRef({{Name}}, out uint valueRefCount));
25 | }
26 | {{/unless}}
27 | {{/each}}
28 | Logger.Info("Leaving {methodName}", "{{InterfaceExtern.Name}}");
29 | {{#unless InterfaceExtern.ReturnParameter.IsVoid}}
30 | return {{InterfaceExtern.ReturnParameter.Name}};
31 | {{/unless}}
32 | }
33 |
34 | {{/#each}}
35 | }
36 | }
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Enums/JavaScriptDiagDebugEventType.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | ///
4 | /// Debug events reported from ChakraCore engine.
5 | ///
6 | public enum JavaScriptDiagDebugEventType
7 | {
8 | ///
9 | /// Indicates a new script being compiled, this includes script, eval, new function.
10 | ///
11 | JsDiagDebugEventSourceCompile = 0,
12 | ///
13 | /// Indicates compile error for a script.
14 | ///
15 | JsDiagDebugEventCompileError = 1,
16 | ///
17 | /// Indicates a break due to a breakpoint.
18 | ///
19 | JsDiagDebugEventBreakpoint = 2,
20 | ///
21 | /// Indicates a break after completion of step action.
22 | ///
23 | JsDiagDebugEventStepComplete = 3,
24 | ///
25 | /// Indicates a break due to debugger statement.
26 | ///
27 | JsDiagDebugEventDebuggerStatement = 4,
28 | ///
29 | /// Indicates a break due to async break.
30 | ///
31 | JsDiagDebugEventAsyncBreak = 5,
32 | ///
33 | /// Indicates a break due to a runtime script exception.
34 | ///
35 | JsDiagDebugEventRuntimeException = 6
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/ModuleLoaders/InMemoryModuleLoader.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.ModuleLoaders
2 | {
3 | using BaristaLabs.BaristaCore.Extensions;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Threading.Tasks;
7 |
8 | ///
9 | /// Represents a simple in-memory barista module loader.
10 | ///
11 | public class InMemoryModuleLoader : IBaristaModuleLoader
12 | {
13 | private IDictionary m_modules = new Dictionary();
14 |
15 | public void RegisterModule(IBaristaModule module)
16 | {
17 | if (module == null)
18 | throw new ArgumentNullException(nameof(module));
19 |
20 | var name = module.GetModuleName();
21 |
22 | if (string.IsNullOrWhiteSpace(name))
23 | throw new InvalidOperationException("The specfied module must indicate a name.");
24 |
25 | if (m_modules.ContainsKey(name))
26 | throw new InvalidOperationException($"A module with the specified name ({name}) has already been registered.");
27 |
28 | m_modules.Add(name, module);
29 | }
30 |
31 | public Task GetModule(string name)
32 | {
33 | if (m_modules.ContainsKey(name))
34 | {
35 | return Task.FromResult(m_modules[name]);
36 | }
37 |
38 | return null;
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/benchmarks/BaristaLabs.BaristaCore.Benchmarks/Program.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Benchmarks
2 | {
3 | using BaristaLabs.BaristaCore.Extensions;
4 | using BenchmarkDotNet.Attributes;
5 | using BenchmarkDotNet.Running;
6 | using Microsoft.Extensions.DependencyInjection;
7 | using System;
8 |
9 | public class ComputeTheAnswerToTheUltimateQuestionOfLifeTheUniverseAndEverything
10 | {
11 | private IServiceProvider m_serviceProvider;
12 | private IBaristaRuntimeFactory m_runtimeFactory;
13 |
14 | public ComputeTheAnswerToTheUltimateQuestionOfLifeTheUniverseAndEverything()
15 | {
16 | var serviceCollection = new ServiceCollection();
17 | serviceCollection.AddBaristaCore();
18 |
19 | m_serviceProvider = serviceCollection.BuildServiceProvider();
20 | m_runtimeFactory = m_serviceProvider.GetRequiredService();
21 | }
22 |
23 | [Benchmark]
24 | public void EvaluateWithNoReuse()
25 | {
26 | using (var rt = m_runtimeFactory.CreateRuntime())
27 | using (var ctx = rt.CreateContext())
28 | {
29 | ctx.EvaluateModule("export default 6*7;");
30 | }
31 | }
32 | }
33 | class Program
34 | {
35 | static void Main(string[] args)
36 | {
37 | var summary = BenchmarkRunner.Run();
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Exceptions/JsFatalException.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using System;
4 |
5 | ///
6 | /// A fatal exception occurred.
7 | ///
8 | public sealed class JsFatalException : JsException
9 | {
10 | ///
11 | /// Initializes a new instance of the class.
12 | ///
13 | /// The error code returned.
14 | public JsFatalException(JsErrorCode code) :
15 | this(code, "A fatal exception has occurred in a JavaScript runtime")
16 | {
17 | }
18 |
19 | ///
20 | /// Initializes a new instance of the class.
21 | ///
22 | /// The error code returned.
23 | /// The error message.
24 | public JsFatalException(JsErrorCode code, string message) :
25 | base(code, message)
26 | {
27 | }
28 |
29 | ///
30 | /// Initializes a new instance of the class.
31 | ///
32 | /// The error message.
33 | /// The inner exception.
34 | private JsFatalException(string message, Exception innerException) :
35 | base(message, innerException)
36 | {
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Exceptions/JsUsageException.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using System;
4 |
5 | ///
6 | /// An API usage exception occurred.
7 | ///
8 | public sealed class JsUsageException : JsException
9 | {
10 | ///
11 | /// Initializes a new instance of the class.
12 | ///
13 | /// The error code returned.
14 | public JsUsageException(JsErrorCode code) :
15 | this(code, "A fatal exception has occurred in a JavaScript runtime")
16 | {
17 | }
18 |
19 | ///
20 | /// Initializes a new instance of the class.
21 | ///
22 | /// The error code returned.
23 | /// The error message.
24 | public JsUsageException(JsErrorCode code, string message) :
25 | base(code, message)
26 | {
27 | }
28 |
29 | ///
30 | /// Initializes a new instance of the class.
31 | ///
32 | /// The error message.
33 | /// The inner exception.
34 | private JsUsageException(string message, Exception innerException) :
35 | base(message, innerException)
36 | {
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Exceptions/JsEngineException.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using System;
4 |
5 | ///
6 | /// An exception that occurred in the workings of the JavaScript engine itself.
7 | ///
8 | public sealed class JsEngineException : JsException
9 | {
10 | ///
11 | /// Initializes a new instance of the class.
12 | ///
13 | /// The error code returned.
14 | public JsEngineException(JsErrorCode code) :
15 | this(code, "A fatal exception has occurred in a JavaScript runtime")
16 | {
17 | }
18 |
19 | ///
20 | /// Initializes a new instance of the class.
21 | ///
22 | /// The error code returned.
23 | /// The error message.
24 | public JsEngineException(JsErrorCode code, string message) :
25 | base(code, message)
26 | {
27 | }
28 |
29 | ///
30 | /// Initializes a new instance of the class.
31 | ///
32 | /// The error message.
33 | /// The inner exception.
34 | private JsEngineException(string message, Exception innerException) :
35 | base(message, innerException)
36 | {
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Portafilter/Properties/PublishProfiles/portafilter - Web Deploy.pubxml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 | MSDeploy
9 | AzureWebSite
10 | Release
11 | Any CPU
12 | http://portafilter.azurewebsites.net
13 | False
14 | False
15 | portafilter.scm.azurewebsites.net:443
16 | /subscriptions/bee6fbee-28c1-4350-a93e-be52baf36093/resourceGroups/portafilter/providers/Microsoft.Web/sites/portafilter
17 | portafilter
18 | True
19 | WMSVC
20 | True
21 | $portafilter
22 | <_SavePWD>True
23 | False
24 |
25 |
--------------------------------------------------------------------------------
/test/BaristaLabs.BaristaCore.Tests/JavaScriptReference_Facts.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Tests
2 | {
3 | using BaristaLabs.BaristaCore.JavaScript;
4 | using Xunit;
5 |
6 | public class JavaScriptReference_Facts
7 | {
8 | private IJavaScriptEngine Engine;
9 |
10 | public JavaScriptReference_Facts()
11 | {
12 | var chakraCoreFactory = new ChakraCoreFactory();
13 | Engine = chakraCoreFactory.CreateJavaScriptEngine();
14 | }
15 |
16 | [Fact]
17 | public void JsReferencesIndicateNativeFunctionSource()
18 | {
19 | using (var runtimeHandle = Engine.JsCreateRuntime(JavaScriptRuntimeAttributes.None, null))
20 | {
21 | Assert.Equal("JsCreateRuntime", runtimeHandle.NativeFunctionSource);
22 | }
23 | }
24 |
25 | [Fact]
26 | public void JsValueSafeHandlesAreNotSingletons()
27 | {
28 | using (var runtimeHandle = Engine.JsCreateRuntime(JavaScriptRuntimeAttributes.None, null))
29 | {
30 | using (var contextHandle = Engine.JsCreateContext(runtimeHandle))
31 | {
32 | Engine.JsSetCurrentContext(contextHandle);
33 |
34 | var trueHandle = Engine.JsGetTrueValue();
35 | var anotherTrueHandle = Engine.JsBoolToBoolean(true);
36 |
37 | Assert.Equal(trueHandle, anotherTrueHandle);
38 | Assert.NotSame(trueHandle, anotherTrueHandle);
39 | }
40 | }
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/BaristaLabs.BaristaCore.Common.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | BaristaLabs.BaristaCore
6 | BaristaLabs.BaristaCore.Common
7 | Full
8 | BaristaLabs, LLC
9 | Copyright (c) 2017 BaristaLabs, LLC
10 |
11 |
12 |
13 | AnyCPU
14 | TRACE;LIBLOG_PUBLIC;RELEASE;NETSTANDARD2_0
15 | latest
16 |
17 |
18 |
19 | AnyCPU
20 | TRACE;DEBUG;LIBLOG_PUBLIC;NETSTANDARD2_0
21 | latest
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Extensions/TaskExtensions.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Extensions
2 | {
3 | using System.Threading;
4 | using System.Threading.Tasks;
5 |
6 | ///
7 | /// Contains useful extension methods for tasks.
8 | ///
9 | public static class TaskExtensions
10 | {
11 | ///
12 | /// Returns a task that completes with the specified cancellation token requests cancellation.
13 | ///
14 | ///
15 | ///
16 | public static Task WhenCancelled(this CancellationToken cancellationToken)
17 | {
18 | var tcs = new TaskCompletionSource();
19 | cancellationToken.Register(s => ((TaskCompletionSource)s).SetResult(true), tcs);
20 | return tcs.Task;
21 | }
22 |
23 | public static object GetTaskResult(this Task task, out bool hasResult)
24 | {
25 | var taskType = task.GetType();
26 | if (!typeof(Task<>).IsSubclassOfRawGeneric(taskType))
27 | {
28 | hasResult = false;
29 | return null;
30 | }
31 |
32 | hasResult = true;
33 | var resultProperty = taskType.GetProperty("Result");
34 | var result = resultProperty.GetValue(task);
35 |
36 | if (result is Task resultTask)
37 | {
38 | result = resultTask.GetTaskResult(out hasResult);
39 | }
40 |
41 | return result;
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/BuiltIns/JsPropertyDescriptor.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | public class JsPropertyDescriptor
4 | {
5 | public bool Configurable
6 | {
7 | get;
8 | set;
9 | }
10 |
11 | public bool Enumerable
12 | {
13 | get;
14 | set;
15 | }
16 |
17 | public bool Writable
18 | {
19 | get;
20 | set;
21 | }
22 |
23 | public JsFunction Get
24 | {
25 | get;
26 | set;
27 | }
28 |
29 | public JsFunction Set
30 | {
31 | get;
32 | set;
33 | }
34 |
35 | public JsValue Value
36 | {
37 | get;
38 | set;
39 | }
40 |
41 | public JsObject GetDescriptorObject(BaristaContext context)
42 | {
43 | var descriptor = context.CreateObject();
44 | if (Configurable)
45 | descriptor.SetProperty("configurable", context.True);
46 | if (Enumerable)
47 | descriptor.SetProperty("enumerable", context.True);
48 | if (Writable)
49 | descriptor.SetProperty("enumerable", context.True);
50 |
51 | if (Get != null)
52 | descriptor.SetProperty("get", Get);
53 |
54 | if (Set != null)
55 | descriptor.SetProperty("set", Set);
56 |
57 | if (Value != null)
58 | descriptor.SetProperty("value", Value);
59 |
60 | return descriptor;
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Portafilter/BaristaLabs.BaristaCore.Portafilter.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | netstandard2.0
4 | v2
5 |
6 |
7 | AnyCPU
8 |
9 |
10 | AnyCPU
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 | PreserveNewest
22 |
23 |
24 | PreserveNewest
25 | Never
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/test/BaristaLabs.BaristaCore.Tests/JavaScriptPropertyId_Facts.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Tests
2 | {
3 | using BaristaCore.Extensions;
4 | using Microsoft.Extensions.DependencyInjection;
5 | using System;
6 | using Xunit;
7 |
8 | [Collection("BaristaCore Tests")]
9 | public class JavaScriptPropertyId_Facts
10 | {
11 | private readonly ServiceCollection ServiceCollection;
12 | private readonly IServiceProvider m_provider;
13 |
14 | public JavaScriptPropertyId_Facts()
15 | {
16 | ServiceCollection = new ServiceCollection();
17 | ServiceCollection.AddBaristaCore();
18 |
19 | m_provider = ServiceCollection.BuildServiceProvider();
20 | }
21 |
22 | public IBaristaRuntimeFactory BaristaRuntimeFactory
23 | {
24 | get { return m_provider.GetRequiredService(); }
25 | }
26 |
27 | [Fact]
28 | public void JsPropertyIdCanBeCreated()
29 | {
30 | using (var rt = BaristaRuntimeFactory.CreateRuntime())
31 | {
32 | using (var ctx = rt.CreateContext())
33 | {
34 | using (ctx.Scope())
35 | {
36 | //TODO: This might not be the final signature -- creating a propertyid requires a current context.
37 | var propertyId = JsPropertyId.FromString(rt.Engine, "foo");
38 | Assert.NotNull(propertyId);
39 | propertyId.Dispose();
40 | }
41 | }
42 | }
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Internal/Helpers.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript.Internal
2 | {
3 | using System;
4 | using System.Text;
5 |
6 | ///
7 | /// Contains helper methods using only native calls
8 | ///
9 | ///
10 | /// These methods serve as helper functions to internal classes and aren't meant for general use. IJavaScriptRuntimeExtensions are better suited for public consumption.
11 | ///
12 | public static class Helpers
13 | {
14 | public static string GetStringUtf8(JavaScriptValueSafeHandle stringHandle, bool releaseHandle = false)
15 | {
16 | bool stringHandleWasCreated = false;
17 | if (stringHandle == null || stringHandle == JavaScriptValueSafeHandle.Invalid)
18 | throw new ArgumentNullException(nameof(stringHandle));
19 |
20 | //Don't use our helper error class in order to prevent recursive errors.
21 | JsErrorCode innerError;
22 |
23 | //Get the size
24 | innerError = LibChakraCore.JsCopyString(stringHandle, null, 0, out ulong size);
25 |
26 | if ((int)size > int.MaxValue)
27 | throw new OutOfMemoryException("Exceeded maximum string length.");
28 |
29 | byte[] result = new byte[(int)size];
30 | innerError = LibChakraCore.JsCopyString(stringHandle, result, (ulong)result.Length, out ulong written);
31 |
32 | var strResult = Encoding.UTF8.GetString(result, 0, result.Length);
33 |
34 | if (stringHandleWasCreated || releaseHandle)
35 | stringHandle.Dispose();
36 |
37 | return strResult;
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.AspNetCore.Common/BaristaContextModule.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.AspNetCore
2 | {
3 | using Microsoft.AspNetCore.Http;
4 | using System;
5 |
6 | [BaristaModule("barista-context", "Contains the current context of the Barista Function, including the current request object.")]
7 | public sealed class BaristaContextModule : IBaristaModule
8 | {
9 | private readonly HttpRequest m_request;
10 |
11 | public BaristaContextModule(HttpRequest request)
12 | {
13 | m_request = request ?? throw new ArgumentNullException(nameof(request));
14 | }
15 |
16 | public JsValue ExportDefault(BaristaContext context, BaristaModuleRecord referencingModule)
17 | {
18 | var brewRequest = new BrewRequest(context, m_request);
19 |
20 | context.Converter.TryFromObject(context, brewRequest, out JsValue requestObj);
21 | context.Converter.TryFromObject(context, typeof(BrewResponse), out JsValue responseObj);
22 | //context.Converter.TryFromObject(context, m_log, out JsValue logObj);
23 |
24 | var contextObj = context.CreateObject();
25 | context.Object.DefineProperty(contextObj, "request", new JsPropertyDescriptor()
26 | {
27 | Configurable = false,
28 | Writable = false,
29 | Value = requestObj
30 | });
31 |
32 | context.Object.DefineProperty(contextObj, "response", new JsPropertyDescriptor()
33 | {
34 | Configurable = false,
35 | Writable = false,
36 | Value = responseObj
37 | });
38 |
39 | return contextObj;
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/test/BaristaLabs.BaristaCore.Extensions.Tests/Lodash_Facts.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Extensions.Tests
2 | {
3 | using BaristaLabs.BaristaCore.Extensions;
4 | using BaristaLabs.BaristaCore.ModuleLoaders;
5 | using BaristaLabs.BaristaCore.Modules;
6 | using Microsoft.Extensions.DependencyInjection;
7 | using Xunit;
8 |
9 | public class Lodash_Facts
10 | {
11 | public IBaristaRuntimeFactory GetRuntimeFactory()
12 | {
13 | var myMemoryModuleLoader = new InMemoryModuleLoader();
14 | myMemoryModuleLoader.RegisterModule(new LodashModule());
15 |
16 | var serviceCollection = new ServiceCollection();
17 | serviceCollection.AddBaristaCore(moduleLoader: myMemoryModuleLoader);
18 |
19 | var provider = serviceCollection.BuildServiceProvider();
20 | return provider.GetRequiredService();
21 | }
22 |
23 | [Fact]
24 | public void CanUseLodashMethods()
25 | {
26 | var script = @"
27 | import _ from 'lodash';
28 | export default _.capitalize('FRED');
29 | ";
30 |
31 | var baristaRuntime = GetRuntimeFactory();
32 |
33 | using (var rt = baristaRuntime.CreateRuntime())
34 | {
35 | using (var ctx = rt.CreateContext())
36 | {
37 | using (ctx.Scope())
38 | {
39 | var response = ctx.EvaluateModule(script);
40 | Assert.NotNull(response);
41 | Assert.IsType(response);
42 | Assert.Equal("Fred", response.ToString());
43 | }
44 | }
45 | }
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Modules/BaristaScriptModule.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Modules
2 | {
3 | using System;
4 |
5 | ///
6 | /// Represents a module that returns a script that will be parsed when imported.
7 | ///
8 | [BaristaModule("ScriptModule", "Built-in module that allows for specifing the script as a string. Not to be imported directly by scripts.", IsDiscoverable = false)]
9 | public sealed class BaristaScriptModule : IBaristaScriptModule
10 | {
11 | private readonly string m_name;
12 | private readonly string m_description;
13 |
14 | public BaristaScriptModule(string name, string description = null)
15 | {
16 | if (string.IsNullOrWhiteSpace(name))
17 | throw new ArgumentNullException(nameof(name));
18 |
19 | m_name = name;
20 | m_description = description;
21 | }
22 |
23 | ///
24 | /// Gets the name of the script module.
25 | ///
26 | public string Name
27 | {
28 | get { return m_name; }
29 | }
30 |
31 | ///
32 | /// Gets the description of the script module.
33 | ///
34 | public string Description
35 | {
36 | get { return m_description; }
37 | }
38 |
39 | ///
40 | /// Gets or sets the script that will be executed.
41 | ///
42 | public string Script
43 | {
44 | get;
45 | set;
46 | }
47 |
48 | public JsValue ExportDefault(BaristaContext context, BaristaModuleRecord referencingModule)
49 | {
50 | return context.CreateString(Script);
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/test/BaristaLabs.BaristaCore.Extensions.Tests/Uuid_Facts.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Extensions.Tests
2 | {
3 | using BaristaLabs.BaristaCore.Extensions;
4 | using BaristaLabs.BaristaCore.ModuleLoaders;
5 | using BaristaLabs.BaristaCore.Modules;
6 | using Microsoft.Extensions.DependencyInjection;
7 | using Xunit;
8 |
9 | public class Uuid_Facts
10 | {
11 | public IBaristaRuntimeFactory GetRuntimeFactory()
12 | {
13 | var myMemoryModuleLoader = new InMemoryModuleLoader();
14 | myMemoryModuleLoader.RegisterModule(new UuidModule());
15 |
16 | var serviceCollection = new ServiceCollection();
17 | serviceCollection.AddBaristaCore(moduleLoader: myMemoryModuleLoader);
18 |
19 | var provider = serviceCollection.BuildServiceProvider();
20 | return provider.GetRequiredService();
21 | }
22 |
23 | [Fact]
24 | public void CanGenerateUuids()
25 | {
26 | var script = @"
27 | import uuid from 'uuid';
28 | export default uuid();
29 | ";
30 |
31 | var baristaRuntime = GetRuntimeFactory();
32 |
33 | using (var rt = baristaRuntime.CreateRuntime())
34 | {
35 | using (var ctx = rt.CreateContext())
36 | {
37 | using (ctx.Scope())
38 | {
39 | var response = ctx.EvaluateModule(script);
40 | Assert.NotNull(response);
41 | Assert.IsType(response);
42 | Assert.True(System.Guid.TryParseExact(response.ToString(), "D", out System.Guid uuid));
43 | }
44 | }
45 | }
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/BuiltIns/JsExternalArrayBuffer.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using BaristaLabs.BaristaCore.JavaScript;
4 | using System;
5 |
6 | ///
7 | /// Represents a external array buffer.
8 | ///
9 | public class JsExternalArrayBuffer : JsArrayBuffer
10 | {
11 | protected JsExternalArrayBuffer(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle valueHandle)
12 | : base(engine, context, valueHandle)
13 | {
14 | }
15 | }
16 |
17 | ///
18 | /// Represents an external array buffer that is backed by memory managed by the application.
19 | ///
20 | public sealed class JsManagedExternalArrayBuffer : JsExternalArrayBuffer
21 | {
22 | private IntPtr m_bufferHandle;
23 |
24 | public JsManagedExternalArrayBuffer(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle valueHandle, IntPtr bufferHandle)
25 | : base(engine, context, valueHandle)
26 | {
27 | if (bufferHandle == default(IntPtr) || bufferHandle == null)
28 | throw new ArgumentNullException(nameof(bufferHandle));
29 | m_bufferHandle = bufferHandle;
30 | }
31 |
32 | ///
33 | /// Gets the underlying GCHandle.
34 | ///
35 | public IntPtr BufferHandle
36 | {
37 | get { return m_bufferHandle; }
38 | }
39 |
40 | protected override void Dispose(bool disposing)
41 | {
42 | if (m_bufferHandle != default(IntPtr))
43 | {
44 | m_bufferHandle = default(IntPtr);
45 | }
46 |
47 | base.Dispose(disposing);
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/test/BaristaLabs.BaristaCore.Extensions.Tests/React_Facts.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Extensions.Tests
2 | {
3 | using BaristaLabs.BaristaCore.Extensions;
4 | using BaristaLabs.BaristaCore.ModuleLoaders;
5 | using BaristaLabs.BaristaCore.Modules;
6 | using Microsoft.Extensions.DependencyInjection;
7 | using Xunit;
8 |
9 | public class React_Facts
10 | {
11 | public IBaristaRuntimeFactory GetRuntimeFactory()
12 | {
13 | var myMemoryModuleLoader = new InMemoryModuleLoader();
14 | myMemoryModuleLoader.RegisterModule(new ReactModule());
15 |
16 | var serviceCollection = new ServiceCollection();
17 | serviceCollection.AddBaristaCore(moduleLoader: myMemoryModuleLoader);
18 |
19 | var provider = serviceCollection.BuildServiceProvider();
20 | return provider.GetRequiredService();
21 | }
22 |
23 | [Fact]
24 | public void CanUseReactComponent()
25 | {
26 | var script = @"
27 | import React from 'react';
28 |
29 | class MyComponent extends React.Component {
30 | render() {
31 | return 'foo';
32 | }
33 | }
34 |
35 | export default MyComponent;
36 | ";
37 |
38 | var baristaRuntime = GetRuntimeFactory();
39 |
40 | using (var rt = baristaRuntime.CreateRuntime())
41 | {
42 | using (var ctx = rt.CreateContext())
43 | {
44 | using (ctx.Scope())
45 | {
46 | var response = ctx.EvaluateModule(script);
47 | Assert.NotNull(response);
48 | Assert.IsType(response);
49 | }
50 | }
51 | }
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/test/BaristaLabs.BaristaCore.Extensions.Tests/Moment_Facts.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Extensions.Tests
2 | {
3 | using BaristaLabs.BaristaCore.Extensions;
4 | using BaristaLabs.BaristaCore.ModuleLoaders;
5 | using BaristaLabs.BaristaCore.Modules;
6 | using Microsoft.Extensions.DependencyInjection;
7 | using Xunit;
8 |
9 | public class Moment_Facts
10 | {
11 | public IBaristaRuntimeFactory GetRuntimeFactory()
12 | {
13 | var myMemoryModuleLoader = new InMemoryModuleLoader();
14 | myMemoryModuleLoader.RegisterModule(new MomentModule());
15 |
16 | var serviceCollection = new ServiceCollection();
17 | serviceCollection.AddBaristaCore(moduleLoader: myMemoryModuleLoader);
18 |
19 | var provider = serviceCollection.BuildServiceProvider();
20 | return provider.GetRequiredService();
21 | }
22 |
23 | [Fact]
24 | public void CanUseMomentMethods()
25 | {
26 | var script = @"
27 | import moment from 'moment';
28 | export default moment('20111031', 'YYYYMMDD').format('MMMM Do YYYY');
29 | ";
30 |
31 | var baristaRuntime = GetRuntimeFactory();
32 |
33 | using (var rt = baristaRuntime.CreateRuntime())
34 | {
35 | using (var ctx = rt.CreateContext())
36 | {
37 | using (ctx.Scope())
38 | {
39 | var response = ctx.EvaluateModule(script);
40 | Assert.NotNull(response);
41 | Assert.IsType(response);
42 | Assert.Equal("October 31st 2011", response.ToString());
43 | }
44 | }
45 | }
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/package.ps1:
--------------------------------------------------------------------------------
1 | $CONFIGURATION = "Release"
2 | $FRAMEWORK = "netstandard2.0"
3 |
4 | $root = (split-path -parent $MyInvocation.MyCommand.Definition)
5 | $packageRoot = "$root\nuget"
6 | $versionFile = "$packageRoot\.version"
7 | $artifactsPath = "$packageRoot\artifacts"
8 |
9 | #Delete any existing artifacts
10 | If (Test-Path $artifactsPath)
11 | {
12 | Remove-Item $artifactsPath\*.nupkg
13 | }
14 |
15 | $common = "$root\src\BaristaLabs.BaristaCore.Common\"
16 | $extensions = "$root\src\BaristaLabs.BaristaCore.Extensions\"
17 | $aspnetcorecommon = "$root\src\BaristaLabs.BaristaCore.AspNetCore.Common\"
18 | dotnet build -c $CONFIGURATION -f $FRAMEWORK $common
19 | dotnet build -c $CONFIGURATION -f $FRAMEWORK $extensions
20 | dotnet build -c $CONFIGURATION -f $FRAMEWORK $aspnetcorecommon
21 |
22 | $VERSION = (Get-Content $versionFile)
23 | Write-Host "Setting .nuspec version tag to $VERSION"
24 | $compiledNuspec = "$packageRoot\compiled.nuspec"
25 |
26 | # Create new packages for any nuspec files that exist in this directory.
27 | Foreach ($nuspec in $(Get-Item "$packageRoot\*.nuspec"))
28 | {
29 | $content = (Get-Content $nuspec)
30 | $content = $content -replace '\$version\$',$VERSION
31 | $content = $content -replace '\$configuration\$',$CONFIGURATION
32 | $content = $content -replace '\$framework\$',$FRAMEWORK
33 | $content = $content -replace '\$root\$',$root
34 | $content | Out-File $compiledNuspec
35 |
36 | & nuget pack $compiledNuspec -outputdirectory $artifactsPath
37 | }
38 |
39 | # Delete compiled temporary nuspec.
40 | If (Test-Path $compiledNuspec)
41 | {
42 | Remove-Item $compiledNuspec
43 | }
44 |
45 | # Publish new packages for any nupkg files that exist in this directory.
46 | Foreach ($nupkg in $(Get-Item $artifactsPath\*.nupkg))
47 | {
48 | & nuget push $nupkg -Source https://api.nuget.org/v3/index.json
49 | }
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.AspNetCore.Common/IBaristaPipeline.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.AspNetCore
2 | {
3 | using BaristaLabs.BaristaCore.ModuleLoaders;
4 | using Microsoft.AspNetCore.Http;
5 | using System.Net.Http;
6 | using System.Threading.Tasks;
7 |
8 | public interface IBaristaPipeline
9 | {
10 | ///
11 | /// Takes the order. E.g. From the http request, gets the script that needs to be brewed.
12 | ///
13 | ///
14 | ///
15 | Task TakeOrder(string path, HttpRequest req);
16 |
17 | ///
18 | /// Tamps the brew request. E.g. Sets up any module loaders that need to be associated as part of the brew.
19 | ///
20 | ///
21 | ///
22 | IBaristaModuleLoader Tamp(BrewOrder brewOrder, HttpRequest req);
23 |
24 | ///
25 | /// Pulls the shot of espresso
26 | ///
27 | ///
28 | ///
29 | ///
30 | ///
31 | HttpResponseMessage Brew(BrewOrder brewOrder, IBaristaRuntimeFactory baristaRuntimeFactory, IBaristaModuleLoader moduleLoader);
32 |
33 | ///
34 | /// Serves the brew. E.g. Now that the coffee, now in liquid form, has been extracted, provide the http response back to the requestor.
35 | ///
36 | ///
37 | ///
38 | ///
39 | HttpResponseMessage Serve(BaristaContext context, JsValue brewResult);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | // Use IntelliSense to find out which attributes exist for C# debugging
3 | // Use hover for the description of the existing attributes
4 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
5 | "version": "0.2.0",
6 | "configurations": [
7 | {
8 | "name": ".NET Core Launch (web)",
9 | "type": "coreclr",
10 | "request": "launch",
11 | "preLaunchTask": "build",
12 | // If you have changed target frameworks, make sure to update the program path.
13 | "program": "${workspaceFolder}/src/BaristaServer/bin/Debug/netcoreapp2.0/BaristaServer.dll",
14 | "args": [],
15 | "cwd": "${workspaceFolder}/src/BaristaServer",
16 | "stopAtEntry": false,
17 | "internalConsoleOptions": "openOnSessionStart",
18 | "launchBrowser": {
19 | "enabled": true,
20 | "args": "${auto-detect-url}",
21 | "windows": {
22 | "command": "cmd.exe",
23 | "args": "/C start ${auto-detect-url}"
24 | },
25 | "osx": {
26 | "command": "open"
27 | },
28 | "linux": {
29 | "command": "xdg-open"
30 | }
31 | },
32 | "env": {
33 | "ASPNETCORE_ENVIRONMENT": "Development"
34 | },
35 | "sourceFileMap": {
36 | "/Views": "${workspaceFolder}/Views"
37 | }
38 | },
39 | {
40 | "name": ".NET Core Attach",
41 | "type": "coreclr",
42 | "request": "attach",
43 | "processId": "${command:pickProcess}"
44 | }
45 | ]
46 | }
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/BuiltIns/JsNumber.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using BaristaLabs.BaristaCore.JavaScript;
4 | using System;
5 |
6 | ///
7 | /// Represents a JavaScript Numeric Value
8 | ///
9 | public sealed class JsNumber : JsObject
10 | {
11 | public JsNumber(IJavaScriptEngine engine, BaristaContext context,JavaScriptValueSafeHandle valueHandle)
12 | : base(engine, context, valueHandle)
13 | {
14 | }
15 |
16 | public override JsValueType Type
17 | {
18 | get { return JsValueType.Number; }
19 | }
20 |
21 | ///
22 | /// Returns the double representation of the numeric value.
23 | ///
24 | ///
25 | public override double ToDouble()
26 | {
27 | if (IsDisposed)
28 | throw new ObjectDisposedException(nameof(JsValue));
29 |
30 | return Engine.JsNumberToDouble(Handle);
31 | }
32 |
33 | ///
34 | /// Returns the integer representation of the numeric value.
35 | ///
36 | ///
37 | public override int ToInt32()
38 | {
39 | if (IsDisposed)
40 | throw new ObjectDisposedException(nameof(JsValue));
41 |
42 | return Engine.JsNumberToInt(Handle);
43 | }
44 |
45 | ///
46 | /// Returns the long representation of the numeric value.
47 | ///
48 | ///
49 | public long ToInt64()
50 | {
51 | if (IsDisposed)
52 | throw new ObjectDisposedException(nameof(JsValue));
53 |
54 | throw new NotImplementedException();
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/test/BaristaLabs.BaristaCore.Extensions.Tests/Handlebars_Facts.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Extensions.Tests
2 | {
3 | using BaristaLabs.BaristaCore.Extensions;
4 | using BaristaLabs.BaristaCore.ModuleLoaders;
5 | using BaristaLabs.BaristaCore.Modules;
6 | using Microsoft.Extensions.DependencyInjection;
7 | using Xunit;
8 |
9 | public class Handlebars_Facts
10 | {
11 | public IBaristaRuntimeFactory GetRuntimeFactory()
12 | {
13 | var myMemoryModuleLoader = new InMemoryModuleLoader();
14 | myMemoryModuleLoader.RegisterModule(new HandlebarsModule());
15 |
16 | var serviceCollection = new ServiceCollection();
17 | serviceCollection.AddBaristaCore(moduleLoader: myMemoryModuleLoader);
18 |
19 | var provider = serviceCollection.BuildServiceProvider();
20 | return provider.GetRequiredService();
21 | }
22 |
23 | [Fact]
24 | public void CanCompileTemplateUsingHandlebars()
25 | {
26 | var script = @"
27 | import Handlebars from 'handlebars';
28 |
29 | var template = Handlebars.compile('Holy {{foo}}, it\'s a {{bar}}!');
30 | var result = template({ foo: 'cow', bar: 'Scottie' });
31 |
32 | export default result;
33 | ";
34 |
35 | var baristaRuntime = GetRuntimeFactory();
36 |
37 | using (var rt = baristaRuntime.CreateRuntime())
38 | {
39 | using (var ctx = rt.CreateContext())
40 | {
41 | using (ctx.Scope())
42 | {
43 | var response = ctx.EvaluateModule(script);
44 | Assert.Equal("Holy cow, it's a Scottie!", response.ToString());
45 | }
46 | }
47 | }
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Modules/RawTextModule.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Modules
2 | {
3 | using System;
4 |
5 | ///
6 | /// Module that returns a text value as its default export.
7 | ///
8 | [BaristaModule("barista-raw-text", "Built-in module that returns a text value. Not to be imported directly by scripts.", IsDiscoverable = false)]
9 | public class RawTextModule : IBaristaModule
10 | {
11 | private readonly string m_name;
12 | private readonly string m_description;
13 | private readonly string m_rawText;
14 |
15 | public RawTextModule(string name, string description, string rawText)
16 | {
17 | if (string.IsNullOrWhiteSpace(name))
18 | throw new ArgumentNullException(nameof(name));
19 |
20 | m_name = name;
21 | m_description = description;
22 | m_rawText = rawText ?? throw new ArgumentNullException(nameof(rawText));
23 | }
24 |
25 | ///
26 | /// Gets the name of the raw text module.
27 | ///
28 | public string Name
29 | {
30 | get { return m_name; }
31 | }
32 |
33 | ///
34 | /// Gets the description of the raw text module.
35 | ///
36 | public string Description
37 | {
38 | get { return m_description; }
39 | }
40 |
41 | ///
42 | /// Gets the text associated with the module.
43 | ///
44 | public string RawText
45 | {
46 | get { return m_rawText; }
47 | }
48 |
49 | public JsValue ExportDefault(BaristaContext context, BaristaModuleRecord referencingModule)
50 | {
51 | return context.CreateString(m_rawText);
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Modules/JsonModule.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Modules
2 | {
3 | using System;
4 |
5 | ///
6 | /// Module that returns a json object as its default export.
7 | ///
8 | [BaristaModule("barista-json", "Built-in module that returns a json object. Not to be imported directly by scripts.", IsDiscoverable = false)]
9 | public class JsonModule : IBaristaModule
10 | {
11 | private readonly string m_name;
12 | private readonly string m_description;
13 | private readonly string m_jsonText;
14 |
15 | public JsonModule(string name, string description, string jsonText)
16 | {
17 | if (string.IsNullOrWhiteSpace(name))
18 | throw new ArgumentNullException(nameof(name));
19 |
20 | m_name = name;
21 | m_description = description;
22 | m_jsonText = jsonText ?? throw new ArgumentNullException(nameof(jsonText));
23 | }
24 |
25 | ///
26 | /// Gets the name of the json module.
27 | ///
28 | public string Name
29 | {
30 | get { return m_name; }
31 | }
32 |
33 | ///
34 | /// Gets the description of the json module.
35 | ///
36 | public string Description
37 | {
38 | get { return m_description; }
39 | }
40 |
41 | ///
42 | /// Gets the json text associated with the module.
43 | ///
44 | public string JsonText
45 | {
46 | get { return m_jsonText; }
47 | }
48 |
49 | public JsValue ExportDefault(BaristaContext context, BaristaModuleRecord referencingModule)
50 | {
51 | return context.JSON.Parse(context.CreateString(JsonText));
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Tasks/CurrentThreadTaskScheduler.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Tasks
2 | {
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Threading.Tasks;
6 |
7 | ///
8 | /// Provides a task scheduler that runs tasks on the current thread.
9 | ///
10 | public sealed class CurrentThreadTaskScheduler : TaskScheduler
11 | {
12 | ///
13 | /// Runs the provided Task synchronously on the current thread.
14 | ///
15 | /// The task to be executed.
16 | protected override void QueueTask(Task task)
17 | {
18 | TryExecuteTask(task);
19 | }
20 |
21 | ///
22 | /// Runs the provided Task synchronously on the current thread.
23 | ///
24 | /// The task to be executed.
25 | /// Whether the Task was previously queued to the scheduler.
26 | /// True if the Task was successfully executed; otherwise, false.
27 | protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
28 | {
29 | return TryExecuteTask(task);
30 | }
31 |
32 | ///
33 | /// Gets the Tasks currently scheduled to this scheduler.
34 | ///
35 | /// An empty enumerable, as Tasks are never queued, only executed.
36 | protected override IEnumerable GetScheduledTasks()
37 | {
38 | return Enumerable.Empty();
39 | }
40 |
41 | /// Gets the maximum degree of parallelism for this scheduler.
42 | public override int MaximumConcurrencyLevel { get { return 1; } }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/Modules/RawBlobModule.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Modules
2 | {
3 | using System;
4 |
5 | ///
6 | /// Module that returns a blob as its default export.
7 | ///
8 | [BaristaModule("barista-raw-blob", "Built-in module that returns a blob value. Not to be imported directly by scripts.", IsDiscoverable = false)]
9 | public class RawBlobModule : IBaristaModule
10 | {
11 | private readonly string m_name;
12 | private readonly string m_description;
13 | private readonly Blob m_blob;
14 |
15 | public RawBlobModule(string name, string description, Blob blob)
16 | {
17 | if (string.IsNullOrWhiteSpace(name))
18 | throw new ArgumentNullException(nameof(name));
19 |
20 | m_name = name;
21 | m_description = description;
22 | m_blob = blob ?? throw new ArgumentNullException(nameof(blob));
23 | }
24 |
25 | ///
26 | /// Gets the name of the raw blob module.
27 | ///
28 | public string Name
29 | {
30 | get { return m_name; }
31 | }
32 |
33 | ///
34 | /// Gets the description of the raw blob module.
35 | ///
36 | public string Description
37 | {
38 | get { return m_description; }
39 | }
40 |
41 | ///
42 | /// Gets the blob associated with the module.
43 | ///
44 | public Blob Blob
45 | {
46 | get { return m_blob; }
47 | }
48 |
49 | public JsValue ExportDefault(BaristaContext context, BaristaModuleRecord referencingModule)
50 | {
51 | context.Converter.TryFromObject(context, m_blob, out JsValue value);
52 | return value;
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Extensions/Modules/FetchModule.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Modules
2 | {
3 | using System;
4 |
5 | [BaristaModule("barista-fetch", "Provides a subset of the standard Fetch Specification.")]
6 | public class FetchModule : IBaristaModule
7 | {
8 | public JsValue ExportDefault(BaristaContext context, BaristaModuleRecord referencingModule)
9 | {
10 | var fnFetch = context.CreateFunction(new Func((thisObj, input, init) =>
11 | {
12 | Request request;
13 | if (input is JsObject inputObj && inputObj.Type == JsValueType.Object && inputObj.TryGetBean(out JsExternalObject exObj) && exObj.Target is Request inputRequest)
14 | {
15 | request = new Request(inputRequest);
16 | }
17 | else
18 | {
19 | request = new Request(input.ToString(), init);
20 | }
21 |
22 | return request.Execute(context);
23 | }));
24 |
25 | if (context.Converter.TryFromObject(context, typeof(Body), out JsValue fnBody))
26 | {
27 | fnFetch["Body"] = fnBody;
28 | }
29 |
30 | if (context.Converter.TryFromObject(context, typeof(Headers), out JsValue fnHeaders))
31 | {
32 | fnFetch["Headers"] = fnHeaders;
33 | }
34 |
35 | if (context.Converter.TryFromObject(context, typeof(Request), out JsValue fnRequest))
36 | {
37 | fnFetch["Request"] = fnRequest;
38 | }
39 |
40 | if (context.Converter.TryFromObject(context, typeof(Request), out JsValue fnResponse))
41 | {
42 | fnFetch["Response"] = fnResponse;
43 | }
44 |
45 | return fnFetch;
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/util/ChakraWrapperGeneratorCLI/ChakraWrapperGeneratorCLI.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp2.2
6 | AnyCPU;x64
7 |
8 |
9 |
10 | latest
11 |
12 |
13 |
14 | latest
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 | PreserveNewest
28 |
29 |
30 | PreserveNewest
31 |
32 |
33 | PreserveNewest
34 |
35 |
36 | PreserveNewest
37 |
38 |
39 | PreserveNewest
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Callbacks/JavaScriptPromiseRejectionTrackerCallback.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 |
5 | ///
6 | /// A Promise Rejection Tracker callback.
7 | ///
8 | ///
9 | /// The host can specify a promise rejection tracker callback in JsSetHostPromiseRejectionTracker.
10 | /// If a promise is rejected with no reactions or a reaction is added to a promise that was rejected
11 | /// before it had reactions by default nothing is done.
12 | /// A Promise Rejection Tracker callback may be set - which will then be called when this occurs.
13 | /// Note - per draft ECMASpec 2018 25.4.1.9 this function should not set or return an exception
14 | /// Note also the promise and reason parameters may be garbage collected after this function is called
15 | /// if you wish to make further use of them you will need to use JsAddRef to preserve them
16 | /// However if you use JsAddRef you must also call JsRelease and not hold unto them after
17 | /// a handled notification (both per spec and to avoid memory leaks)
18 | ///
19 | /// The promise object, represented as a JsValueRef.
20 | /// The value/cause of the rejection, represented as a JsValueRef.
21 | /// Boolean - false for promiseRejected: i.e. if the promise has just been rejected with no handler,
22 | /// true for promiseHandled: i.e. if it was rejected before without a handler and is now being handled.
23 | /// The state passed to JsSetHostPromiseRejectionTracker.
24 | public delegate void JavaScriptPromiseRejectionTrackerCallback(JavaScriptValueSafeHandle promise, JavaScriptValueSafeHandle reason, bool handled, IntPtr callbackState);
25 | }
26 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: generic
2 |
3 | cache:
4 | directories:
5 | - $HOME/.nuget/packages
6 |
7 | addons:
8 | apt:
9 | packages:
10 | - build-essential
11 | - gettext
12 | - clang-3.8
13 | - cmake
14 | - libcurl4-openssl-dev
15 | - libicu-dev
16 | - libssl-dev
17 | - libunwind8
18 | - libunwind8-dev
19 | - zlib1g
20 |
21 | matrix:
22 | include:
23 | - os: linux
24 | dist: trusty
25 | sudo: required
26 | compiler: clang
27 | runtime:
28 | - name: netcore
29 | version: 2
30 | env: CONFIGURATION=Release FRAMEWORK=netcoreapp2.2
31 | - os: osx
32 | osx_image: xcode9.1
33 | runtime:
34 | - name: netcore
35 | version: 2
36 | env: CONFIGURATION=Release FRAMEWORK=netcoreapp2.2
37 |
38 | before_install:
39 | - if test "$TRAVIS_OS_NAME" == "osx"; then
40 | sw_vers -productVersion;
41 | sudo curl -sSL https://dot.net/v1/dotnet-install.sh | bash /dev/stdin --channel 2.2;
42 | eval $(/usr/libexec/path_helper -s);
43 | PATH="$HOME/.dotnet":"$PATH";
44 | else
45 | lsb_release -a;
46 | which $cc;
47 | sudo apt-get install curl;
48 | sudo curl -sSL https://dot.net/v1/dotnet-install.sh | bash /dev/stdin --channel 2.2;
49 | PATH="$HOME/.dotnet":"$PATH";
50 | fi;
51 |
52 | install:
53 | # Display dotnet version info
54 | - which dotnet;
55 | if [ $? -eq 0 ]; then
56 | echo "Using dotnet:";
57 | dotnet --info;
58 | else
59 | echo "dotnet.exe not found";
60 | exit 1;
61 | fi
62 |
63 | script:
64 | # Run tests
65 | - dotnet test -c $CONFIGURATION -f $FRAMEWORK ./test/BaristaLabs.BaristaCore.Tests/ /p:CollectCoverage=true /p:CoverletOutputFormat=\"cobertura,opencover\" /p:Exclude=[xunit.*]*
66 | - dotnet test -c $CONFIGURATION -f $FRAMEWORK ./test/BaristaLabs.BaristaCore.Extensions.Tests/ /p:CollectCoverage=true /p:CoverletOutputFormat=\"cobertura,opencover\" /p:Exclude=[xunit.*]*
--------------------------------------------------------------------------------
/test/BaristaLabs.BaristaCore.MyTestModule/DisposableTestModule.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.MyTestModule
2 | {
3 | using System;
4 | using System.Diagnostics.CodeAnalysis;
5 |
6 | [BaristaModule("MyDisposableTestModule", "This is a test, this is only a test.")]
7 | [ExcludeFromCodeCoverage]
8 | public class DisposableTestModule : IBaristaModule, IDisposable
9 | {
10 | public JsValue ExportDefault(BaristaContext context, BaristaModuleRecord referencingModule)
11 | {
12 | return context.CreateString("The maze still isn't meant for you.");
13 | }
14 |
15 | #region IDisposable Support
16 | public bool IsDisposed = false; // To detect redundant calls
17 |
18 | protected virtual void Dispose(bool disposing)
19 | {
20 | if (!IsDisposed)
21 | {
22 | if (disposing)
23 | {
24 | // TODO: dispose managed state (managed objects).
25 | }
26 |
27 | // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
28 | // TODO: set large fields to null.
29 |
30 | IsDisposed = true;
31 | }
32 | }
33 |
34 | // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
35 | // ~DisposableTestModule() {
36 | // // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
37 | // Dispose(false);
38 | // }
39 |
40 | // This code added to correctly implement the disposable pattern.
41 | public void Dispose()
42 | {
43 | // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
44 | Dispose(true);
45 | // TODO: uncomment the following line if the finalizer is overridden above.
46 | // GC.SuppressFinalize(this);
47 | }
48 | #endregion
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.AspNetCore.Common/BaristaPipeline.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.AspNetCore
2 | {
3 | using BaristaLabs.BaristaCore.AspNetCore.Middleware;
4 | using BaristaLabs.BaristaCore.Extensions;
5 | using BaristaLabs.BaristaCore.ModuleLoaders;
6 | using BaristaLabs.BaristaCore.TypeScript;
7 | using Microsoft.AspNetCore.Http;
8 | using System;
9 | using System.IO;
10 | using System.Linq;
11 | using System.Net;
12 | using System.Net.Http;
13 | using System.Text;
14 | using System.Threading.Tasks;
15 |
16 | public class BaristaPipeline : IBaristaPipeline
17 | {
18 | public async Task TakeOrder(string path, HttpRequest req)
19 | {
20 | return await TakeOrderMiddleware.Invoke(path, req);
21 | }
22 |
23 | public IBaristaModuleLoader Tamp(BrewOrder brewOrder, HttpRequest req)
24 | {
25 | return TampMiddleware.Invoke(brewOrder, req);
26 | }
27 |
28 | public HttpResponseMessage Brew(BrewOrder brewOrder, IBaristaRuntimeFactory baristaRuntimeFactory, IBaristaModuleLoader moduleLoader)
29 | {
30 | if (brewOrder == null)
31 | throw new ArgumentNullException(nameof(brewOrder));
32 |
33 | if (baristaRuntimeFactory == null)
34 | throw new ArgumentNullException(nameof(baristaRuntimeFactory));
35 |
36 | //Brew:
37 | HttpResponseMessage responseMessage = null;
38 | BrewMiddleware.Invoke(brewOrder, baristaRuntimeFactory, moduleLoader, (ctx, brewResult) =>
39 | {
40 | responseMessage = Serve(ctx, brewResult);
41 | return Task.CompletedTask;
42 | }).GetAwaiter().GetResult();
43 |
44 | return responseMessage;
45 | }
46 |
47 | public HttpResponseMessage Serve(BaristaContext ctx, JsValue result)
48 | {
49 | return ServeMiddleware.Invoke(ctx, result);
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/test/BaristaLabs.BaristaCore.Extensions.Tests/BaristaLabs.BaristaCore.Extensions.Tests.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp2.2
5 |
6 | false
7 |
8 |
9 |
10 | AnyCPU
11 | latest
12 |
13 |
14 |
15 | AnyCPU
16 | latest
17 |
18 |
19 |
20 |
21 |
22 | all
23 | runtime; build; native; contentfiles; analyzers
24 |
25 |
26 |
27 |
28 |
29 | all
30 | runtime; build; native; contentfiles; analyzers
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 | PreserveNewest
43 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/nuget/BaristaLabs.BaristaCore.Extensions.nuspec:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | BaristaLabs.BaristaCore.Extensions
5 | $version$
6 | Sean McLellan
7 | BaristaLabs, LLC
8 | MIT
9 | https://github.com/BaristaLabs/BaristaCore
10 | https://github.com/BaristaLabs/BaristaCore/raw/master/Logo.png
11 | false
12 | false
13 | Provides commonly used modules, module loaders, transpilers, and more to BaristaCore
14 | Provides commonly used modules, module loaders, transpilers, and more to BaristaCore
15 |
16 | For more information, visit the wiki at https://github.com/BaristaLabs/BaristaCore/wiki/baristacore-extensions
17 |
18 | https://github.com/BaristaLabs/BaristaCore/blob/master/README.md#roadmap
19 | Copyright (c) 2017 BaristaLabs, LLC
20 | en-US
21 | Barista,BaristaCore,Chakra,ChakraCore,javascript,js,ecmascript,compiler,platform,oss,opensource,native
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/BuiltIns/JsValueType.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | ///
4 | /// The JavaScript type of a JsValueRef.
5 | ///
6 | public enum JsValueType
7 | {
8 | ///
9 | /// The value is the undefined value.
10 | ///
11 | Undefined = 0,
12 | ///
13 | /// The value is the null value.
14 | ///
15 | Null = 1,
16 | ///
17 | /// The value is a JavaScript number value.
18 | ///
19 | Number = 2,
20 | ///
21 | /// The value is a JavaScript string value.
22 | ///
23 | String = 3,
24 | ///
25 | /// The value is a JavaScript Boolean value.
26 | ///
27 | Boolean = 4,
28 | ///
29 | /// The value is a JavaScript object value.
30 | ///
31 | Object = 5,
32 | ///
33 | /// The value is a JavaScript function object value.
34 | ///
35 | Function = 6,
36 | ///
37 | /// The value is a JavaScript error object value.
38 | ///
39 | Error = 7,
40 | ///
41 | /// The value is a JavaScript array object value.
42 | ///
43 | Array = 8,
44 | ///
45 | /// The value is a JavaScript symbol value.
46 | ///
47 | Symbol = 9,
48 | ///
49 | /// The value is a JavaScript ArrayBuffer object value.
50 | ///
51 | ArrayBuffer = 10,
52 | ///
53 | /// The value is a JavaScript typed array object value.
54 | ///
55 | TypedArray = 11,
56 | ///
57 | /// The value is a JavaScript DataView object value.
58 | ///
59 | DataView = 12,
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Extensions/TypeExtensions.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Extensions
2 | {
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Numerics;
6 |
7 | public static class TypeExtensions
8 | {
9 | private static readonly HashSet m_numTypes = new HashSet
10 | {
11 | typeof(int), typeof(double), typeof(decimal),
12 | typeof(long), typeof(short), typeof(sbyte),
13 | typeof(byte), typeof(ulong), typeof(ushort),
14 | typeof(uint), typeof(float), typeof(BigInteger)
15 | };
16 |
17 | public static bool IsSameOrSubclass(this Type potentialBase, Type potentialDescendant)
18 | {
19 | return potentialDescendant.IsSubclassOf(potentialBase)
20 | || potentialDescendant == potentialBase;
21 | }
22 |
23 | public static object GetDefaultValue(this Type t)
24 | {
25 | if (t == null)
26 | return null;
27 |
28 | if (t.IsValueType)
29 | return Activator.CreateInstance(t);
30 |
31 | return null;
32 | }
33 |
34 | public static bool IsNumeric(this Type t)
35 | {
36 | if (t == null)
37 | return false;
38 |
39 | return m_numTypes.Contains(t);
40 | }
41 |
42 | public static bool IsSubclassOfRawGeneric(this Type genericType, Type typeToCheck)
43 | {
44 | if (typeToCheck == typeof(object))
45 | {
46 | return false;
47 | }
48 | else if (typeToCheck == null)
49 | {
50 | return false;
51 | }
52 | else if (typeToCheck.IsGenericType && typeToCheck.GetGenericTypeDefinition() == genericType)
53 | {
54 | return true;
55 | }
56 | else
57 | {
58 | return IsSubclassOfRawGeneric(genericType, typeToCheck.BaseType);
59 | }
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/BuiltIns/JsExternalObject.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using BaristaLabs.BaristaCore.JavaScript;
4 | using System;
5 | using System.Runtime.InteropServices;
6 |
7 | public class JsExternalObject : JsObject
8 | {
9 | private readonly GCHandle m_objHandle;
10 |
11 | public JsExternalObject(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle valueHandle, GCHandle objHandle)
12 | : base(engine, context, valueHandle)
13 | {
14 | m_objHandle = objHandle;
15 | }
16 |
17 | public object Target
18 | {
19 | get { return m_objHandle.Target; }
20 | }
21 |
22 | ///
23 | /// Returns a value that indicates if the current object has external data associated with it.
24 | ///
25 | ///
26 | public bool HasExternalData()
27 | {
28 | return Engine.JsHasExternalData(Handle);
29 | }
30 |
31 | ///
32 | /// Retrieves the external data associated with the current object.
33 | ///
34 | ///
35 | ///
36 | public T GetExternalData()
37 | where T : class
38 | {
39 | var ptrData = Engine.JsGetExternalData(Handle);
40 | throw new NotImplementedException();
41 | }
42 |
43 | ///
44 | /// Sets the external data associated with the current object.
45 | ///
46 | ///
47 | ///
48 | public void SetExternalData(T externalData)
49 | where T : class
50 | {
51 | throw new NotImplementedException();
52 | }
53 |
54 | protected override void Dispose(bool disposing)
55 | {
56 | if (m_objHandle.IsAllocated)
57 | m_objHandle.Free();
58 |
59 | base.Dispose(disposing);
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.AspNetCore.Common/Middleware/4.ServeMiddleware.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.AspNetCore.Middleware
2 | {
3 | using Microsoft.AspNetCore.Http;
4 | using System;
5 | using System.Net.Http;
6 | using System.Threading.Tasks;
7 |
8 | public class ServeMiddleware
9 | {
10 | private readonly RequestDelegate m_next;
11 |
12 | public ServeMiddleware(RequestDelegate next)
13 | {
14 | m_next = next;
15 | }
16 |
17 | public async Task Invoke(HttpContext context)
18 | {
19 | var brewContext = context.Items[BrewKeys.BrewContext] as BaristaContext;
20 | if (brewContext == null)
21 | throw new InvalidOperationException("BrewContext was not defined within the http context.");
22 |
23 | var brewResult = context.Items[BrewKeys.BrewResult] as JsValue;
24 | if (brewResult is JsObject jsObject &&
25 | jsObject.TryGetBean(out JsExternalObject exObj) &&
26 | exObj.Target is BrewResponse brewResponseObj
27 | )
28 | {
29 | BrewResponse.PopulateHttpResponse(context.Response, brewContext, brewResponseObj);
30 | return;
31 | }
32 | else if (brewResult != null)
33 | {
34 | ResponseValueConverter.PopulateResponseForValue(context.Response, brewContext, brewResult);
35 | return;
36 | }
37 |
38 | await m_next(context);
39 | }
40 |
41 | public static HttpResponseMessage Invoke(BaristaContext brewContext, JsValue brewResult)
42 | {
43 | if (brewResult is JsObject jsObject &&
44 | jsObject.TryGetBean(out JsExternalObject exObj) &&
45 | exObj.Target is BrewResponse brewResponseObj
46 | )
47 | {
48 | return BrewResponse.CreateResponseMessage(brewContext, brewResponseObj);
49 | }
50 |
51 | return ResponseValueConverter.CreateResponseMessageForValue(brewContext, brewResult);
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/BuiltIns/JsArray.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using BaristaLabs.BaristaCore.JavaScript;
4 | using System.Collections;
5 | using System.Collections.Generic;
6 |
7 | public class JsArray : JsObject, IEnumerable
8 | {
9 | public JsArray(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle valueHandle)
10 | : base(engine, context, valueHandle)
11 | {
12 | }
13 |
14 | public int Length
15 | {
16 | get
17 | {
18 | var result = GetProperty("length");
19 | return result.ToInt32();
20 | }
21 | }
22 |
23 | public override JsValueType Type
24 | {
25 | get { return JsValueType.Array; }
26 | }
27 |
28 | public IEnumerator GetEnumerator()
29 | {
30 | var len = Length;
31 | for (int i = 0; i < len; i++)
32 | {
33 | yield return this[i];
34 | }
35 | }
36 |
37 | public JsValue Pop()
38 | {
39 | var fn = GetProperty("pop");
40 | return fn.Call(this);
41 | }
42 |
43 | public void Push(JsValue value)
44 | {
45 | var fn = GetProperty("push");
46 | fn.Call(this, value);
47 | }
48 |
49 | public int IndexOf(JsValue valueToFind, int? startIndex = null)
50 | {
51 | var args = new List
52 | {
53 | valueToFind
54 | };
55 |
56 | if (startIndex.HasValue == true)
57 | {
58 | args.Add(ValueFactory.CreateNumber(startIndex.Value));
59 | }
60 |
61 | var fn = GetProperty("indexOf");
62 | var result = fn.Call(this, args.ToArray());
63 | return result.ToInt32();
64 | }
65 |
66 | IEnumerator IEnumerable.GetEnumerator()
67 | {
68 | return GetEnumerator();
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/BuiltIns/JsIterator.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using BaristaLabs.BaristaCore.JavaScript;
4 | using System.Collections;
5 | using System;
6 | using System.Collections.Generic;
7 |
8 | ///
9 | /// Represents a object that implements the JavaScript iterator protocol, encapsulating an IEnumerator
10 | ///
11 | ///
12 | ///
13 | ///
14 | public sealed class JsIterator : JsObject
15 | {
16 | private readonly IEnumerator m_enumerator;
17 |
18 | public JsIterator(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle valueHandle, IEnumerator enumerator)
19 | : base(engine, context, valueHandle)
20 | {
21 | m_enumerator = enumerator ?? throw new ArgumentNullException(nameof(enumerator));
22 |
23 | var fnNext = context.CreateFunction(new Func((thisObj) =>
24 | {
25 | return Next();
26 | }));
27 |
28 | SetProperty("next", fnNext);
29 | }
30 |
31 | ///
32 | /// Gets the underlying enumerator
33 | ///
34 | [BaristaIgnore]
35 | public IEnumerator Enumerator
36 | {
37 | get { return m_enumerator; }
38 | }
39 |
40 | public JsObject Next()
41 | {
42 | var isDone = !m_enumerator.MoveNext();
43 | JsValue value = Context.Undefined;
44 |
45 | if (!isDone)
46 | {
47 | if (Context.Converter.TryFromObject(Context, m_enumerator.Current, out JsValue currentValue))
48 | {
49 | value = currentValue;
50 | }
51 | }
52 |
53 | var resultObj = Context.CreateObject();
54 | resultObj.SetProperty("done", isDone ? Context.True : Context.False);
55 | resultObj.SetProperty("value", value);
56 |
57 | return resultObj;
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/nuget/BaristaCore.AspNetCore.nuspec:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | BaristaCore.AspNetCore
5 | $version$
6 | Sean McLellan
7 | BaristaLabs, LLC
8 | MIT
9 | https://github.com/BaristaLabs/BaristaCore
10 | https://github.com/BaristaLabs/BaristaCore/raw/master/Logo.png
11 | false
12 | false
13 | Provides middleware and other behavior for hosting BaristaCore within a ASP.Net Core Web Application
14 | Allows BaristaCore to be used in conjunction with ASP.Net core to provide Azure Functions or AWS Lambda like functionality within your own web application.
15 |
16 | For more information, visit the wiki at https://github.com/BaristaLabs/BaristaCore/wiki/Using-BaristaCore-as-AspDotNet-Middleware
17 |
18 | https://github.com/BaristaLabs/BaristaCore/blob/master/README.md#roadmap
19 | Copyright (c) 2017 BaristaLabs, LLC
20 | en-US
21 | Barista,BaristaCore,Chakra,ChakraCore,javascript,js,ecmascript,compiler,platform,oss,opensource,native
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Utils/BaristaModuleTypeLoader.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using System;
4 | using System.Collections.Generic;
5 | using System.IO;
6 | using System.Linq;
7 | using System.Reflection;
8 |
9 | public static class BaristaModuleTypeLoader
10 | {
11 | ///
12 | /// For the given assembly path, returns any types that implement IBaristaModule.
13 | ///
14 | ///
15 | public static IEnumerable LoadBaristaModulesFromAssembly(string path)
16 | {
17 | if (!File.Exists(path))
18 | throw new ArgumentException($"A file does not exist at the specified path {path}");
19 |
20 | try
21 | {
22 | var assembly = Assembly.LoadFile(path);
23 | var types = assembly.GetExportedTypes();
24 | return LoadBaristaModulesFromAssembly(assembly);
25 | }
26 | catch (Exception)
27 | {
28 | return Enumerable.Empty();
29 | }
30 | }
31 |
32 | ///
33 | /// For the given assembly, returns any types that implement IBaristaModule
34 | ///
35 | ///
36 | ///
37 | public static IEnumerable LoadBaristaModulesFromAssembly(Assembly assembly)
38 | {
39 | foreach (var type in assembly.GetExportedTypes())
40 | {
41 | var typeList = type.FindInterfaces(BaristaModuleInterfaceFilter, typeof(IBaristaModule));
42 | if (!type.IsAbstract && !type.IsInterface && !type.IsGenericType && !type.IsNotPublic && typeList.Length > 0)
43 | {
44 | yield return type;
45 | }
46 | }
47 | }
48 |
49 | private static bool BaristaModuleInterfaceFilter(Type typeObj, Object criteriaObj)
50 | {
51 | if (typeObj.ToString() == criteriaObj.ToString())
52 | return true;
53 |
54 | return false;
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/BuiltIns/JsSymbolConstructor.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using BaristaLabs.BaristaCore.JavaScript;
4 | using System;
5 |
6 | ///
7 | /// Contains the methods of the symbol constructor
8 | ///
9 | ///
10 | ///
11 | ///
12 | public class JsSymbolConstructor : JsObject
13 | {
14 | public JsSymbolConstructor(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle valueHandle)
15 | : base(engine, context, valueHandle)
16 | {
17 | }
18 |
19 | public JsSymbol Iterator
20 | {
21 | get
22 | {
23 | return GetProperty("iterator");
24 | }
25 | }
26 |
27 | ///
28 | /// Searches for existing symbols in a runtime-wide symbol registry with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with this key.
29 | ///
30 | /// The key for the symbol (and also used for the description of the symbol).
31 | /// An existing symbol with the given key if found; otherwise, a new symbol is created and returned.
32 | public JsSymbol For(string key)
33 | {
34 | if (string.IsNullOrWhiteSpace(key))
35 | throw new ArgumentNullException(nameof(key));
36 |
37 | var fnFor = GetProperty("for");
38 | return fnFor.Call(this, Context.CreateString(key));
39 | }
40 |
41 | ///
42 | ///
43 | ///
44 | ///
45 | ///
46 | public JsValue KeyFor(JsSymbol sym)
47 | {
48 | if (sym == null)
49 | throw new ArgumentNullException(nameof(sym));
50 |
51 | var fnKeyFor = GetProperty("keyFor");
52 | return fnKeyFor.Call(this, sym);
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/nuget/BaristaCore.nuspec:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | BaristaCore
5 | $version$
6 | Sean McLellan
7 | BaristaLabs, LLC
8 | MIT
9 | https://github.com/BaristaLabs/BaristaCore
10 | https://github.com/BaristaLabs/BaristaCore/raw/master/Logo.png
11 | false
12 | false
13 | Provides a sandboxed JavaScript runtime natively to a .Net Standard 2.0 application on Windows, Linux and macOS.
14 | Provides a sandboxed JavaScript runtime natively to a .Net Standard 2.0 application on Windows, Linux and macOS.
15 |
16 | Applications can expose custom modules and types written in .Net code to the runtime, making it useful for providing a rules engine or other scripted capabilities that interact with existing managed libraries.
17 |
18 | The underlying JavaScript runtime is Chakra, the JavaScript engine that powers Microsoft Edge, allowing for a fully managed, latest standards compliant, performant and well sandboxed JavaScript-based scripting environment.
19 |
20 | For more information, visit the wiki at https://github.com/BaristaLabs/BaristaCore/wiki/Embedding-BaristaCore-into-your-own-application
21 |
22 | https://github.com/BaristaLabs/BaristaCore/blob/master/README.md#roadmap
23 | Copyright (c) 2017 BaristaLabs, LLC
24 | en-US
25 | Barista,BaristaCore,sandbox,Chakra,ChakraCore,javascript,js,ecmascript,compiler,platform,oss,opensource,native
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Portafilter/BaristaFunction.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.Portafilter
2 | {
3 | using BaristaLabs.BaristaCore.AspNetCore;
4 | using BaristaLabs.BaristaCore.Extensions;
5 | using Microsoft.AspNetCore.Http;
6 | using Microsoft.Azure.WebJobs;
7 | using Microsoft.Azure.WebJobs.Extensions.Http;
8 | using Microsoft.Azure.WebJobs.Host;
9 | using Microsoft.Extensions.DependencyInjection;
10 | using Microsoft.Extensions.Logging;
11 | using System;
12 | using System.Net.Http;
13 | using System.Threading.Tasks;
14 |
15 | public static class BaristaFunction
16 | {
17 | private static readonly IBaristaPipeline s_pipeline;
18 | private static readonly IBaristaRuntimeFactory s_baristaRuntimeFactory;
19 |
20 | static BaristaFunction()
21 | {
22 | var serviceCollection = new ServiceCollection();
23 | serviceCollection.AddBaristaCore();
24 |
25 | var provider = serviceCollection.BuildServiceProvider();
26 |
27 | s_baristaRuntimeFactory = provider.GetRequiredService();
28 | s_pipeline = new BaristaPipeline();
29 | }
30 |
31 | [FunctionName("BaristaFunction")]
32 | public static async Task Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", "patch", "put", "delete", "options", "head", "brew", Route = "{*path}")]HttpRequest req, string path, ILogger log)
33 | {
34 | log.LogTrace("Barista Function processed a request.");
35 |
36 | var brewOrder = await s_pipeline.TakeOrder(path, req);
37 |
38 | if (brewOrder.IsCodeSet == false)
39 | {
40 | //Return an exception.
41 | }
42 |
43 | var moduleLoader = s_pipeline.Tamp(brewOrder, req);
44 |
45 | try
46 | {
47 | return s_pipeline.Brew(brewOrder, s_baristaRuntimeFactory, moduleLoader);
48 | }
49 | finally
50 | {
51 | if (moduleLoader is IDisposable disposableLoader)
52 | {
53 | disposableLoader.Dispose();
54 | }
55 | }
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/JavaScript/Enums/JavaScriptRuntimeAttributes.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore.JavaScript
2 | {
3 | using System;
4 |
5 | ///
6 | /// Attributes of a runtime.
7 | ///
8 | [Flags]
9 | public enum JavaScriptRuntimeAttributes
10 | {
11 | ///
12 | /// No special attributes.
13 | ///
14 | None = 0x00000000,
15 | ///
16 | /// The runtime will not do any work (such as garbage collection) on background threads.
17 | ///
18 | DisableBackgroundWork = 0x00000001,
19 | ///
20 | /// The runtime should support reliable script interruption. This increases the number of
21 | /// places where the runtime will check for a script interrupt request at the cost of a
22 | /// small amount of runtime performance.
23 | ///
24 | AllowScriptInterrupt = 0x00000002,
25 | ///
26 | /// Host will call JsIdle, so enable idle processing. Otherwise, the runtime will
27 | /// manage memory slightly more aggressively.
28 | ///
29 | EnableIdleProcessing = 0x00000004,
30 | ///
31 | /// Runtime will not generate native code.
32 | ///
33 | DisableNativeCodeGeneration = 0x00000008,
34 | ///
35 | /// Using eval or function constructor will throw an exception.
36 | ///
37 | DisableEval = 0x00000010,
38 | ///
39 | /// Runtime will enable all experimental features.
40 | ///
41 | EnableExperimentalFeatures = 0x00000020,
42 | ///
43 | /// Calling JsSetException will also dispatch the exception to the script debugger
44 | /// (if any) giving the debugger a chance to break on the exception.
45 | ///
46 | DispatchSetExceptionsToDebugger = 0x00000040,
47 | ///
48 | /// Disable Failfast fatal error on OOM
49 | ///
50 | JsRuntimeAttributeDisableFatalOnOOM = 0x00000080,
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/nuget/BaristaLabs.BaristaCore.Common.nuspec:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | BaristaLabs.BaristaCore.Common
5 | $version$
6 | Sean McLellan
7 | BaristaLabs, LLC
8 | MIT
9 | https://github.com/BaristaLabs/BaristaCore
10 | https://github.com/BaristaLabs/BaristaCore/raw/master/Logo.png
11 | false
12 | false
13 | Common base library that provides the base types and high-level wrapper around Chakra
14 | Common base library that provides the base types and high-level wrapper around Chakra, the JavaScript engine that powers Microsoft Edge.
15 |
16 | For more information, visit the wiki at https://github.com/BaristaLabs/BaristaCore/wiki/Embedding-BaristaCore-into-your-own-application
17 |
18 | https://github.com/BaristaLabs/BaristaCore/blob/master/README.md#roadmap
19 | Copyright (c) 2017 BaristaLabs, LLC
20 | en-US
21 | Barista,BaristaCore,Chakra,ChakraCore,javascript,js,ecmascript,compiler,platform,oss,opensource,native
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/src/BaristaLabs.BaristaCore.Common/Undefined.cs:
--------------------------------------------------------------------------------
1 | namespace BaristaLabs.BaristaCore
2 | {
3 | using System;
4 | using System.Runtime.Serialization;
5 |
6 | ///
7 | /// Represents the JavaScript "undefined" type and provides the one and only instance of that type.
8 | ///
9 | [Serializable]
10 | public sealed class Undefined : System.Runtime.Serialization.ISerializable
11 | {
12 | ///
13 | /// Creates a new Undefined instance.
14 | ///
15 | private Undefined()
16 | {
17 | }
18 |
19 | ///
20 | /// Creates a new Undefined instance -- used for serialization.
21 | ///
22 | ///
23 | ///
24 | private Undefined(SerializationInfo info, StreamingContext context)
25 | {
26 | }
27 |
28 | ///
29 | /// Gets the one and only "undefined" instance.
30 | ///
31 | public static readonly Undefined Value = new Undefined();
32 |
33 | [Serializable]
34 | private class SerializationHelper : IObjectReference
35 | {
36 | public object GetRealObject(StreamingContext context)
37 | {
38 | return Value;
39 | }
40 | }
41 |
42 | ///
43 | /// Sets the SerializationInfo with information about the exception.
44 | ///
45 | /// The SerializationInfo that holds the serialized object data about
46 | /// the exception being thrown.
47 | /// The StreamingContext that contains contextual information about
48 | /// the source or destination.
49 | public void GetObjectData(SerializationInfo info, StreamingContext context)
50 | {
51 | // Save the object state.
52 | info.SetType(typeof(SerializationHelper));
53 | }
54 |
55 | ///
56 | /// Returns a string representing the current object.
57 | ///
58 | /// A string representing the current object.
59 | public override string ToString()
60 | {
61 | return "undefined";
62 | }
63 | }
64 | }
65 |
--------------------------------------------------------------------------------