Esempio n. 1
0
 public ReactHtmlOutputFormatter(INodeJSService nodeJSService)
 {
     _nodeJSService = nodeJSService ?? throw new ArgumentNullException(nameof(nodeJSService));
     SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/html"));
     SupportedEncodings.Add(Encoding.UTF8);
     SupportedEncodings.Add(Encoding.Unicode);
 }
        /// <summary>
        /// Adds a instance of <see cref="NodeJsEngineFactory"/> to
        /// the specified <see cref="JsEngineFactoryCollection" />
        /// </summary>
        /// <param name="source">Instance of <see cref="JsEngineFactoryCollection" /></param>
        /// <param name="service">Node JS service</param>
        /// <param name="configure">The delegate to configure the provided <see cref="NodeSettings"/></param>
        /// <returns>Instance of <see cref="JsEngineFactoryCollection" /></returns>
        public static JsEngineFactoryCollection AddNode(this JsEngineFactoryCollection source,
                                                        INodeJSService service, Action <NodeSettings> configure)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (service == null)
            {
                throw new ArgumentNullException(nameof(service));
            }

            if (configure == null)
            {
                throw new ArgumentNullException(nameof(configure));
            }

            var settings = new NodeSettings();

            configure(settings);

            source.Add(new NodeJsEngineFactory(service, settings));

            return(source);
        }
        /// <summary>
        /// Constructs an instance of adapter for the Node JS engine
        /// </summary>
        /// <param name="service">Node JS service</param>
        /// <param name="settings">Settings of the Node JS engine</param>
        public NodeJsEngine(INodeJSService service, NodeSettings settings)
        {
            if (service == null)
            {
                throw new ArgumentNullException(nameof(service));
            }

            _jsService = service;

            try
            {
                Task <string> versionTask = _jsService.InvokeFromStringAsync <string>(
                    @"module.exports = (callback) => {
	var version = process.versions.node;
	callback(null , version);
};"
                    );
                _engineVersion = versionTask.ConfigureAwait(false).GetAwaiter().GetResult();
            }
            catch (Exception e)
            {
                throw JsErrorHelpers.WrapEngineLoadException(e, EngineName, _engineVersion, true);
            }

            NodeSettings nodeSettings = settings ?? new NodeSettings();

            _executionTimeout = (int)nodeSettings.TimeoutInterval.TotalMilliseconds;
            _engineId         = JsEngineIdGenerator.GetNextId();

            InvokeEngineHelper("addContext", new object[] { _engineId, nodeSettings.UseBuiltinLibrary });
        }
        public NodeInvocationService(
            INodeJSService nodeJsService,
            ReactConfiguration configuration,
            IEmbeddedResourcesService embeddedResourcesService,
            IOptions <NodeJSProcessOptions> nodeJsProcessOptions,
            IServiceScopeFactory serviceScopeFactory)
        {
            _nodeJsService            = nodeJsService;
            _embeddedResourcesService = embeddedResourcesService;

            using (IServiceScope scope = serviceScopeFactory.CreateScope())
            {
                IServiceProvider serviceProvider = scope.ServiceProvider;

                IHostingEnvironment hostingEnvironment = serviceProvider.GetService <IHostingEnvironment>();

                var requireFiles = configuration.ScriptFilesWithoutTransform
                                   .Select(relativePath =>
                {
                    if (relativePath.StartsWith(nodeJsProcessOptions.Value.ProjectPath))
                    {
                        return(relativePath);
                    }

                    relativePath = relativePath.TrimStart('~').TrimStart('/');

                    return(Path.GetFullPath(Path.Combine(hostingEnvironment?.WebRootPath ?? nodeJsProcessOptions.Value.ProjectPath, relativePath)));
                });

                //TODO: do this in configure
                nodeJsProcessOptions.Value.EnvironmentVariables.Add("NODEREACT_REQUIREFILES", string.Join(',', requireFiles));
            }
        }
