internal static void HighlightElement(IJavaScriptEnginePool enginePool, AngleSharp.Dom.IElement element)
        {
            using (IJavaScriptEngine engine = enginePool.GetEngine())
            {
                // Make sure to use TextContent, otherwise you'll get escaped html which highlight.js won't parse
                engine.SetVariableValue("input", element.TextContent);

                // Check if they specified a language in their code block
                string language = element.ClassList.FirstOrDefault(i => i.StartsWith("language"));
                if (language != null)
                {
                    engine.SetVariableValue("language", language.Replace("language-", string.Empty));
                    engine.Execute("result = hljs.highlight(language, input)");
                }
                else
                {
                    language = "(auto)"; // set this to auto in case there is an exception below
                    engine.Execute("result = hljs.highlightAuto(input)");
                    string detectedLanguage = engine.Evaluate <string>("result.language");
                    if (!string.IsNullOrWhiteSpace(detectedLanguage))
                    {
                        element.ClassList.Add("language-" + detectedLanguage);
                    }
                }

                element.ClassList.Add("hljs");
                element.InnerHtml = engine.Evaluate <string>("result.value");
            }
        }
Example #2
0
        protected JsValue(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle valueHandle)
        {
            m_javaScriptEngine    = engine ?? throw new ArgumentNullException(nameof(engine));
            m_context             = context ?? throw new ArgumentNullException(nameof(context));
            m_javaScriptReference = valueHandle ?? throw new ArgumentNullException(nameof(valueHandle));

            //Let's just make sure that we're the correct type.
            var reportedType = engine.JsGetValueType(valueHandle);

            //if (reportedType != Type)
            //    throw new InvalidOperationException($"The underlying type ({reportedType}) does not match the type that is being created ({Type}). Ensure that correct value is being created.");

            //Set the event that will be called prior to the engine collecting the value.
            if ((this is JsNumber) == false)
            {
                //Set the event that will be called prior to the engine collecting the value.
                JavaScriptObjectBeforeCollectCallback beforeCollectCallback = (IntPtr handle, IntPtr callbackState) =>
                {
                    try
                    {
                        OnBeforeCollect(handle, callbackState);
                    }
                    catch
                    {
                        //Do Nothing.
                    }
                };

                m_beforeCollectCallbackDelegateHandle = GCHandle.Alloc(beforeCollectCallback);
                //An exception thrown here is usually due to trying to associate a callback to a JsNumber.
                Engine.JsSetObjectBeforeCollectCallback(valueHandle, IntPtr.Zero, beforeCollectCallback);
            }
        }
        public IJavaScriptEngine GetEngine(TimeSpan?timeout = null)
        {
            IJavaScriptEngine engine = _engineFunc();

            _initializer?.Invoke(engine);
            return(engine);
        }
 public BaristaModuleRecordFactory(IJavaScriptEngine engine, IServiceProvider serviceProvider)
 {
     m_engine                = engine ?? throw new ArgumentNullException(nameof(engine));
     m_serviceProvider       = serviceProvider;
     m_moduleReferencePool   = new BaristaObjectPool <BaristaModuleRecord, JavaScriptModuleRecord>();
     m_specifierModuleLookup = new Dictionary <JavaScriptValueSafeHandle, JavaScriptModuleRecord>();
 }
 public JavascriptCommandHandler(IServiceLocator serviceLocator, ApiScriptCommand command, Boolean wrap)
 {
     _serviceLocator = serviceLocator;
     _script         = _serviceLocator.GetService <IJavaScriptEngine>();
     _reader         = _serviceLocator.GetService <IApplicationHost>().ApplicationReader;
     _command        = command;
     _wrap           = wrap;
 }
 public JsManagedExternalArrayBuffer(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle valueHandle, IntPtr bufferHandle)
     : base(engine, context, valueHandle)
 {
     if (bufferHandle == default(IntPtr) || bufferHandle == null)
     {
         throw new ArgumentNullException(nameof(bufferHandle));
     }
     m_bufferHandle = bufferHandle;
 }
Example #7
0
        /// <summary>
        /// Creates a new instance of a Barista Context.
        /// </summary>
        /// <param name="engine"></param>
        /// <param name="contextHandle"></param>
        public BaristaContext(IJavaScriptEngine engine, IBaristaValueFactoryBuilder valueFactoryBuilder, IBaristaConversionStrategy conversionStrategy, IBaristaModuleRecordFactory moduleRecordFactory, IPromiseTaskQueue taskQueue, JavaScriptContextSafeHandle contextHandle)
            : base(engine, contextHandle)
        {
            if (valueFactoryBuilder == null)
            {
                throw new ArgumentNullException(nameof(valueFactoryBuilder));
            }

            m_taskFactory = new TaskFactory(
                CancellationToken.None,
                TaskCreationOptions.DenyChildAttach,
                TaskContinuationOptions.None,
                new CurrentThreadTaskScheduler());

            m_conversionStrategy = conversionStrategy ?? throw new ArgumentNullException(nameof(conversionStrategy));

            m_valueFactory = valueFactoryBuilder.CreateValueFactory(this);

            m_undefinedValue = new Lazy <JsUndefined>(() => m_valueFactory.Undefined);
            m_nullValue      = new Lazy <JsNull>(() => m_valueFactory.Null);
            m_trueValue      = new Lazy <JsBoolean>(() => m_valueFactory.True);
            m_falseValue     = new Lazy <JsBoolean>(() => m_valueFactory.False);
            m_globalValue    = new Lazy <JsObject>(() => m_valueFactory.GlobalObject);
            m_jsonValue      = new Lazy <JsJSON>(() =>
            {
                var global = m_globalValue.Value;
                return(global.GetProperty <JsJSON>("JSON"));
            });
            m_objectValue = new Lazy <JsObjectConstructor>(() =>
            {
                var global = m_globalValue.Value;
                return(global.GetProperty <JsObjectConstructor>("Object"));
            });
            m_promiseValue = new Lazy <JsPromiseConstructor>(() =>
            {
                var global = m_globalValue.Value;
                return(global.GetProperty <JsPromiseConstructor>("Promise"));
            });
            m_symbolValue = new Lazy <JsSymbolConstructor>(() =>
            {
                var global = m_globalValue.Value;
                return(global.GetProperty <JsSymbolConstructor>("Symbol"));
            });

            m_promiseTaskQueue    = taskQueue;
            m_moduleRecordFactory = moduleRecordFactory ?? throw new ArgumentNullException(nameof(moduleRecordFactory));

            //Set the event that will be called prior to the engine collecting the context.
            JavaScriptObjectBeforeCollectCallback beforeCollectCallback = (IntPtr handle, IntPtr callbackState) =>
            {
                OnBeforeCollect(handle, callbackState);
            };

            m_beforeCollectCallbackDelegateHandle = GCHandle.Alloc(beforeCollectCallback);
            Engine.JsSetObjectBeforeCollectCallback(contextHandle, IntPtr.Zero, beforeCollectCallback);
        }
Example #8
0
        /// <summary>
        /// Creates a new JavaScript reference wrapper with the specified engine and JavaScript Reference.
        /// </summary>
        /// <param name="engine"></param>
        /// <param name="javaScriptReference"></param>
        protected BaristaObject(IJavaScriptEngine engine, T javaScriptReference)
        {
            if (javaScriptReference == null || javaScriptReference.IsClosed || javaScriptReference.IsInvalid)
            {
                throw new ArgumentNullException(nameof(javaScriptReference));
            }

            m_javaScriptEngine    = engine ?? throw new ArgumentNullException(nameof(engine));
            m_javaScriptReference = javaScriptReference;
        }
Example #9
0
        public JsIterator(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle valueHandle, IEnumerator enumerator)
            : base(engine, context, valueHandle)
        {
            m_enumerator = enumerator ?? throw new ArgumentNullException(nameof(enumerator));

            var fnNext = context.CreateFunction(new Func <JsObject, JsObject>((thisObj) =>
            {
                return(Next());
            }));

            SetProperty("next", fnNext);
        }
Example #10
0
        public ScriptSource(IJavaScriptEngine engine, string script, string sourceUrl = "[eval source]")
        {
            if (engine == null)
            {
                throw new ArgumentNullException(nameof(engine));
            }
            m_script = script ?? throw new ArgumentNullException(nameof(script));

            m_ptrScript       = Marshal.StringToHGlobalAnsi(script);
            m_scriptHandle    = engine.JsCreateExternalArrayBuffer(m_ptrScript, (uint)script.Length, null, IntPtr.Zero);
            m_sourceUrlHandle = engine.JsCreateString(sourceUrl, (ulong)sourceUrl.Length);
            m_sourceContext   = JavaScriptSourceContext.GetNextSourceContext();

            m_fnScript = engine.JsParse(m_scriptHandle, m_sourceContext, m_sourceUrlHandle, JavaScriptParseScriptAttributes.None);
        }