Esempio n. 5
0
        public static Task <RenderToStringResult> RenderToString(
            string applicationBasePath,
            INodeJSService nodeServices,
            CancellationToken applicationStoppingToken,
            JavaScriptModuleExport bootModule,
            HttpContext httpContext,
            object customDataParameter,
            int timeoutMilliseconds)
        {
            // We want to pass the original, unencoded incoming URL data through to Node, so that
            // server-side code has the same view of the URL as client-side code (on the client,
            // location.pathname returns an unencoded string).
            // The following logic handles special characters in URL paths in the same way that
            // Node and client-side JS does. For example, the path "/a=b%20c" gets passed through
            // unchanged (whereas other .NET APIs do change it - Path.Value will return it as
            // "/a=b c" and Path.ToString() will return it as "/a%3db%20c")
            var requestFeature        = httpContext.Features.Get <IHttpRequestFeature>();
            var unencodedPathAndQuery = requestFeature.RawTarget;

            var request = httpContext.Request;
            var unencodedAbsoluteUrl = $"{request.Scheme}://{request.Host}{unencodedPathAndQuery}";

            return(RenderToString(
                       applicationBasePath,
                       nodeServices,
                       applicationStoppingToken,
                       bootModule,
                       unencodedAbsoluteUrl,
                       unencodedPathAndQuery,
                       customDataParameter,
                       timeoutMilliseconds,
                       request.PathBase.ToString()));
        }
Esempio n. 6
0
 public JeringServerRenderer(INodeJSService jsService, IOptions <SpaOptions> options, ITelemetryProvider telemetryProvider, IAssetsResolver assesResolver)
 {
     _jsService         = jsService;
     _options           = options;
     _telemetryProvider = telemetryProvider;
     _assesResolver     = assesResolver;
 }
 public override void Dispose()
 {
     if (_disposedFlag.Set())
     {
         InvokeEngineHelper("removeСontext", new[] { _engineId });
         _jsService = null;
     }
 }
Esempio n. 8
0
 public ConversionTool(
     INodeJSService nodeJSService,
     string input, string output)
 {
     NodeJSService = nodeJSService;
     Input         = input;
     Output        = output;
 }
Esempio n. 9
0
 public RenderService(INodeJSService nodeJSService, IWebHostEnvironment webHostEnvironment)
 {
     if (webHostEnvironment is null)
     {
         throw new System.ArgumentNullException(nameof(webHostEnvironment));
     }
     _nodeJSService = nodeJSService ?? throw new System.ArgumentNullException(nameof(nodeJSService));
     _serverJsPath  = webHostEnvironment.ContentRootFileProvider.GetFileInfo(ServerJsRelPath).PhysicalPath;
 }
        public void INodeJSService_InvokeFromFile_Setup()
        {
            var services = new ServiceCollection();

            services.AddNodeJS();
            services.Configure <NodeJSProcessOptions>(options => options.ProjectPath = Path.Combine(Directory.GetCurrentDirectory(), "../../../.."));
            _serviceProvider = services.BuildServiceProvider();
            _nodeJSService   = _serviceProvider.GetRequiredService <INodeJSService>(); // Default INodeJSService is HttpNodeJSService
            _counter         = 0;
        }
Esempio n. 11
0
 public DefaultSpaPrerenderer(
     INodeJSService nodeServices,
     IApplicationLifetime applicationLifetime,
     IHostingEnvironment hostingEnvironment,
     IHttpContextAccessor httpContextAccessor)
 {
     _applicationBasePath      = hostingEnvironment.ContentRootPath;
     _applicationStoppingToken = applicationLifetime.ApplicationStopping;
     _httpContextAccessor      = httpContextAccessor;
     _nodeServices             = nodeServices;
 }
Esempio n. 12
0
        public void INodeJSService_Latency_InvokeFromCache_Setup()
        {
            var services = new ServiceCollection();

            services.AddNodeJS();
            _serviceProvider = services.BuildServiceProvider();
            _nodeJSService   = _serviceProvider.GetRequiredService <INodeJSService>();
            _counter         = 0;

            // Warmup/cache.
            _nodeJSService.InvokeFromStringAsync <DummyResult>(DummyModuleFactory, DUMMY_MODULE_IDENTIFIER, args: new object[] { _counter++ }).GetAwaiter().GetResult();
        }