Example #11
0
        /// <summary>
        ///     Gets a property id object for the specified property name.
        /// </summary>
        /// <param name="engine">
        ///     The JavaScript engine to use.
        /// </param>
        /// <param name="name">
        ///     The name of the property.
        /// </param>
        /// <returns>The property ID in this runtime for the given name.</returns>
        public static JsPropertyId FromString(IJavaScriptEngine engine, string name)
        {
            if (engine == null)
            {
                throw new ArgumentNullException(nameof(engine));
            }

            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            var propertyHandle = engine.JsCreatePropertyId(name, (ulong)name.Length);

            return(new JsPropertyId(engine, propertyHandle));
        }
Example #12
0
        public static void SetGlobalVariable(this IJavaScriptEngine jsrt, string name, JavaScriptValueSafeHandle value)
        {
            var globalObjectHandle = jsrt.JsGetGlobalObject();
            var propertyIdHandle   = default(JavaScriptPropertyIdSafeHandle);

            try
            {
                propertyIdHandle = jsrt.JsCreatePropertyId(name, (ulong)name.Length);
                jsrt.JsSetProperty(globalObjectHandle, propertyIdHandle, value, true);
            }
            finally
            {
                if (propertyIdHandle != default(JavaScriptPropertyIdSafeHandle))
                {
                    propertyIdHandle.Dispose();
                }
                globalObjectHandle.Dispose();
            }
        }
Example #13
0
        public static string GetStringUtf8(this IJavaScriptEngine jsrt, JavaScriptValueSafeHandle stringHandle, bool autoConvert = false)
        {
            bool stringHandleWasCreated = false;

            if (stringHandle == null || stringHandle == JavaScriptValueSafeHandle.Invalid)
            {
                throw new ArgumentNullException(nameof(stringHandle));
            }

            //If Auto Convert is specified, ensure that the type is a string, otherwise convert it.
            if (autoConvert)
            {
                var handleValueType = jsrt.JsGetValueType(stringHandle);

                if (handleValueType != JsValueType.String)
                {
                    var convertedToStringHandle = jsrt.JsConvertValueToString(stringHandle);

                    stringHandle           = convertedToStringHandle;
                    stringHandleWasCreated = true;
                }
            }

            //Get the size
            var size = jsrt.JsCopyString(stringHandle, null, 0);

            if ((int)size > int.MaxValue)
            {
                throw new OutOfMemoryException("Exceeded maximum string length.");
            }

            byte[] result  = new byte[(int)size];
            var    written = jsrt.JsCopyString(stringHandle, result, (ulong)result.Length);

            var strResult = Encoding.UTF8.GetString(result, 0, result.Length);

            if (stringHandleWasCreated)
            {
                stringHandle.Dispose();
            }

            return(strResult);
        }
Example #14
0
        /// <summary>
        /// Executes a script, automatically storing the script value within an ExternalArrayBuffer.
        /// </summary>
        /// <remarks>
        ///     This extension method exists for simplicity.
        /// </remarks>
        /// <param name="jsrt"></param>
        /// <param name="script"></param>
        /// <param name="sourceContext"></param>
        /// <param name="sourceUrl"></param>
        /// <param name="parseAttributes"></param>
        /// <param name="result"></param>
        /// <returns>A JavaScriptValueSafeHandle containing the result.</returns>
        public static JavaScriptValueSafeHandle JsRunScript(this IJavaScriptEngine jsrt, string script, JavaScriptSourceContext sourceContext = default(JavaScriptSourceContext), string sourceUrl = null, JavaScriptParseScriptAttributes parseAttributes = JavaScriptParseScriptAttributes.None)
        {
            var ptrScript = Marshal.StringToHGlobalAnsi(script);

            JavaScriptObjectFinalizeCallback callback = (IntPtr ptr) =>
            {
                //Release pinned string.
                Marshal.FreeHGlobal(ptrScript);
            };

            var scriptHandle = jsrt.JsCreateExternalArrayBuffer(ptrScript, (uint)script.Length, callback, IntPtr.Zero);

            if (sourceContext == default(JavaScriptSourceContext))
            {
                sourceContext = JavaScriptSourceContext.None;
            }

            JavaScriptValueSafeHandle sourceUrlHandle;

            if (string.IsNullOrWhiteSpace(sourceUrl))
            {
                sourceUrl = "[eval code]";
            }

            sourceUrlHandle = jsrt.JsCreateString(EvalSourceUrl, (ulong)EvalSourceUrl.Length);

            if (parseAttributes == default(JavaScriptParseScriptAttributes))
            {
                parseAttributes = JavaScriptParseScriptAttributes.None;
            }

            try
            {
                return(jsrt.JsRun(scriptHandle, sourceContext, sourceUrlHandle, parseAttributes));
            }
            finally
            {
                //Release variables created during this operation.
                sourceUrlHandle.Dispose();
                scriptHandle.Dispose();
            }
        }