Esempio n. 13
0
        public void INodeJSService_Concurrency_None_Setup()
        {
            var services = new ServiceCollection();

            services.AddNodeJS();
            services.Configure <NodeJSProcessOptions>(options => options.ProjectPath = _projectPath);
            _serviceProvider = services.BuildServiceProvider();
            _nodeJSService   = _serviceProvider.GetRequiredService <INodeJSService>();

            // Warmup. First run starts a Node.js processes.
            _nodeJSService.InvokeFromStringAsync(DUMMY_WARMUP_MODULE).GetAwaiter().GetResult();
        }
Esempio n. 14
0
        static void Main()
        {
            IServiceCollection services = new ServiceCollection();

            services.AddNodeJS();
            ServiceProvider serviceProvider = services.BuildServiceProvider();
            INodeJSService  nodeJSService   = serviceProvider.GetRequiredService <INodeJSService>();

            int result = nodeJSService.InvokeFromStringAsync <int>("module.exports = (callback) => callback(null, 1)").GetAwaiter().GetResult();

            Console.WriteLine(result);
        }
Esempio n. 15
0
        public MjmlServices(INodeJSService nodeServices, MjmlServiceOptions options)
        {
            _nodeServices = nodeServices;
            _options      = options;

            _renderer = GetRenderer();

            if (options.WarmUpRender)
            {
                Warmup().Wait();
            }
        }
        public void INodeJSService_InvokeFromCache_Setup()
        {
            var services = new ServiceCollection();

            services.AddNodeJS();
            _serviceProvider = services.BuildServiceProvider();
            _nodeJSService   = _serviceProvider.GetRequiredService <INodeJSService>(); // Default INodeJSService is HttpNodeJSService
            _counter         = 0;

            // Cache module
            DummyResult _ = _nodeJSService.InvokeFromStringAsync <DummyResult>("module.exports = (callback, resultString) => callback(null, { result: resultString });", DUMMY_MODULE_IDENTIFIER, args: new object[] { $"success {_counter++}" }).Result;
        }
Esempio n. 17
0
        public void AddNodeJS_AddsServices()
        {
            // Arrange
            var services = new ServiceCollection();

            // Act
            services.AddNodeJS();

            // Assert
            IServiceProvider serviceProvider = services.BuildServiceProvider();
            INodeJSService   _ = serviceProvider.GetRequiredService <INodeJSService>(); // As long as this doesn't throw, the dependency graph is valid
        }
Esempio n. 18
0
 public GetEntityViewmodelHandler(
     DataContext ctx,
     INodeJSService node,
     ILogger <GetEntityViewmodelHandler> logger,
     IMediator mediator
     )
 {
     this.ctx      = ctx;
     this.node     = node;
     this.logger   = logger;
     this.mediator = mediator;
 }
Esempio n. 19
0
        public async Task Invoke(HttpContext context, INodeJSService nodeService)
        {
            if (IsRequestingAsyncApiIndex(context.Request))
            {
                using (var client = _httpClientFactory.CreateClient())
                    using (var response = await client.GetAsync($"{context.Request.Scheme}://{context.Request.Host.Value}/asyncapi/asyncapi.json"))
                    {
                        var asyncapiDocument = await response.Content.ReadAsStringAsync();

                        await nodeService.InvokeFromFileAsync($"{AppDomain.CurrentDomain.BaseDirectory}/app.js", args : new [] { asyncapiDocument, "AsyncApi" });
                    }
            }
            await _next(context);
        }
Esempio n. 20
0
        public void INodeJSService_Latency_InvokeFromFile_GracefulShutdownEnabled_Setup()
        {
            var services = new ServiceCollection();

            services.AddNodeJS();
            services.Configure <NodeJSProcessOptions>(options => options.ProjectPath = _projectPath);
            services.Configure <OutOfProcessNodeJSServiceOptions>(options => options.EnableFileWatching = true);
            _serviceProvider = services.BuildServiceProvider();
            _nodeJSService   = _serviceProvider.GetRequiredService <INodeJSService>();
            _counter         = 0;

            // Warmup. First run starts a Node.js process.
            _nodeJSService.InvokeFromStringAsync(DUMMY_WARMUP_MODULE).GetAwaiter().GetResult();
        }
Esempio n. 21
0
        private static void RunTests()
        {
            using (NodeJSService = ServiceProvider.GetRequiredService <INodeJSService>())
            {
                var tasks = new List <Task>();

                for (var i = 0; i < TestIterations; i++)
                {
                    tasks.Add(DocxToPdfCb(i));
                    tasks.Add(DocxToPdfAsync(i));
                }

                Task.WaitAll(tasks.ToArray());
            }
        }
Esempio n. 22
0
        public NodeService()
        {
            var services = new ServiceCollection();

            services.AddNodeJS();

            //services.Configure<NodeJSProcessOptions>(options => options.ProjectPath = "C:\\Users\\kcjer\\my-lights\\light-rest\\src\\dist");
            services.Configure <NodeJSProcessOptions>(options => options.NodeAndV8Options      = "--inspect-brk");
            services.Configure <OutOfProcessNodeJSServiceOptions>(options => options.TimeoutMS = -1);

            ServiceProvider serviceProvider = services.BuildServiceProvider();
            INodeJSService  nodeJSService   = serviceProvider.GetRequiredService <INodeJSService>();

            this.node = nodeJSService;
        }
Esempio n. 23
0
        public void INodeJSService_Concurrency_MultiProcess_Setup()
        {
            var services = new ServiceCollection();

            services.AddNodeJS();
            services.Configure <NodeJSProcessOptions>(options => options.ProjectPath             = _projectPath);
            services.Configure <OutOfProcessNodeJSServiceOptions>(options => options.Concurrency = Concurrency.MultiProcess);
            _serviceProvider = services.BuildServiceProvider();
            _nodeJSService   = _serviceProvider.GetRequiredService <INodeJSService>();

            // Warmup. First few runs start Node.js processes, so they take longer. If we don't manually warm up, BenchmarkDotNet erroneously complains
            // about iteration time being too low
            for (int i = 0; i < Environment.ProcessorCount; i++)
            {
                _nodeJSService.InvokeFromStringAsync(DUMMY_WARMUP_MODULE).GetAwaiter().GetResult();
            }
        }
        /// <summary>
        /// Adds a instance of <see cref="NodeJsEngineFactory"/> to
        /// the specified <see cref="JsEngineFactoryCollection" />
        /// </summary>
        /// <param name="source">Instance of <see cref="JsEngineFactoryCollection" /></param>
        /// <param name="service">Node JS service</param>
        /// <returns>Instance of <see cref="JsEngineFactoryCollection" /></returns>
        public static JsEngineFactoryCollection AddNode(this JsEngineFactoryCollection source,
                                                        INodeJSService service)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (service == null)
            {
                throw new ArgumentNullException(nameof(service));
            }

            source.Add(new NodeJsEngineFactory(service));

            return(source);
        }
        public void INodeJSService_RealWorkload_Setup()
        {
            var services = new ServiceCollection();

            services.AddNodeJS();
            services.Configure <NodeJSProcessOptions>(options => options.ProjectPath             = _projectPath); // Module loads prismjs from node_modules
            services.Configure <OutOfProcessNodeJSServiceOptions>(options => options.Concurrency = Concurrency.MultiProcess);
            _serviceProvider = services.BuildServiceProvider();
            _nodeJSService   = _serviceProvider.GetRequiredService <INodeJSService>();
            _counter         = 0;

            // Warmup/cache. First few runs start Node.js processes, so they take longer. If we don't manually warm up, BenchmarkDotNet erroneously complains
            // about iteration time being too low
            for (int i = 0; i < Environment.ProcessorCount; i++)
            {
                _nodeJSService.InvokeFromStringAsync(DummyModuleFactory, DUMMY_CACHE_IDENTIFIER, args: new object[] { string.Format(DUMMY_CODE_FORMAT, _counter++) }).GetAwaiter().GetResult();
            }
        }
        /// <summary>
        /// Creates a new instance of <see cref="PrerenderTagHelper"/>.
        /// </summary>
        /// <param name="serviceProvider">The <see cref="IServiceProvider"/>.</param>
        public PrerenderTagHelper(IServiceProvider serviceProvider)
        {
            var hostEnv = (IWebHostEnvironment)serviceProvider.GetService(typeof(IWebHostEnvironment));

            _nodeServices        = NodeInteropFactory.GetInstance(serviceProvider) ?? _fallbackNodeServices;
            _applicationBasePath = hostEnv.ContentRootPath;

            var applicationLifetime = (IHostApplicationLifetime)serviceProvider.GetService(typeof(IHostApplicationLifetime));

            _applicationStoppingToken = applicationLifetime.ApplicationStopping;

            // Consider removing the following. Having it means you can get away with not putting app.AddNodeServices()
            // in your startup file, but then again it might be confusing that you don't need to.
            if (_nodeServices == null)
            {
                _nodeServices = _fallbackNodeServices = NodeInteropFactory.BuildNewInstance(serviceProvider);
            }
        }