Example #15
0
        /// <summary>
        /// Creates a new instance of a Barista Runtime.
        /// </summary>
        public BaristaRuntime(IJavaScriptEngine engine, IBaristaContextFactory contextFactory, JavaScriptRuntimeSafeHandle runtimeHandle)
            : base(engine, runtimeHandle)
        {
            m_contextFactory = contextFactory ?? throw new ArgumentNullException(nameof(contextFactory));

            JavaScriptMemoryAllocationCallback runtimeMemoryAllocationChanging = (IntPtr callbackState, JavaScriptMemoryEventType allocationEvent, UIntPtr allocationSize) =>
            {
                try
                {
                    return(OnRuntimeMemoryAllocationChanging(callbackState, allocationEvent, allocationSize));
                }
                catch
                {
                    //Do Nothing.
                    return(true);
                }
            };

            m_runtimeMemoryAllocationChangingDelegateHandle = GCHandle.Alloc(runtimeMemoryAllocationChanging);
            Engine.JsSetRuntimeMemoryAllocationCallback(runtimeHandle, IntPtr.Zero, runtimeMemoryAllocationChanging);

            JavaScriptBeforeCollectCallback beforeCollectCallback = (IntPtr callbackState) =>
            {
                try
                {
                    OnBeforeCollect(IntPtr.Zero, callbackState);
                }
                catch
                {
                    //Do Nothing.
                }
            };

            m_beforeCollectCallbackDelegateHandle = GCHandle.Alloc(beforeCollectCallback);
            Engine.JsSetRuntimeBeforeCollectCallback(runtimeHandle, IntPtr.Zero, beforeCollectCallback);
        }
 protected JsExternalArrayBuffer(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle valueHandle)
     : base(engine, context, valueHandle)
 {
 }
Example #17
0
 public JsPromiseConstructor(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle valueHandle)
     : base(engine, context, valueHandle)
 {
 }
Example #18
0
 public JsString(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle valueHandle)
     : base(engine, context, valueHandle)
 {
 }
Example #19
0
        public JavaScriptReference_Facts()
        {
            var chakraCoreFactory = new ChakraCoreFactory();

            Engine = chakraCoreFactory.CreateJavaScriptEngine();
        }
Example #20
0
 public JsUndefined(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle handle)
     : base(engine, context, handle)
 {
 }
        public IDebugJavaScriptEngine_Facts()
        {
            var chakraCoreFactory = new ChakraCoreFactory();

            Engine = chakraCoreFactory.CreateJavaScriptEngine();
        }
 public void RecycleEngine(IJavaScriptEngine engine)
 {
     throw new NotImplementedException();
 }
 public BaristaValueFactory(IJavaScriptEngine engine, BaristaContext context)
 {
     m_engine    = engine ?? throw new ArgumentNullException(nameof(engine));
     m_context   = context ?? throw new ArgumentNullException(nameof(context));
     m_valuePool = new BaristaObjectPool <JsValue, JavaScriptValueSafeHandle>();
 }
Example #24
0
 public JsArrayBuffer(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle valueHandle)
     : base(engine, context, valueHandle)
 {
 }
Example #25
0
 public JsExternalObject(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle valueHandle, GCHandle objHandle)
     : base(engine, context, valueHandle)
 {
     m_objHandle = objHandle;
 }
 public BaristaRuntimeFactory(IJavaScriptEngine engine, IServiceProvider serviceProvider)
 {
     m_engine          = engine ?? throw new ArgumentNullException(nameof(engine));
     m_serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
 }
Example #27
0
 /// <summary>
 /// Creates a new JavaScript Property Id
 /// </summary>
 public JsPropertyId(IJavaScriptEngine engine, JavaScriptPropertyIdSafeHandle propertyIdHandle)
     : base(engine, propertyIdHandle)
 {
 }
 public BaristaContextFactory(IJavaScriptEngine engine, IServiceProvider serviceProvider)
 {
     m_engine          = engine ?? throw new ArgumentNullException(nameof(engine));
     m_serviceProvider = serviceProvider;
     m_contextPool     = new BaristaObjectPool <BaristaContext, JavaScriptContextSafeHandle>();
 }
 public ExecuteJavaScriptCommand(IJavaScriptEngine engine, IApplicationReader reader)
 {
     _engine = engine;
     _reader = reader;
 }
Example #30
0
 public JsTypedArray(IJavaScriptEngine engine, BaristaContext context, JavaScriptValueSafeHandle valueHandle)
     : base(engine, context, valueHandle)
 {
     m_arrayInfo = new Lazy <JavaScriptTypedArrayInfo>(GetTypedArrayInfo);
 }