Esempio n. 27
0
        /// <summary>
        /// Renders the tree using ELK.js.
        /// </summary>
        private async Task <string> RenderTree(INodeJSService js, TreeLayoutVM tree, DynamicConfig cfg)
        {
            var thoroughness = Interpolator.MapValue(
                cfg.TreeRenderThoroughness,
                new IntervalMap(1, 10, 1, 10),
                new IntervalMap(11, 50, 11, 600),
                new IntervalMap(51, 100, 301, 15000)
                );

            var json   = JsonConvert.SerializeObject(tree);
            var result = await js.InvokeFromFileAsync <string>("./External/tree/tree-layout.js", args : new object[] { json, thoroughness });

            if (string.IsNullOrEmpty(result))
            {
                throw new Exception("Failed to render tree: output is empty.");
            }

            return(result);
        }
        /// <summary>
        /// Creates a instance of the Node JS engine
        /// </summary>
        /// <returns>Instance of the Node JS engine</returns>
        public IJsEngine CreateEngine()
        {
            if (_services != null && _jsService == null)
            {
                lock (_creationSynchronizer)
                {
                    if (_jsService == null)
                    {
                        ServiceProvider serviceProvider = _services.BuildServiceProvider();
                        _jsService = serviceProvider.GetRequiredService <INodeJSService>();
                    }
                }
            }

            IJsEngine engine = _jsService != null ?
                               new NodeJsEngine(_jsService, _settings) : new NodeJsEngine(_settings);

            return(engine);
        }
Esempio n. 29
0
        static void Main()
        {
            string javascriptModule = @"
module.exports = (callback, x, y) => {  // Module must export a function that takes a callback as its first parameter
    var result = x + y; // Your javascript logic
    callback(null /* If an error occurred, provide an error object or message */, result); // Call the callback when you're done.
}";

            // Create INodeJSService instance
            var services = new ServiceCollection();

            services.AddNodeJS();
            ServiceProvider serviceProvider = services.BuildServiceProvider();
            INodeJSService  nodeJSService   = serviceProvider.GetRequiredService <INodeJSService>();

            // Invoke javascript
            int result = nodeJSService.InvokeFromStringAsync <int>(javascriptModule, args: new object[] { 3, 5 }).Result;

            Console.WriteLine(result);
        }
Esempio n. 30
0
        private static INodeJSService GetOrCreateNodeJSService()
        {
            if (_nodeJSService == null || _services != null)
            {
                lock (_createLock)
                {
                    if (_nodeJSService == null || _services != null)
                    {
                        // Dispose of service provider
                        _serviceProvider?.Dispose();

                        // Create new service provider
                        _services        = _services ?? new ServiceCollection().AddNodeJS();
                        _serviceProvider = _services.BuildServiceProvider();
                        _nodeJSService   = _serviceProvider.GetRequiredService <INodeJSService>();

                        _services = null;
                    }
                }
            }

            // NodeJSService already exists and no configuration pending
            return(_nodeJSService);
        }